AutoScalingCtrl.java 14.4 KB
package com.ui.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ui.cloud.AwsModifyScalingGroupReq;
import com.ui.cloud.CommAutoModifyScalingGroupReq;
import com.ui.cloud.DeployProjectCloud;
import com.ui.cloud.QcloudModifyScalingGroupReq;
import com.ui.cloud.task.AutoScalingFactory;
import com.ui.contants.HttpUriContants;
import com.ui.http.HttpRestClient;
import com.ui.model.BaseResponse;
import com.ui.model.domain.BuildMessage;
import com.ui.model.req.BuildRequest;
import com.ui.model.req.User;
import com.ui.project.ProjectEnvironment;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 亚马逊云 腾讯云 伸缩组操作
 * Created by xh on 2017/5/9.
 */
@Controller
@RequestMapping("/autoScalingTool")
public class AutoScalingCtrl {

    @Autowired
    private HttpRestClient httpClient;

    @Autowired
    private AutoScalingFactory autoScalingFactory;

    /**
     * 跳转到页面
     * @param model
     * @return
     */
    @RequestMapping("/toautoscalingpage")
    public ModelAndView toAutoScalingPage(Model model) {
        return new ModelAndView("manager/autoscaling");
    }

    /**
     * 显示配置信息
     * @param cloudType 云类型 1:AWS 2:QCLOUD
     * @return
     */
    @RequestMapping("/getAutoScalingGroups")
    @ResponseBody
    public BaseResponse<?> getAutoScalingGroups(int cloudType) {
       return autoScalingFactory.getAutoScalingGroups(cloudType);
    }


    /**
     * 显示配置信息
     * @param cloudType 云类型 1:AWS 2:QCLOUD
     * @return
     */
    @RequestMapping("/autoscalingconfig")
    @ResponseBody
    public BaseResponse<?> autoScalingConfig(int cloudType) {
        BaseResponse<?> response = httpClient.defaultPost(
                HttpUriContants.GET_CLOUD_AUTOSCALING_CONFIG + "?cloudType="+cloudType, null,
                BaseResponse.class);
        return response;
    }

    /**
     * 显示配置信息
     * @param qCloudReq 修改的相关参数,暂时只用了腾讯云的,日后考虑亚马逊的
     * @return
     */
    @RequestMapping("/modifyScalingGroup")
    @ResponseBody
    public BaseResponse<?> modifyScalingGroup(QcloudModifyScalingGroupReq qCloudReq, int cloudType) {
        CommAutoModifyScalingGroupReq req = new CommAutoModifyScalingGroupReq();
        req.setCloudType(cloudType);
        if(1==cloudType){
            AwsModifyScalingGroupReq awsReq=new AwsModifyScalingGroupReq();
            awsReq.setScalingGroupName(qCloudReq.getScalingGroupName());
            awsReq.setMaxSize(qCloudReq.getMaxSize());
            awsReq.setMinSize(qCloudReq.getMinSize());
            awsReq.setDesiredCapacity(qCloudReq.getDesiredCapacity());
            req.setAwsModifyScalingGroupReq(awsReq);
        }else{
            req.setQCloudParms(qCloudReq);
        }
        BaseResponse<?> response = httpClient.defaultPost(
                HttpUriContants.GET_CLOUD_MODIFY_SCALING_GROUP, req, BaseResponse.class);
        return response;
    }

    /**
     * 腾讯云:修改伸缩组后的下一个流程是查询伸缩活动
     * 亚马逊云:修改伸缩组后的下一个流程待定,因为不清楚
     * @param scalingGroupId 待查询的伸缩组Id
     * @param startTime 开始时间,如果不填,则默认是当前时间前10秒之后发生的活动
     * @return
     */
    @RequestMapping("/describeScalingActivity")
    @ResponseBody
    public BaseResponse<?> describeScalingActivity(int cloudType,String scalingGroupName,String scalingGroupId, String startTime){
        /*String url = "";
        if(1==cloudType){
            url= String.format(HttpUriContants.GET_CLOUD_DESCRIBE_SCALING_ACTIVITY+"?cloudType=1&scalingGroupName=%s",scalingGroupName);
        }else if(2==cloudType){
            url= String.format(HttpUriContants.GET_CLOUD_DESCRIBE_SCALING_ACTIVITY+"?cloudType=2&scalingGroupId=%s&startTime=%s",scalingGroupId,startTime);
        }
        BaseResponse<?> response = httpClient.defaultPost(url, null, BaseResponse.class);*/

        String url= String.format(HttpUriContants.GET_CLOUD_DESCRIBE_SCALING_ACTIVITY+"?cloudType=%d&scalingGroupName=%s",cloudType,scalingGroupName);
        BaseResponse<?> response = httpClient.defaultPost(url, null, BaseResponse.class);
        return response;
    }

    /**
     * 腾讯云:根据实例id获取内网ip
     * 亚马逊云待定:不清楚流程
     * @param ids 实例id集合
     * @return
     */
    @RequestMapping("/getQcloudDescribeInstances")
    @ResponseBody
    public BaseResponse<?> getQcloudDescribeInstances(String ids){
        String url = String.format(HttpUriContants.GET_QCLOUD_DESCRIBE_INSTANCES+"?instanceIds=%s",ids);
        BaseResponse<?> response = httpClient.defaultPost(url, null, BaseResponse.class);
        return response;
    }

    /**
     * 腾讯云:根据实例id获取内网ip
     * 亚马逊云待定:不清楚流程
     * @param groupId 伸缩组id
     * @return
     */
    @RequestMapping("/getIpsByScalingGroupId")
    @ResponseBody
    public BaseResponse<?> getIpsByScalingGroupId(int cloudType ,String groupName,String groupId){
        String url = String.format(HttpUriContants.GET_QCLOUD_INSTANCES_IP_BY_SCALINGGROUPID+"?cloudType=%d&groupName=%s&groupId=%s",cloudType,groupName,groupId);
        BaseResponse<?> response = httpClient.defaultPost(url, null, BaseResponse.class);
        return response;
    }


    /**
     * 系统发布的group下的所有项目
     */
    @RequestMapping("/getDeployProjectNames")
    @ResponseBody
    public BaseResponse<?> getDeployProjectNames(String environment,String scalingGroupName )
    {
        BaseResponse t=new BaseResponse();
        t.setData(AutoScalingGroupProjectConstant.getProjectNames(environment, scalingGroupName));
        return t;
    }

    /**
     * 系统发布
     * @param session
     * @param projectName 项目名称
     * @param ips 所需发布的ip集合 ,分割
     * @param branch 分支名称
     * @param environment 发布环境 此为qcloud
     * @return
     */
    @RequestMapping("/deployCloudProject")
    @ResponseBody
    public BaseResponse<?> deployCloudProject(HttpSession session, String projectName, String ips, String branch, String environment){
        BaseResponse response = null;

        try{
            User user = (User) session.getAttribute("user");
            List<BuildMessage> list = new ArrayList<>();
            BuildRequest buildRequest = new BuildRequest();
            //分支名称
            buildRequest.setBranch(branch);
            //登陆用户
            buildRequest.setUser(user.getName());
            //设置需要发布的ip
            buildRequest.setHost(ips);
            //发布环境
            buildRequest.setEnvironment(environment);
            //不存在回滚文件
            //操作类型
            buildRequest.setOperate("Deploy");
            //关联工单
            buildRequest.setWorkid("release0");
            //项目名称
            buildRequest.setProject(AutoScalingGroupProjectConstant.getProjectNames(environment, projectName));

            String messageids = "";
            BuildMessage buildMessage = httpClient.post(ProjectEnvironment.getUrl(environment) + "build", buildRequest, BuildMessage.class);
            if (buildMessage != null) {
                list.add(buildMessage);
                messageids =  buildMessage.getId() + ",";
            }
            DeployProjectCloud deploy = new DeployProjectCloud();
            deploy.setMessageids(messageids);
            deploy.setMessageList(list);
            response = new BaseResponse();
            response.setData(deploy);
        }catch (Exception e){
            response.setCode(300);
            response.setMessage(e.getMessage());
        }

        return response;
    }

    /**
     * 获取执行结果
     *
     * @param messageid  qcloud_1233 或者 aws_1234
     * @return
     */
    @RequestMapping(value = "/getBuildMsgAfterDeploy", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse getBuildMsgAfterDeploy(String messageid, String project) {
        try {
            BaseResponse response=new BaseResponse();
            String cloudType=messageid.split("_")[0];
            String[] projectArray= AutoScalingGroupProjectConstant.getProjectNames(cloudType,project).split(",");
            StringBuilder rtnMsg=new StringBuilder();
            Boolean allOK=true;
            String desc="";
            for(String pro:projectArray){
                Map<String, String> map = new HashMap<>();
                map.put("messageid", messageid);
                map.put("project", pro);

                //rtnMsg.append("project is "+pro+"<br>");
                String buildInfoJsonString=httpClient.get(ProjectEnvironment.getUrl(messageid.split("_")[0]) + "getbuildmsg", String.class, map);
                if(StringUtils.isNotBlank(buildInfoJsonString)){
                    JSONObject jo=JSON.parseObject(buildInfoJsonString);
                    Integer code=(Integer)jo.get("code");
                    if(code==2|| code == 3 || code == 4){
                        if(desc.length()>0){
                            desc+=";";
                        }
                        desc += (pro+"-->"+code);
                    }else{
                        allOK=false;
                    }
                }
            }
           /* Map<String,Object> dat=new HashMap<>();
            dat.put("allOK",allOK);
            dat.put("desc",desc);*/
            response.setMessage(desc);
            response.setData(allOK);
            return response;
        } catch (Exception ex) {
            return new BaseResponse();
        }
    }

    /**
     * 项目发布后集成测试
     * @param cloudType 云类型 1:AWS 2:QCLOUD
     * @param projectName 项目名称
     * @param ips 部署在哪台服务器上,内网ip集合, ,分割
     * @return
     */
    @RequestMapping("/integrationTest")
    @ResponseBody
    public BaseResponse<?> integrationTest(int cloudType, String projectName, String ips){
        String cloudTypeStr="";
        if(1==cloudType){
            cloudTypeStr="aws";
        }else if(2==cloudType){
            cloudTypeStr="qcloud";
        }
        String url = String.format(HttpUriContants.GET_CLOUD_INTEGRATION_TEST+"?cloudType=%s&projectName=%s&ips=%s",cloudType, AutoScalingGroupProjectConstant.getProjectNames(cloudTypeStr,projectName), ips);
        BaseResponse<?> response = httpClient.defaultPost(url, null, BaseResponse.class);
        return response;
    }


    /**
     * 自动伸缩后,修改ip,ip从云管理中心重新获取
     * http://git.yoho.cn/yohoops/auto_deploy.git
     * @param cloudType 云类型 1:AWS 2:QCLOUD
     * @param projectName 项目名称
     * @param oldInstanceIps 伸缩之前的实例ip
     * @param upDownFlag   伸缩标志 :up  down
     * @return
     */
    @RequestMapping("/updateIpToGit")
    @ResponseBody
    public BaseResponse<?> updateIpToGit(int cloudType, String projectName, String scalingGroupId,String oldInstanceIps,String newInstanceIps,String upDownFlag){
        String cloudTypeStr="";
        if(1==cloudType){
            cloudTypeStr="aws";
        }else if(2==cloudType){
            cloudTypeStr="qcloud";
        }

        //获取新的伸缩实例ip
        /*BaseResponse newInstanceIpsResponse=this.getIpsByScalingGroupId(cloudType,projectName,scalingGroupId);
        if(newInstanceIpsResponse==null||newInstanceIpsResponse.getCode()!=200){
            newInstanceIpsResponse.setMessage("获取伸缩组新的实例ip失败!");
            return newInstanceIpsResponse;
        }*/


        String projectNameArray[]= AutoScalingGroupProjectConstant.getProjectNames(cloudTypeStr,projectName).split(",");
        StringBuilder sb=new StringBuilder();
        for(String project:projectNameArray){
            String url = String.format(HttpUriContants.GET_CLOUD_UPDATE_IP_TO_GIT+"?cloudType=%d&projectName=%s&scalingGroupId=%s",cloudType,project, scalingGroupId);
            BaseResponse<?> responseTmp = httpClient.defaultPost(url, null, BaseResponse.class);
            if(responseTmp==null||responseTmp.getCode()!=200){
                responseTmp.setMessage(responseTmp.getMessage()+"**********project:"+project);
                return responseTmp;
            }else{
                sb.append(responseTmp.getMessage()+"**********project:"+project);
            }
        }

        if("gateway".equals(projectName)){
            //List<String> newInstanceIps=(List<String>)newInstanceIpsResponse.getData();
            List<String> newInstanceIpList=null;
            if(StringUtils.isNotBlank(newInstanceIps)){
                newInstanceIpList=Arrays.asList(newInstanceIps.split(","));
            }else{
                newInstanceIpList=new ArrayList<String>();
            }
            if("up".equals(upDownFlag)){
                List<String> oldIps= Arrays.asList(oldInstanceIps.split(","));
                for(String strIP:newInstanceIpList){
                    if(!oldIps.contains(strIP)&&StringUtils.isNotBlank(strIP)){
                        String url = String.format(HttpUriContants.GET_CLOUD_UPDATE_GATEWAY_CHANGE_UPSTREAM+"?operate=%s&cloudTypeStr=%s&ip=%s","add",cloudTypeStr, strIP);
                        BaseResponse<?> responseTmp = httpClient.defaultPost(url, null, BaseResponse.class);
                        sb.append("gateway upstream add "+strIP);
                    }
                }

            }else if("down".equals(upDownFlag)){
                List<String> oldIps= Arrays.asList(oldInstanceIps.split(","));
                for(String strIP:oldIps){
                    if(!newInstanceIpList.contains(strIP)){
                        String url = String.format(HttpUriContants.GET_CLOUD_UPDATE_GATEWAY_CHANGE_UPSTREAM+"?operate=%s&cloudTypeStr=%s&ip=%s","del",cloudTypeStr, strIP);
                        BaseResponse<?> responseTmp = httpClient.defaultPost(url, null, BaseResponse.class);
                        sb.append("gateway upstream del "+strIP);
                    }
                }
            }
        }
        BaseResponse<?> response=new BaseResponse();
        response.setMessage(sb.toString());
        return response;
    }
}