deploy.js 2.15 KB
/**
 * 分发部署
 * upload >> unzip >> startup
 * 
 * @class Deploy
 * @author jf<jeff.jiang@yoho.cn>
 * @date 2016/5/21
 */

import sh from 'shelljs';
import ssh from 'ssh2';
import fs from 'fs';
import path from 'path';
import rp from 'request-promise';

import config from '../../config/config';
import ws from '../../lib/ws';
import {
    DeployInfo,
    Server
} from '../models';

class Deploy {

    constructor(project, building) {
        this.project = project;
        this.building = building;
    }

    deploy(info) {
        var self = this;

        return this._deploy().then(() => {
            self._state('deploying');
        }).then(() => {
            self._flush();
            self._state('flushing');
        }).then(() => {
            self._state('deploy success');
        }).catch(e => {
            console.error(e);
            self._state('fail');
        });
    }

    _deploy() {
        var self = this;

        return new Promise((resolve, reject) => {
            self._state('deploy code');
            sh.cd(config.ci);

            let child = sh.exec(`gulp upQiniu --name=${self.project.name} --time=${self.building.buildTime} --pkg=${self.building.pkgName}`, {
                async: true
            });

            child.on('close', (code) => {
                if (code == 0) {
                    console.log('deploy success');
                    resolve();
                } else {
                    reject(new Error(`build code fail`));
                }
            });
        })
    }

    _flush() {
        var self = this;

        return rp({
            uri: 'http://flushcache.yoho.cn/flushdaction.php',
            type: 'GET',
            qs: {
                url: `http://cdn.yoho.cn/${self.building.pkgName}/${self.building.version}/`
            }
        }).then(data => {
            console.log(data);
        });
    }

    
    async _state(state) {
        ws.broadcast(`/deploy/${this.project._id}`, {
            state: state
        });
    }

    _log(msg) {
        ws.broadcast(`/deploy/${this.project._id}/log`, {
            host: this.info.host,
            msg: msg
        });
    }
}

export default Deploy;