NodeBuildCtrl.java 13.1 KB
package com.ui.ctrl;

import com.ui.contants.HttpUriContants;
import com.ui.ctrl.util.ReleaseCheck;
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 org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("nodeBuild")
public class NodeBuildCtrl {
    Logger log = LoggerFactory.getLogger(NodeBuildCtrl.class);

    @Autowired
    private HttpRestClient httpRestClient;

    @Autowired
    private ReleaseCheck releaseCheck;

    @Autowired
    private Pch5SwitchCtrl pch5SwitchCtrl;

    private final String AZ2_Auto_Switch_Online_CHECK="az2AutoSwitchOnlineCheck";

    private String URL = "http://172.31.16.167:8883/node/";

    @RequestMapping("/toProject")
    public ModelAndView toProject(Model model,String workJobId) {
        if(StringUtils.isNotBlank(workJobId)){
            BaseResponse response = httpRestClient.defaultGet(HttpUriContants.GET_RELEASEWORKJOB_ID + "?id=" + workJobId, BaseResponse.class);
            if(response!=null&&response.getCode()==200&&response.getData()!=null){
                Map map=(Map)response.getData();
                String releaseWorkJob_environment=(String)(map.get("environment")==null?"":map.get("environment"));

                if(releaseWorkJob_environment!=null&&releaseWorkJob_environment.length()>0&&!releaseWorkJob_environment.endsWith(",")){
                    releaseWorkJob_environment+=",";
                }
                String releaseWorkJob_project =  map.get("project")==null?"":(String)map.get("project");
                if(releaseWorkJob_project!=null&&releaseWorkJob_project.length()>0&&!releaseWorkJob_project.endsWith(",")){
                    releaseWorkJob_project += ",";
                }
                int releaseWorkJob_nodeProjectCount=0;
                for(String tmp:releaseWorkJob_project.split(",")){
                    if(tmp!=null&&tmp.length()>0){
                        releaseWorkJob_nodeProjectCount++;
                    }
                }
                model.addAttribute("releaseWorkJob_nodeProjectCount", releaseWorkJob_nodeProjectCount);
                model.addAttribute("releaseWorkJob_environment", releaseWorkJob_environment);
                model.addAttribute("releaseWorkJob_branch", map.get("branch")==null?"":(String)map.get("branch"));
                model.addAttribute("releaseWorkJob_project",releaseWorkJob_project);
                model.addAttribute("releaseWorkJob_id", workJobId);
            }
        }

        return new ModelAndView("project/node_project");
    }

    /**
     * 获取所有项目
     *
     * @return
     */
    @RequestMapping(value = "getProjects", method = RequestMethod.POST)
    @ResponseBody
    public String getProjects() {
        try {
            return httpRestClient.get(URL + "getProjects", String.class, null);
            /*String tt= "[{\"exeOrder\":0,\"name\":\"YOHOBUY-Portal-fe2\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBUY-Shop-fe2\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBUY-shop-fe\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBLK-WWW\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBUY-WAP-NODE\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBUY-PC-NODE\",\"group\":\"Node项目\",\"order\":\"1\"},{\"exeOrder\":0,\"name\":\"YOHOBLK-WAP\",\"group\":\"Node项目\",\"order\":\"1\"}]";
            return JSONArray.toJSONString(JSON.parseArray(tt));*/
        } catch (Exception ex) {
            return "failed";
        }
    }

    /**
     * 根据项目名字获取项目想起
     * 获取所有项目
     *
     * @return
     */
    @RequestMapping(value = "getProject", method = RequestMethod.POST)
    @ResponseBody
    public String getProjectByName(String name) {
        try {
            return httpRestClient.get(URL + "getProject?name="+name , String.class, null);
            //return "{\"project\":\"yohobuy-node\",\"name\":\"YOHOBUY-PC-NODE\",\"group\":\"Node项目\",\"groupid\":1,\"envs\":[{\"name\":\"qcloud_gray\",\"host_ips\":[\"10.66.101.9\"]},{\"name\":\"az1\",\"host_ips\":[\"10.66.1.6\",\"10.66.1.7\",\"10.66.1.8\"]},{\"name\":\"az2\",\"host_ips\":[\"10.66.103.6\",\"10.66.103.7\"]},{\"name\":\"az1-az2\",\"host_ips\":[\"10.66.1.6\",\"10.66.1.7\",\"10.66.1.8\",\"10.66.103.6\",\"10.66.103.7\"]}]}";
        } catch (Exception ex) {
            return "failed";
        }
    }

    /**
     * 发布前校验
     *
     * @return
     */
    @RequestMapping(value = "check")
    @ResponseBody
    public BaseResponse check(String operate_name,String project,String branch, String environment,String workid,HttpSession httpSession) {
        BaseResponse rtnResponse=releaseCheck.check(workid,httpSession);
        if(200!=rtnResponse.getCode()){
            return rtnResponse;
        }


        if(environment.contains("az")&&"Deploy".equalsIgnoreCase(operate_name)){
            //获取az2灰度情况
            BaseResponse<Boolean> checkGrayResponse = httpRestClient.defaultGet("/pch5Switch/queryAz2InGray",BaseResponse.class);
            if (checkGrayResponse==null||checkGrayResponse.getCode() != 200){
                rtnResponse.setCode(201);
                rtnResponse.setMessage("检查az2灰度失败");
                return rtnResponse;
            }
            boolean  az2InGray=checkGrayResponse.getData();

            //检查分支和可用区的冲突
            if(environment.contains("az1")){
                if(!"master".equals(branch)){
                    rtnResponse.setCode(201);
                    rtnResponse.setMessage("az1区域只能发布master分支");
                    return rtnResponse;
                }
            }else{
                //单独发布az2,环境可能还有aws等(其它不需要校验的项目)
                if(environment.contains("az2")){
                    if("master".equals(branch)){
                        //z2区如果发master分支,需要检查所有项目(现在是3个:YOHOBUY-WAP-NODE  , YOHOBUY-PC-NODE  ,YOHOBLK-WAP)
                        //如果所有项目最近一次发送成功都是master分支,则自动关闭灰度环境
                        if(az2InGray){
                            Map<String,String> releaseRecordMap=this.getReleaseRecordMap();
                            if(releaseRecordMap!=null&&releaseRecordMap.size()>0){
                                rtnResponse.setData(AZ2_Auto_Switch_Online_CHECK);
                                for(Map.Entry<String,String>  entry:releaseRecordMap.entrySet()){
                                    if(project.equals(entry.getKey())){
                                        continue;
                                    }
                                    if(!"master".equals(entry.getValue())){
                                        rtnResponse.setData("");//其它项目最近发布的是非master,不需要切换
                                        break;
                                    }
                                }
                            }
                        }else{
                            rtnResponse.setData("az2AlreadyOnline");
                        }
                    }else{
                        //az2区如果发非master分支,发布之前自动切换到灰度环境
                        if(az2InGray){
                            rtnResponse.setData("az2AlreadyInGray");
                        }else{
                            rtnResponse.setData("az2AutoSwitchGray");
                        }

                    }
                }
            }
        }

        return rtnResponse;

    }

    @RequestMapping(value = "getReleaseRecordMap")
    @ResponseBody
    public Map<String,String> getReleaseRecordMap(){
        BaseResponse<Map> releaseRecordAz2Response = httpRestClient.defaultGet("/pch5Switch/getAzProjectLatestReleaseHistoryMap",BaseResponse.class);
        if(releaseRecordAz2Response!=null&&200==releaseRecordAz2Response.getCode()){
            Map<String,String> releaseRecordMap=releaseRecordAz2Response.getData();
            return releaseRecordMap;
        }
        return null;
    }

    /**
     * 执行任务
     *
     * @return
     */
    @RequestMapping(value = "build", method = RequestMethod.POST)
    public ModelAndView build(String workid_name,String project_name, String environment_name,
                              String operate_name, String branch_name, String rollbackfile_name, String hosts_name
            , boolean force_name, Model model, HttpSession session,String az2AutoSwitchOnlineCheck) {
        try {
            User user = (User) session.getAttribute("user");
            BaseResponse checkResponse=releaseCheck.checkAndUpdate(workid_name,operate_name,user.getName());
            if(200!=checkResponse.getCode()){
                model.addAttribute("environment_name", checkResponse.getMessage());
                return new ModelAndView("project/node_project_build");
            }
            List<BuildMessage> list = new ArrayList<>();
            BuildRequest buildRequest = new BuildRequest();
            buildRequest.setBranch(branch_name);
            buildRequest.setUser(user.getName());
            buildRequest.setEnvironment(environment_name);
            buildRequest.setRollbackfile(rollbackfile_name);
            buildRequest.setOperate(operate_name);
            buildRequest.setHost(hosts_name);
            buildRequest.setIsForce(String.valueOf(force_name));
            buildRequest.setWorkid(workid_name);

            String messageids = "";
            buildRequest.setProject(project_name);
            BuildMessage buildMessage = httpRestClient.post(URL + "build", buildRequest, BuildMessage.class);
            if (buildMessage != null) {
                list.add(buildMessage);
                messageids = messageids + buildMessage.getId() + ",";
            }
            model.addAttribute("environment_name", environment_name);
            model.addAttribute("operate_name", operate_name);
            model.addAttribute("branch_name", branch_name);
            model.addAttribute("rollbackfile_name", rollbackfile_name);
            model.addAttribute("messageids", messageids);
            model.addAttribute("messageList", list);
            model.addAttribute("hosts_name", hosts_name);
            model.addAttribute("az2AutoSwitchOnlineCheck", az2AutoSwitchOnlineCheck);

        } catch (Exception ex) {
            log.error("build", ex.toString());
        }
        return new ModelAndView("project/node_project_build");
    }

    /**
     * 切换az2区域
     *
     * @return
     */
    @RequestMapping(value = "switchAz2", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse switchAz2(String onlineOrGray) {
        return pch5SwitchCtrl.switchAz2(onlineOrGray);
    }

    /**
     * 切换az2区域到online
     * 检测符合条件之后才切换
     *
     * @return
     */
    @RequestMapping(value = "switchAz2ToOnLineCheck")
    @ResponseBody
    public BaseResponse switchAz2ToOnLineCheck(String environment_name,
                                               String operate_name, String branch_name) {
        Map<String,String> releaseRecordMap=this.getReleaseRecordMap();
        boolean switchFlag=false;
        if(releaseRecordMap!=null&&releaseRecordMap.size()>0){
            for(Map.Entry<String,String> entry:releaseRecordMap.entrySet()){
                if(!"master".equals(entry.getValue())){
                    switchFlag=false;
                    break;
                }else{
                    switchFlag=true;
                }
            }
        }
        return new BaseResponse(switchFlag);

    }

    /**
     * 获取执行结果
     *
     * @param messageid
     * @return
     */
    @RequestMapping(value = "getbuildmsg", method = RequestMethod.POST)
    @ResponseBody
    public String getbuildmsg(String messageid, String project) {
        return releaseCheck.getbuildmsg(URL,messageid,project);
    }

    @RequestMapping(value = "cancelBuild")
    @ResponseBody
    public String cancelBuild(String id) {
        return releaseCheck.cancelBuild(URL,id);
    }

    @RequestMapping(value = "rollbackList", method = RequestMethod.POST)
    @ResponseBody
    public String rollbackList(String project, String environment) {
        return releaseCheck.rollbackList(URL,project,environment);
    }

    @RequestMapping(value = "refreshGit", method = RequestMethod.POST)
    @ResponseBody
    public String refreshGit() {
        return releaseCheck.refreshGit(URL);
    }


}