ProjectBuildCtrl.java 30.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
package com.ui.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ui.cloud.task.ProjectsLoader;
import com.ui.contants.AlarmGroupContants;
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.*;
import com.ui.project.Project;
import com.ui.project.ProjectEnvironment;
import com.ui.project.ProjectMutex;
import com.ui.project.ProjectOnlineResponse;
import lombok.Data;
import org.apache.commons.lang.RandomStringUtils;
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.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("project")
public class ProjectBuildCtrl {
    Logger log = LoggerFactory.getLogger(ProjectBuildCtrl.class);
    //需要特殊处理的项目
    private final List<String> lb_proejct_list=new ArrayList<String>() {{
        //add("yoho-search-service");
        //add("uic");
    }};


    @Autowired
    private ProjectsLoader projectsLoader;

    @Autowired
    private HttpRestClient httpRestClient;

    @Autowired
    private ReleaseCheck releaseCheck;

    @RequestMapping("/toOm")
    public ModelAndView toOm() {
        return new ModelAndView("project/om");
    }

    @RequestMapping("/toNewOm")
    public ModelAndView toOmNew() {
        return new ModelAndView("project/newOm");
    }

    @RequestMapping("/toNode")
    public ModelAndView toNode() {
        return new ModelAndView("project/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();
                List<String> releaseWorkJob_environment_list=new ArrayList<>();
                String releaseWorkJob_environment=(String)(map.get("environment")==null?"":map.get("environment"));
                int releaseWorkJob_enviCount=0;
                if(releaseWorkJob_environment!=null&&releaseWorkJob_environment.length()>0&&!releaseWorkJob_environment.endsWith(",")){
                    releaseWorkJob_environment+=",";
                }
                for(String tmp:releaseWorkJob_environment.split(",")){
                    if(tmp!=null&&tmp.trim().length()>0){
                        releaseWorkJob_enviCount++;
                        releaseWorkJob_environment_list.add(tmp.trim());
                    }
                }

                String releaseWorkJob_project =  map.get("project")==null?"":(String)map.get("project");
                if(releaseWorkJob_project!=null&&releaseWorkJob_project.length()>0&&!releaseWorkJob_project.endsWith(",")){
                    releaseWorkJob_project += ",";
                }
                model.addAttribute("releaseWorkJob_enviCount", releaseWorkJob_enviCount);
                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);
                model.addAttribute("releaseWorkJob_environment_list", releaseWorkJob_environment_list);
            }

        }
        model.addAttribute("environments", Arrays.asList(projectsLoader.getProjectOnline().getJavaEnvAll().split(",")));
        ModelAndView mv=new ModelAndView("project/project");
        return mv;
    }

    @RequestMapping("/toHistory")
    public ModelAndView toHistory(Model model) {
        ProjectOnlineResponse projectOnline=projectsLoader.getProjectOnline(true);
        model.addAttribute("environments", Arrays.asList(projectOnline.getJavaEnvAll().split(",")));

        model.addAttribute("projects", projectOnline.getJavaList());

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

    /**
     * 获取所有项目
     *
     * @return
     */
    @RequestMapping(value = "getProjects", method = RequestMethod.POST)
    @ResponseBody
    public String getProjects() {
        try {
            return JSONArray.toJSON(projectsLoader.getProjectOnline().getJavaList()).toString();
        } catch (Exception ex) {
            return "failed";
        }
    }

    /**
     * 获取项目的发布环境
     * 不同项目取交集
     *
     * @return
     */
    @RequestMapping(value = "getJavaProjectEnvList")
    @ResponseBody
    public List<String> getJavaProjectEnvList(String projects) {
        List<String> projArray=new ArrayList<>();
        for(String tmp:projects.split(",")){
            if(StringUtils.isNotBlank(tmp)){
                projArray.add(tmp);
            }
        }
        return getJavaProjectEnvList(projArray);
    }

    public List<String> getJavaProjectEnvList(List<String> projArray) {
        Map<String,Project> javaMap=projectsLoader.getProjectOnline().getJavaMap();
        List<String> envs=new ArrayList<>();
        for(int i=0;i<projArray.size();i++){
            List<String> ls= javaMap.get(projArray.get(i)).getSupportEnvList();
            if(i==0){
                envs.addAll(ls);
            }else{
                envs.retainAll(ls);
            }
        }
        return envs;
    }

    /**
     * 校验tag
     *
     * @return
     */
    @RequestMapping(value = "checkTag", method = RequestMethod.POST)
    @ResponseBody
    public String checkTag(String projects, String tag, String enviromment) {
        Map<String, String> map = new HashMap<>();
        map.put("projects", projects);
        map.put("tag", tag);
        return httpRestClient.get(ProjectEnvironment.getUrl(enviromment) + "checkTag", String.class, map);

    }

    /**
     * 发布前校验
     *
     * @return
     */
    @RequestMapping(value = "check")
    @ResponseBody
    public BaseResponse check(String projects, String branch, String environment,String workid,HttpSession httpSession) {
        BaseResponse rtnResponse=releaseCheck.check(workid,httpSession);
        if(200!=rtnResponse.getCode()){
            return rtnResponse;
        }
        //项目冲突的校验
        List<Object> checkRtn= ProjectMutex.checkMutex(projects);
        boolean mutex=(Boolean)checkRtn.get(0);
        if(mutex){
            rtnResponse.setCode(201);
            rtnResponse.setMessage((String)checkRtn.get(1));
            return rtnResponse;
        }

        Map<String,String> map = new HashMap<>();
        if (!("master".equals(branch) || "test".equals(branch) || "dev".equals(branch) )) {
            map.clear();
            map.put("projects", projects);
            map.put("branch", branch);
            String checkBranchResult= httpRestClient.get(ProjectEnvironment.getUrl(environment) + "checkBranch", String.class, map);
            if(!"1".equals(checkBranchResult)){
                rtnResponse.setCode(201);
                rtnResponse.setMessage("分支不存在"+branch+",result :"+checkBranchResult);
                return rtnResponse;
            }
        }
        return rtnResponse;


    }

    @RequestMapping(value = "tobuildpage")
    @ResponseBody
    public ModelAndView tobuildpage(String messageid, String project, String environment, String operate, String branch, String rollbackfile, Model model) {
        model.addAttribute("messageid", messageid);
        model.addAttribute("project", project);
        model.addAttribute("environment", environment);
        model.addAttribute("operate", operate);
        model.addAttribute("branch", branch);
        model.addAttribute("rollbackfile", rollbackfile);
        return new ModelAndView("project/single_project_build");
    }

    /**
     * 执行任务
     *
     * 修改日志:yoho-search-service项目发布或者回滚时,aws和qq需要特殊处理,
     *                先从负载均衡器卸载n-1个机器,保留一台,发布卸载的n-1台,发布,再挂载,再卸载原来一台,发布,再挂载
     * 修改时间:2017-12-28
     * 修改人:craig.qin
     *
     * 最终执行的方法是 project-boot 工程里的JavaBuildCtrl(web) -> build.do
     * 执行的ip是http:/
     * @return
     */
    @RequestMapping(value = "build", method = RequestMethod.POST)
    public ModelAndView build(String project_name, String environment_name, String operate_name, String branch_name, String rollbackfile_name,String workid_name, Model model, HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            /*Map<String,String> map = new HashMap<>();
            if (StringUtils.equals("Deploy",operate_name) && !StringUtils.equals("release0",workid_name)){//查询用户是否有工单处理权限
                map.put("id",workid_name);
                map.put("user",user.getName());
                BaseResponse baseResponse = httpRestClient.defaultGet(HttpUriContants.UPDATE_JOB_BY_OPERATOR,BaseResponse.class,map);
                if (baseResponse.getCode() != 200){
                    model.addAttribute("environment_name", baseResponse.getMessage());
                    return new ModelAndView("project/project_build");
                }
            }*/

            BaseResponse checkResponse=releaseCheck.checkAndUpdate(workid_name,operate_name,user.getName());
            if(200!=checkResponse.getCode()){
                model.addAttribute("environment_name", checkResponse.getMessage());
                return new ModelAndView("project/project_build");
            }

            //发布的时候,启动一个线程 ,更新项目的tag
            final String projectNamesForUpdateTag=project_name;
            new Thread(() -> {
                try {
                    httpRestClient.defaultGet(HttpUriContants.JAVA_RESTART_UPDATE_HOST_TAGS+"?projectNames="+projectNamesForUpdateTag,BaseResponse.class);
                } catch (Exception e) {
                    log.error("project build update tags error {}",e);
                }

            }).start();

            List<String> projectList=Arrays.asList(project_name.split(","));
            //把要发布的项目重新组合,其中特殊情况的项目,先拿出来传递到前台,其余的普通项目直接发布
            List<String> specialProjectLb=new ArrayList<>();
            if(("aws".equals(environment_name)||"qcloud".equals(environment_name))){
                project_name="";
                for(String str:projectList){
                    if(StringUtils.isNotBlank(str)){
                        if(lb_proejct_list.contains(str)){
                            specialProjectLb.add(str);
                            continue;
                        }
                        if(project_name.length()>0){
                            project_name += ",";
                        }
                        project_name += str ;
                    }
                }
            }
            model.addAttribute("specialProjectLbList", JSONArray.parseArray(JSON.toJSONString(specialProjectLb)));

            String messageids = "";
            List<BuildMessage> list = new ArrayList<>();
            if(StringUtils.isNotBlank(project_name)){
                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.setWorkid(workid_name);

                if ("Deploy".equals(operate_name)) {
                    //不包含特殊项目,直接走原来的发布
                    messageids=deploy(project_name,environment_name,buildRequest,list,messageids);
                } else {
                    buildRequest.setProject(project_name);
                    messageids=rollback(environment_name, buildRequest, list, messageids);
                }
            }

            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("workid_name",workid_name);
        } catch (Exception ex) {
        }
        return new ModelAndView("project/project_build");
    }

    @RequestMapping(value ="/buildProjectWithIPs", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse<?> buildProjectWithIPs(HttpSession session, String project_name,String ips, String environment_name, String operate_name, String branch_name, String rollbackfile_name,String workid_name){
        BaseResponse response = new BaseResponse();
        try{
            User user = (User) session.getAttribute("user");
            BaseResponse checkResponse=releaseCheck.checkAndUpdate(workid_name,operate_name,user.getName());
            if(200!=checkResponse.getCode()){
                return checkResponse;
            }

            List<BuildMessage> list = new ArrayList<>();
            BuildRequest buildRequest = new BuildRequest();
            //分支名称
            buildRequest.setBranch(branch_name);
            //登陆用户
            buildRequest.setUser(user.getName());

            //设置需要发布的ip
            buildRequest.setHost(ips);

            //发布环境
            buildRequest.setEnvironment(environment_name);
            //回滚文件名称
            buildRequest.setRollbackfile(rollbackfile_name);
            //操作类型
            buildRequest.setOperate(operate_name);
            //关联工单
            buildRequest.setWorkid(workid_name);
            //项目名称
            buildRequest.setProject(project_name);

            String messageids = "";
            BuildMessage buildMessage = httpRestClient.post(ProjectEnvironment.getUrl(environment_name) + "build", buildRequest, BuildMessage.class);
            if (buildMessage != null) {
                list.add(buildMessage);
                messageids =  buildMessage.getId() + ",";
            }
            response.setData(messageids);
        }catch (Exception e){
            response.setCode(300);
            response.setMessage(e.getMessage());
        }

        return response;
    }

    @RequestMapping(value = "/deregisterHostYohoSearchService")
    @ResponseBody
    public BaseResponse deregisterHostYohoSearchService(String project,String environment_name,String instIds){
        Map<String, String> map=new HashMap<>();
        map.put("cloudType",environment_name);
        map.put("instIds",instIds);
        map.put("project",project);
        return httpRestClient.defaultGet("/lb/deregisterHostFromLb/yohoSearchService",BaseResponse.class,map);
    }

    @RequestMapping(value = "/registerHostYohoSearchService")
    @ResponseBody
    public BaseResponse registerHostYohoSearchService(String project,String environment_name,String instIds){
        Map<String, String> map=new HashMap<>();
        map.put("cloudType",environment_name);
        map.put("instIds",instIds);
        map.put("project",project);
        return httpRestClient.defaultGet("/lb/registerHostFromLb/yohoSearchService",BaseResponse.class,map);
    }

    @RequestMapping(value = "/getLbInfoYohoSearchService")
    @ResponseBody
    public BaseResponse getLbInfoYohoSearchService(String project,String environment_name){
        Map<String, String> map=new HashMap<>();
        map.put("cloudType",environment_name);
        map.put("project",project);
        return httpRestClient.defaultGet("/lb/getLb/yohoSearchService",BaseResponse.class,map);
    }

    /**
     * 特殊项目发布之前检查lb的情况
     * @param project
     * @param environment_name
     * @return
     */
    @RequestMapping(value = "/checkSpecialProjectLbInfoBeforeBuild")
    @ResponseBody
    public BaseResponse checkSpecialProjectLbInfoBeforeBuild(String project,String environment_name,String branch_name,String workid_name,String operate_name,String rollbackfile_name){
        LbResult lbResult=new LbResult();
        lbResult.setCurrentProject(project);
        lbResult.setEnvironmentName(environment_name);
        lbResult.setBranch(branch_name);
        lbResult.setWorkIdName(workid_name);
        lbResult.setOperateName(operate_name);
        lbResult.setRollbackfileName(rollbackfile_name);

        BaseResponse response = this.getLbInfoYohoSearchService(project,environment_name);
        if(response!=null&&response.getCode()==200){
            Map<String,String> hostIdAndIpMap=(Map<String,String>)response.getData();
            //负载均衡只有一台机器的情况,就不拿掉了 ,直接发布吧
            if(hostIdAndIpMap.size()<=1){
                lbResult.setOnlyOneHost("1");
                lbResult.setMsg("负载均衡最多只有一台机器,直接发布!");
            }else{
                lbResult.setOnlyOneHost("2");
                //保留的机器和需要卸载(挂载)的机器
                lbResult.setMsg("负载均衡有多个机器,走特殊发布流程!");
                int index=0;
                for(String id:hostIdAndIpMap.keySet()){
                    if(index==0){
                        lbResult.setKeepId(id);
                        lbResult.setKeepNum(1);
                        lbResult.setKeepIp(hostIdAndIpMap.get(id));
                    }else{
                        if(lbResult.getChangeIds().length()>0){
                            lbResult.setChangeIds(lbResult.getChangeIds()+",");
                        }
                        lbResult.setChangeIds(lbResult.getChangeIds()+id);

                        if(lbResult.getChangeIps().length()>0){
                            lbResult.setChangeIps(lbResult.getChangeIps()+",");
                        }
                        lbResult.setChangeIps(lbResult.getChangeIps()+hostIdAndIpMap.get(id));
                    }
                    index++;
                }
                lbResult.setHostNum(index);
                lbResult.setChangeNum(index-1);
            }

            response.setData(lbResult);
        }
        return response;
    }



    @Data
    class LbResult{
        String currentProject="";
        String branch="";
        String environmentName="";
        String workIdName="";
        String operateName="";
        String rollbackfileName="";

        boolean errorFlag=false;
        String onlyOneHost="";
        String msg="";

        //保留的机器和需要卸载(挂载)的机器
        int hostNum=0;
        String keepId="";
        int keepNum=0;
        String keepIp="";
        String changeIds="";
        String changeIps="";
        int changeNum=0;
        //Map<String,String> changeHostIdAndIpMap=new LinkedHashMap<>();
    }

    private String deploy(String project_name,String environment_name,BuildRequest buildRequest,List<BuildMessage> list,String messageids){
        String[] array = project_name.split(",");
        if (array.length > 4) {
            String[] newArray = new String[]{"", "", "", ""};
            for (int i = 0; i < array.length; i++) {
                newArray[i % 4] = newArray[i % 4] + array[i] + ",";
            }
            //如上下所述,只支持长度为4。。。。。不明白
            for (String project : newArray) {
                buildRequest.setProject(project.substring(0, project.length() - 1));
                BuildMessage buildMessage = httpRestClient.post(ProjectEnvironment.getUrl(environment_name) + "build", buildRequest, BuildMessage.class);
                if (buildMessage != null) {
                    list.add(buildMessage);
                    messageids = messageids + buildMessage.getId() + ",";
                }
            }

        } else {
            for (String project : array) {
                buildRequest.setProject(project);
                BuildMessage buildMessage = httpRestClient.post(ProjectEnvironment.getUrl(environment_name) + "build", buildRequest, BuildMessage.class);
                if (buildMessage != null) {
                    list.add(buildMessage);
                    messageids = messageids + buildMessage.getId() + ",";
                }
            }
        }
        return messageids;
    }

    private String  rollback(String environment_name,BuildRequest buildRequest,List<BuildMessage> list,String messageids){
        BuildMessage buildMessage = httpRestClient.post(ProjectEnvironment.getUrl(environment_name) + "build", buildRequest, BuildMessage.class);
        if (buildMessage != null) {
            list.add(buildMessage);
            messageids = messageids + buildMessage.getId() + ",";
        }
        return messageids;
    }

    /**
     * 获取执行结果
     *
     * @param messageid
     * @return
     */
    @RequestMapping(value = "getbuildmsg", method = RequestMethod.POST)
    @ResponseBody
    public String getbuildmsg(String messageid, String project) {
        /*try {
            Map<String, String> map = new HashMap<>();
            map.put("messageid", messageid);
            map.put("project", project);

            return httpRestClient.get(ProjectEnvironment.getUrl(messageid.split("_")[0]) + "getbuildmsg", String.class, map);

        } catch (Exception ex) {
            return "failed";
        }*/
        return releaseCheck.getbuildmsg(ProjectEnvironment.getUrl(messageid.split("_")[0]) ,messageid,project);
    }

    @RequestMapping(value = "cancelBuild")
    @ResponseBody
    public String cancelBuild(String id) {
       /* try {
            Map<String, String> map = new HashMap<>();
            map.put("id", id);
            return httpRestClient.get(ProjectEnvironment.getUrl(id.split("_")[0]) + "cancelBuild", String.class, map);
        } catch (Exception ex) {
            return "failed";
        }*/
        return releaseCheck.cancelBuild(ProjectEnvironment.getUrl(id.split("_")[0]) ,id);
    }

    @RequestMapping(value = "rollbackList", method = RequestMethod.POST)
    @ResponseBody
    public String rollbackList(String project, String environment) {
        /*try {
            Map<String, String> map = new HashMap<>();
            map.put("project", project);
            map.put("environment", environment);
            return httpRestClient.get(ProjectEnvironment.getUrl(environment) + "rollbackList", String.class, map);
        } catch (Exception ex) {
            return "failed";
        }*/
        return releaseCheck.rollbackList(ProjectEnvironment.getUrl(environment) ,project,environment);
    }

    @RequestMapping("/getHistory")
    @ResponseBody
    public BaseResponse getHistory(ProjectBuildReq req) throws Exception {
        if ("all".equals(req.getEnvironment())) {
            req.setEnvironment(null);
        }
        if ("all".equals(req.getCurrentProject())) {
            req.setCurrentProject(null);
        }
        BaseResponse response = httpRestClient.defaultPost("/projectBuild/getHistory", req, BaseResponse.class);
        return response;
    }

    @RequestMapping("/projectDetectUrl")
    @ResponseBody
    public BaseResponse projectDetectUrl(String operate_name,String project,String environment) throws Exception {
        Map<String,String> map=new HashMap<>();
        map.put("project",project);
        map.put("environment",environment);
        BaseResponse response = httpRestClient.defaultGet("/javaApiDetect/projectDetectUrl", BaseResponse.class,map);
        return response;
    }

    @RequestMapping("/toRollbackByTime")
    @ResponseBody
    public ModelAndView toRollbackByTime() {
        return new ModelAndView("project/project_rollbackByTime");
    }

    @RequestMapping("/rollbackByTime")
    @ResponseBody
    public String rollbackByTime(String time, String environment) {
        Map<String, String> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,1);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);

        if (StringUtils.equals("yestoday",time)){
            time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        }else if (StringUtils.equals("beforeYestoday",time)){
            calendar.add(Calendar.DAY_OF_YEAR,-1);
            time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        }
        map.put("time", time);
        map.put("environment", environment);
        return httpRestClient.get(ProjectEnvironment.getUrl(environment) + "rollbackByTime", String.class, map);
    }

    @RequestMapping("/doRollbackByTime")
    @ResponseBody
    public ModelAndView doRollbackByTime(String data, String environment, HttpSession session, Model model) {
        try {
            JSONArray jsonArray = JSONArray.parseArray(data);
            User user = (User) session.getAttribute("user");
            List<BuildMessage> list = new ArrayList<>();
            BuildRequest buildRequest = new BuildRequest();
            buildRequest.setUser(user.getName());
            buildRequest.setEnvironment(environment);
            buildRequest.setOperate("Rollback");

            String messageids = "";
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String project = jsonObject.getString("project");
                buildRequest.setProject(project);
                buildRequest.setRollbackfile(jsonObject.getString("rollbackFile"));
                BuildMessage buildMessage = httpRestClient.post(ProjectEnvironment.getUrl(environment) + "build", buildRequest, BuildMessage.class);
                if (buildMessage != null) {
                    list.add(buildMessage);
                    messageids = messageids + buildMessage.getId() + ",";
                }
            }
            model.addAttribute("environment_name", environment);
            model.addAttribute("operate_name", "Rollback");
            model.addAttribute("messageids", messageids);
            model.addAttribute("messageList", list);
        } catch (Exception ex) {
        }
        return new ModelAndView("project/project_build");


    }


    @RequestMapping("/newOm/query")
    public BaseResponse queryProjects(ProjectInfoReq req) {

        BaseResponse response = httpRestClient.defaultPost("/projectManager/query", req, BaseResponse.class);

        return response;
    }


    @RequestMapping("/newOm/save")
    public BaseResponse addProject(ProjectInfoReq req) {

        BaseResponse response = httpRestClient.defaultPost("/projectManager/add", req, BaseResponse.class);
        return response;
    }

    @RequestMapping("/newOm/del")
    public BaseResponse delProject(ProjectInfoReq req) {

        BaseResponse response = httpRestClient.defaultPost("/projectManager/del", req, BaseResponse.class);
        return response;
    }

    @RequestMapping("/newOm/build")
    public BaseResponse buildOmProject(ProjectBuildInfoReq req) {
        BaseResponse response = httpRestClient.defaultPost("/projectManager/build", req, BaseResponse.class);
        return response;
    }

    @RequestMapping("/aototest/autoTestService")
    @ResponseBody
    public BaseResponse autoTestService(String models, String branch, HttpSession session) {
        User user = (User) session.getAttribute("user");
        AutoTestReq autoTestReq = new AutoTestReq();
        String id = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomStringUtils.randomNumeric(6);
        autoTestReq.setTaskname(id);
        autoTestReq.setEnv("5");
        autoTestReq.setModels(models.substring(0, models.length() - 1));
        autoTestReq.setBranch(branch);
        autoTestReq.setProId(0);
        autoTestReq.setVersionId(0);
        autoTestReq.setMailto(user.getEmail());
        BaseResponse baseResponse = httpRestClient.post("http://qmc.yohops.com:9999/autotest/autoTestService", autoTestReq, BaseResponse.class);
        System.out.println(id);
        return baseResponse;
    }

    @RequestMapping("/aototest/getAutoTestResult")
    @ResponseBody
    public BaseResponse getAutoTestResult(String id) {
        AutoTestReq autoTestReq = new AutoTestReq();
        autoTestReq.setTaskname(id);
        BaseResponse baseResponse = httpRestClient.post("http://qmc.yohops.com:9999/autotest/getAutoTestResult", autoTestReq, BaseResponse.class);
        return baseResponse;
    }

    @RequestMapping("/aototest/toAutoTestResult")
    public ModelAndView toAutoTestResult(String id, Model model) {
        model.addAttribute("id", id);
        return new ModelAndView("project/autotestresult");
    }

    @RequestMapping("/testexecute")
    @ResponseBody
    public BaseResponse testexecute(String env) {
        AutoTestReq autoTestReq = new AutoTestReq();
        autoTestReq.setEnv(env);
        BaseResponse emailResponse = httpRestClient.defaultPost(HttpUriContants.GET_EMAIL_BY_ALARM_GROUP+"?groupName=" + AlarmGroupContants.GROUP_NAME_YUNWEI, null, BaseResponse.class);
        if(emailResponse.getData() != null){
            autoTestReq.setMailto((String)emailResponse.getData());
        }
        BaseResponse baseResponse = httpRestClient.post("http://qmc.yohops.com:9999/autoTask/executeApiAutoTask", autoTestReq, BaseResponse.class);
        return baseResponse;
    }

    @RequestMapping("/testget")
    public BaseResponse testget(String id) {
        AutoTestReq autoTestReq = new AutoTestReq();
        autoTestReq.setId(id);
        BaseResponse baseResponse = httpRestClient.post("http://qmc.yohops.com:9999/autoTask/getAutoTestExecuteResult", autoTestReq, BaseResponse.class);
        return baseResponse;
    }
}