projects.js 12.8 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
'use strict';

import Router from 'koa-router';
import moment from 'moment';
import Rp from 'request-promise';
import Build from '../../ci/build';
import Deploy from '../../ci/deploy';
import DeployPhp from '../../ci/deploy_php';
import Restart from '../../ci/restart';
import DeleteRestart from '../../ci/delete_restart';
import Operation from '../../logger/operation';
import ws from '../../../lib/ws';

const monit = require('../../ci/monit');

const DeployPool = require('../../ci/deploy_pool');

import {
    Building,
    Project,
    Server,
    DeployInfo,
    RestartInfo,
    DeleteRestartInfo
} from '../../models';

let r = new Router();

const colors = ['primary', 'success', 'info', 'warning', 'danger', 'success-alt', 'info-alt', 'warning-alt', 'danger-alt', 'primary-head', 'success-head', 'danger-head'];
const envs = {
    production: '线上环境',
    preview: '灰度环境',
    test: '测试环境'
};

const p = {
    /**
     * 所有项目首页
     */
    index_page: async(ctx, next) => {
        let projects = await Project.findAll();
        let awsProjects = [];
        let qcloudProject = [];

        projects.forEach((p, i) => {
            p.color = colors[i % colors.length];
            if (p.cloud === 'aws') {
                awsProjects.push(p);
            } else {
                qcloudProject.push(p);
            }

            awsProjects.sort((a, b) => {
                return a.name > b.name ? 1 : -1;
            });
            qcloudProject.sort((a, b) => {
                return a.name > b.name ? 1 : -1;
            });

            if (p.deploy) {
                Object.keys(p.deploy).forEach(k => {
                    if (typeof p.deploy[k].target === 'string') {
                        p.deploy[k].target = [p.deploy[k].target];
                    }
                });
            }
        });
        await ctx.render('action/projects', {
            awsProjects: awsProjects,
            qcloudProject: qcloudProject
        });
    },
    /**
     * 单个项目首页
     */
    project_index: async(ctx, next) => {
        let id = ctx.params.id;
        let env = ctx.request.query.env;
        let project = await Project.findById(id);
        let deploy = project.deploy[env] || {};
        deploy.env = env;
        deploy.name = envs[env];

        if (typeof deploy.target === 'string') {
            deploy.target = [deploy.target];
        }

        let promises = deploy.target.map((host) => {
            return DeployInfo.findOne({
                projectId: project._id,
                host: host,
                env: env
            }).then((info) => {
                return {
                    host: host,
                    hostFm: host.replace(/\./g, '-'),
                    info: info
                };
            });
        });
        let targets = await Promise.all(promises);

        targets.sort((a, b) => {
            return a.host > b.host ? 1 : -1;
        });

        await ctx.render('action/project_index', {
            project: project,
            deploy: deploy,
            targets: targets
        });
    },

    new_page: async(ctx, next) => {
        let serversAll = await Server.findAll();
        let servers = {};
        serversAll.forEach(s => {
            if (servers[s.env]) {
                servers[s.env].push(s);
            } else {
                servers[s.env] = [s];
            }
        });
        await ctx.render('action/project_form', {
            servers: servers,
            project: {
                deploy: {
                    production: {},
                    test: {}
                }
            }
        });

    },
    edit_page: async(ctx, next) => {
        let id = ctx.query.id;
        let project = await Project.findById(id);

        let serversAll = await Server.findAll();
        let servers = {};
        serversAll.forEach(s => {
            if (servers[s.env]) {
                servers[s.env].push(s);
            } else {
                servers[s.env] = [s];
            }
            if (project.deploy[s.env] && project.deploy[s.env].target && project.deploy[s.env].target.indexOf(s.host) >= 0) {
                s.checked = true;
            }
        });

        Object.keys(servers).forEach(key => {
            servers[key].sort((a, b) => {
                return a.host > b.host ? 1 : -1;
            });
        });

        await ctx.render('action/project_form', {
            project: project,
            servers: servers
        });
    },
    save: async(ctx, next) => {
        let project = ctx.request.body;
        let id = project._id;
        delete project._id;
        if (id) {
            await Project.update({
                _id: id
            }, {
                $set: project
            });
            await Operation.action(ctx.session.user, 'EDIT_PROJECT_INFO', '修改项目信息', {
                _id: id,
                name: project.name
            });
        } else {
            await Project.insert(project);
            await Operation.action(ctx.session.user, 'NEW_PROJECT_INFO', '新增项目信息', {
                _id: id,
                name: project.name
            });
        }
        ctx.redirect('/projects');
        ctx.status = 301;
    },
    buildings_table: async(ctx, next) => {
        let env = ctx.request.query.env;
        let pid = ctx.params.id;
        let buildings = await Building.cfind({
            env: env,
            projectId: pid
        }).sort({
            buildTime: -1
        }).limit(30).exec();
        buildings.forEach(b => {
            b.updatedAt = moment(b.updatedAt).format('YYYY-MM-DD HH:mm:ss');
        });
        ctx.body = {
            data: buildings
        };
    },
    project_build: async(ctx, next) => {
        let pid = ctx.params.pid;
        let env = ctx.request.body.env;
        let branch = ctx.request.body.branch;
        let p = await Project.findById(pid);
        let build = new Build(p);

        let {
            buildTime,
            distFile
        } = build.build(branch);
        let buildingDoc = await Building.insert({
            buildTime: buildTime,
            project: p.name,
            projectId: pid,
            branch: branch,
            env: env,
            distFile: distFile,
            state: 'waiting',
            createdAt: new Date(),
            updatedAt: new Date()
        });

        let id = buildingDoc[0]._id;

        build.run(id);

        await Operation.action(ctx.session.user, 'NEW_PROJECT_BUILDING', '新增项目构建', {
            _id: id,
            project: p.name,
            branch: branch,
            env: env
        });

        ctx.body = {
            code: 200,
            id: id
        };
        await next();
    },
    project_deploy: async(ctx) => {
        let buildingId = ctx.params.building;
        let building = await Building.findById(buildingId);
        if (!building) {
            ctx.body = {
                code: 201,
                msg: '该版本不存在'
            };
        } else if (building.state == 'success') {
            let project = await Project.findById(building.projectId);
            let targets = project.deploy[building.env].target;

            if (typeof targets === 'string') {
                targets = [targets];
            }

            targets.forEach(async(host) => {

                let doc = await DeployInfo.findOne({
                    projectId: project._id,
                    host: host,
                    env: building.env
                });

                if (!doc || doc.state !== 'running' || doc.building !== building.buildTime) {
                    let deploy = new Deploy(project, building, host);

                    // if (project.type === 'php') {
                    //     deploy = new DeployPhp(project, building, host);
                    // } else {
                    //     deploy = new Deploy(project, building, host);
                    // }
                    DeployPool.deploy(deploy);
                }
            });

            await Operation.action(ctx.session.user, 'PROJECT_DEPLOY', '项目分发部署', {
                _id: buildingId,
                project: project.name,
                branch: building.branch,
                env: building.env
            });

            ctx.body = {
                code: 200,
                building: building
            };
        } else {
            ctx.body = {
                code: 201,
                msg: '该版本未构建成功,暂不能分发'
            };
        }
    },
    project_restart: async(ctx) => {
        const projectId = ctx.request.body.id;
        const host = ctx.request.body.host;
        const env = ctx.request.body.env;
        const project = await Project.findById(projectId);

        if (!project) {
            ctx.body = {
                code: 201,
                msg: '该项目不存在'
            };
            return;
        }

        let hosts = [];
        if (host === 'all') {
            // 全部重启
            hosts = project.deploy[env].target;
        } else {
            // 单台重启
            hosts.push(host);
        }

        hosts.forEach(async(host) => {
            let doc = await DeployInfo.findOne({
                projectId: projectId,
                host: host,
                env: env
            });

            if (!doc) {
                return;
            }

            let info = {
                projectId: projectId,
                host: host,
                env: env,
                createdAt: new Date(),
                updatedAt: new Date(),
                state: 'waiting'
            };

            let restartDoc = await RestartInfo.insert(info);
            let restart = new Restart(project);

            info._id = restartDoc[0]._id;
            restart.restart(info);

            await Operation.action(ctx.session.user, 'PROJECT_RESTART', '项目重启', {
                _id: info._id,
                project: project.name,
                branch: project.deploy[env].branchName,
                env: env
            });
        });

        ctx.body = {
            code: 200
        };
    },
    project_deleterestart: async(ctx) => {
        const projectId = ctx.request.body.id;
        const host = ctx.request.body.host;
        const env = ctx.request.body.env;
        const project = await Project.findById(projectId);

        if (!project) {
            ctx.body = {
                code: 201,
                msg: '该项目不存在'
            };
            return;
        }

        let hosts = [];
        if (host === 'all') {
            // 全部重启
            hosts = project.deploy[env].target;
        } else {
            // 单台重启
            hosts.push(host);
        }

        hosts.forEach(async(host) => {
            let doc = await DeployInfo.findOne({
                projectId: projectId,
                host: host,
                env: env
            });

            if (!doc) {
                return;
            }

            let info = {
                projectId: projectId,
                host: host,
                env: env,
                createdAt: new Date(),
                updatedAt: new Date(),
                state: 'waiting'
            };

            let delrestartDoc = await DeleteRestartInfo.insert(info);
            let deleteRestart = new DeleteRestart(project);

            info._id = delrestartDoc[0]._id;
            deleteRestart.deleteRestart(info);

            await Operation.action(ctx.session.user, 'PROJECT_DELETERESTART', '项目删除重启', {
                _id: info._id,
                project: project.name,
                branch: project.deploy[env].branchName,
                env: env
            });
        });

        ctx.body = {
            code: 200
        };
    },
    project_monit: async(ctx) => {
        const projectId = ctx.request.body.id;
        const env = ctx.request.body.env;
        const project = await Project.findById(projectId);
        if (!project) {
            ctx.body = {
                code: 201,
                msg: '该项目不存在'
            };
            return;
        }

        let hosts = [];
        let target = project.deploy[env].target;
        if (typeof target === 'string') {
            hosts.push(target);
        } else {
            hosts = target;
        }
        
        if (project.type === 'php') {
            monit.php(project, hosts);
        } else {
            monit.node(project, hosts);
        }
        ctx.body = {
            code: 200
        };
    }
};

r.get('/', p.index_page);
r.get('/new', p.new_page);
r.get('/edit', p.edit_page);
r.get('/:id', p.project_index);
r.get('/:id/buildings', p.buildings_table);
r.post('/save', p.save);
r.post('/build/:pid', p.project_build);
r.post('/deploy/:building', p.project_deploy);
r.post('/restart', p.project_restart);
r.post('/deleterestart', p.project_deleterestart);
r.post('/monit', p.project_monit);
export default r;