monitor.js 2.12 KB
/**
 *
 * @author: jiangfeng<jeff.jiang@yoho.cn>
 * @date: 16/8/4
 */

'use strict';

const Router = require('koa-router');

const {
    Project
} = require('../../models');

const InfluxDB = require('../../logger/influxdb');

const r = new Router();

const monitor = {
    async log(ctx) {
        let id = ctx.query.pid;
        let ip = ctx.query.ip;
        let env = ctx.query.env;
        let projects = await Project.findAll();
        let data = {
            projects: projects, ip: ip, env: [{
                name: '线上环境',
                value: 'production',
                checked: env === 'production'
            },{
                name: '灰度环境',
                value: 'preview',
                checked: env === 'preview'
            }, {
                name: '测试环境',
                value: 'test',
                checked: env === 'test'
            }]
        };

        if (id) {
            projects.forEach((p) => {
                p.checked = p._id === id;

                if (env) {
                    data.hosts = p.deploy[env].target;
                }
            });
        }
        await ctx.render('action/log_view', data);
    },

    async query(ctx) {
        let influxName = ctx.query.influxName;
        let ip = ctx.query.ip;
        let limit = ctx.query.limit || 30;
        let page = ctx.query.page || 1;

        let oldTime = ctx.query.oldTime;
        let newTime = ctx.query.newTime;

        ip = ip.replace(/\./g, '-');

        let where = 'where host =~ /./ ';

        if (ip) {
            where += ` and host='ip-${ip}'`;
        }

        if (oldTime) {
            where += ` and time<'${oldTime}' order by time desc`;
        }

        if (newTime) {
            where += ` and time>'${newTime}'`;
        }

        if (!(oldTime || newTime)) {
            where += ' order by time desc';
        }

        let sql = `select * from ${influxName} ${where}  limit ${limit} OFFSET ${(page -1) * limit}`;
        
        let logs = await InfluxDB.query(sql);

        ctx.body = logs[0];
    }
};

r.get('/log', monitor.log);
r.get('/log/query', monitor.query);

module.exports = r;