Python之行 --liunx常用服务监管

Python之行--服务监管

背景

针对公司系统平台服务不断增多和复杂化,定位问题效率逐渐下降,实现各个服务统一监管显得越来越重要,在作为运维人员的我管理越来越头疼的时候,我觉得开发自己的监控程序!

动作

首先公司系统使用 java 开发,以微服务体系实现的快速搭建,服务器使用最常用的centos系统(centos7)因此有多个xxx.jar 启动命令冗长繁琐,在不断和后台人员优化统一启动命令后,统一改造成系统服务 例如: systemctl start xxx.service,类似这样都有9个之多,还不包括所依赖的其他服务,如mysql,redis,kafka...,这些服务也统一做成了系统服务!

开发(上代码)

# coding:utf-8
# author:Liu Xiaofei
# date:2020-5-4
# mood:restless

import time
import logging
import subprocess

from copy import deepcopy
from functools import wraps


class ParsesTools(object):

    @staticmethod
    def parse_netstat_response(origin):
        """
        解析netstat -tnlp 返回结果
        :param origin:
        :return:
        """
        res = origin.strip().splitlines()
        origin_parse = deepcopy(res[2::])

        for index, item in enumerate(origin_parse):
            every_info = item.split()
            dicts = {
                "type": every_info[0],
                "process": every_info[6].split("/")[0],
                "service": every_info[6].split("/")[1].replace(":", ""),
                "port": every_info[3].replace(":", "") if "::" in every_info[3] else every_info[3].split(":")[1]
            }
            yield dicts

    @staticmethod
    def execute_result(command):
        """
        收集某些指令后的返回值
        :param command: 常规指令
        :return:
        """
        network_res = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                       shell=True)
        response_info = network_res.stdout.read()
        network_res.stdout.close()
        return response_info

    @staticmethod
    def service_run(command):
        """
        带参数装饰器执行服务启动监测
        :param command: 执行的命令
        :return:
        """
        def execute_status(func):
            @wraps(func)
            def inner(*args, **kwargs):
                try:
                    subprocess.check_call(command, shell=True)
                    status = True
                except Exception as e:
                    logging.error(e)
                    status = False
                kwargs[func.__name__.replace("_", "-")] = status
                result = func(*args, **kwargs)
                return result

            return inner

        return execute_status

class ExecuteLinuxCommands(object):
    CENTOS7_NETSTAT = "netstat -tnlp"

    CENTOS7_MYSQL = "systemctl start mysqld.service"
    CENTOS7_REDIS = "systemctl start redis-server.service"
    CENTOS7_INFLUXDB = "systemctl start influxdb"
    CENTOS7_GRAFANA = "systemctl start grafana-server"
    CENTOS7_NGINX = "systemctl start nginx.service"
    CENTOS7_KAFKA = "systemctl start kafka.service"
    CENTOS7_ZOOKEEPER = "systemctl restart kafka.service"

    JAVA_GATEWAYAPI = "systemctl start gateway-api.service"
    JAVA_CONFIGMANGER = "systemctl start config-manger.service"
    JAVA_REALTIME = "systemctl start realtime.service"
    JAVA_REALTIME_DATAVIEW = "systemctl start realtime-dataview.service"
    JAVA_ALERT_STRATEGY = "systemctl start alert-strategy.service"
    JAVA_ALERT_PUSHER = "systemctl start alert-pusher.service"
    JAVA_ALERT_ENGINE = "systemctl start alert-engine.service"
    JAVA_LOGIN = "systemctl start alert-engine.service"
    JAVA_GATEWAY = "systemctl start gateway.service"

class YiLianSystemServe(object):
    pt = ParsesTools
    els = ExecuteLinuxCommands

    def __init__(self):
        self.serve_counter = 0
        self.serve_recorder = {}

    @staticmethod
    def comm(*args, **kwargs):
        """
        校验服务是否正常,返回记录结果
        :param args:
        :param kwargs:
        :return:
        """
        result = dict()
        count = 0
        result.update(kwargs)
        serve_name = kwargs.keys()[0].replace("_", "-")
        if result.get(serve_name):
            count += 1
        else:
            print "{}服务启动失败,请检查启动命令是否正确以及跟踪错误日志!!!".format(serve_name)
        return result, count

    def record(self, *args):
        """
        记录信息和统计次数
        :param args:
        :return: None
        """
        self.serve_recorder.update(args[0])
        self.serve_counter += args[1]

    @pt.service_run(els.CENTOS7_MYSQL)
    def mysql_service(self, *args, **kwargs):
        result, count = self.comm(args, kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_REDIS)
    def redis_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_INFLUXDB)
    def influx_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_GRAFANA)
    def grafana_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_KAFKA)
    def kafka_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_ZOOKEEPER)
    def zookeeper_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.CENTOS7_REDIS)
    def redis_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_GATEWAYAPI)
    def gateway_api_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_CONFIGMANGER)
    def config_manger_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_ALERT_STRATEGY)
    def alert_strategy_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_ALERT_PUSHER)
    def alert_pusher_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_ALERT_ENGINE)
    def alert_engine_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_REALTIME_DATAVIEW)
    def realtime_dataview_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_REALTIME)
    def realtime_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

    @pt.service_run(els.JAVA_LOGIN)
    def login_service(self, *args, **kwargs):
        res, count = self.comm(*args, **kwargs)
        self.record(res, count)

    @pt.service_run(els.JAVA_GATEWAY)
    def gateway_service(self, *args, **kwargs):
        result, count = self.comm(*args, **kwargs)
        self.record(result, count)

class TotalServicesRun(YiLianSystemServe):
    YiLianJavaServices = {
        "8089": "gateway",
        "8090": "config-manger",
        "8080": "gateway-api",
        "6077": "alert-strategy",
        "6088": "alert-pusher",
        "6099": "alert-engine",
        "8099": "realtime-dataview",
        "8100": "realtime",
        "8101": "login"
    }
    YiLianDependOnServices = {
        "3306": "mysql",
        "6379": "redis",
        "80": "nginx",
        "8088": "influx",
        "3000": "grafana",
        "9092": "kafka",
        "2181": "zookeeper"
    }

    def __init__(self):
        self.elc = ExecuteLinuxCommands
        self.pt = ParsesTools
        self.ports = []
        self.error_info = None
        self.total_status = dict()
        super(self.__class__, self).__init__()

    def methods(self, dictionary):
        """
        校验初始状态下服务情况,已成功启动服务做记录,未启动则执行启动
        :param dictionary: 各个服务详情
        :return: None
        """
        self.serve_recorder = {}
        self.serve_counter = 0

        for k, v in dictionary.items():
            if k not in self.ports:
                v = v.replace("-", "_") if "-" in v else v
                print "{}服务未启动!!!".format(v)
                getattr(self, "{}_service".format(v))()
            else:
                print "{}服务启动成功!".format(v)
                self.serve_recorder[v] = True
                self.serve_counter += 1


    def statistical_services(self,services,before=False):
        """
        执行不同服务组的统计
        :param services: 要启动的服务组
        :param before: 依赖服务标识
        :return:
        """
        self.methods(services)
        self.total_status.update(self.serve_recorder)
        services_name = "依赖" if before else "Java"
        if self.serve_counter < len(services):
            self.error_info = {k: v for k, v in self.serve_recorder.items() if v is False}

            print "易联系统{}服务启动失败,共{}个服务未启动{}失败服务详情(json格式):{}".format(
                services_name,len(self.error_info), "\r\n", self.error_info)
            return False
        print "易联系统{}服务已全部启动正常{}启动详情(字典格式):{}".format(services_name,"\r\n", self.serve_recorder)
        return True

    def run(self):
        origin_ingo = self.pt.execute_result(self.elc.CENTOS7_NETSTAT)

        self.ports = [i.get("port") for i in self.pt.parse_netstat_response(origin_ingo)]

        if self.statistical_services(self.YiLianDependOnServices,before=True):
            self.statistical_services(self.YiLianJavaServices)

        print "易联系统服务启动状态总览(字典格式):{}".format(self.total_status)
        return self.total_status

if __name__ == '__main__':
    count = 1
    while True:
        start = time.time()
        ts = TotalServicesRun()
        ts.run()
        diff_time = time.time() - start
        print "程序执行耗时{}s".format(diff_time)
        time.sleep(300)
ServicesSupervision

代码开发已完成,只用了些常用模块,逻辑相对简单,功能已满足当前公司需要。各位大佬,欢迎可劲指正!有更好的写法烦请留言告知我,帮助小弟更好的优化,共同进步!O(∩_∩)O谢谢

 

posted @ 2020-05-05 00:06  FindSoul  阅读(178)  评论(0编辑  收藏  举报
var RENDERER = { POINT_INTERVAL : 5, FISH_COUNT : 3, MAX_INTERVAL_COUNT : 50, INIT_HEIGHT_RATE : 0.5, THRESHOLD : 50, init : function(){ this.setParameters(); this.reconstructMethods(); this.setup(); this.bindEvent(); this.render(); }, setParameters : function(){ this.$window = $(window); this.$container = $('#jsi-flying-fish-container'); this.$canvas = $('
'); this.context = this.$canvas.appendTo(this.$container).get(0).getContext('2d-disabled'); this.points = []; this.fishes = []; this.watchIds = []; }, createSurfacePoints : function(){ var count = Math.round(this.width / this.POINT_INTERVAL); this.pointInterval = this.width / (count - 1); this.points.push(new SURFACE_POINT(this, 0)); for(var i = 1; i < count; i++){ var point = new SURFACE_POINT(this, i * this.pointInterval), previous = this.points[i - 1]; point.setPreviousPoint(previous); previous.setNextPoint(point); this.points.push(point); } }, reconstructMethods : function(){ this.watchWindowSize = this.watchWindowSize.bind(this); this.jdugeToStopResize = this.jdugeToStopResize.bind(this); this.startEpicenter = this.startEpicenter.bind(this); this.moveEpicenter = this.moveEpicenter.bind(this); this.reverseVertical = this.reverseVertical.bind(this); this.render = this.render.bind(this); }, setup : function(){ this.points.length = 0; this.fishes.length = 0; this.watchIds.length = 0; this.intervalCount = this.MAX_INTERVAL_COUNT; this.width = this.$container.width(); this.height = this.$container.height(); this.fishCount = this.FISH_COUNT * this.width / 500 * this.height / 500; this.$canvas.attr({width : this.width, height : this.height}); this.reverse = false; this.fishes.push(new FISH(this)); this.createSurfacePoints(); }, watchWindowSize : function(){ this.clearTimer(); this.tmpWidth = this.$window.width(); this.tmpHeight = this.$window.height(); this.watchIds.push(setTimeout(this.jdugeToStopResize, this.WATCH_INTERVAL)); }, clearTimer : function(){ while(this.watchIds.length > 0){ clearTimeout(this.watchIds.pop()); } }, jdugeToStopResize : function(){ var width = this.$window.width(), height = this.$window.height(), stopped = (width == this.tmpWidth && height == this.tmpHeight); this.tmpWidth = width; this.tmpHeight = height; if(stopped){ this.setup(); } }, bindEvent : function(){ this.$window.on('resize', this.watchWindowSize); this.$container.on('mouseenter', this.startEpicenter); this.$container.on('mousemove', this.moveEpicenter); this.$container.on('click', this.reverseVertical); }, getAxis : function(event){ var offset = this.$container.offset(); return { x : event.clientX - offset.left + this.$window.scrollLeft(), y : event.clientY - offset.top + this.$window.scrollTop() }; }, startEpicenter : function(event){ this.axis = this.getAxis(event); }, moveEpicenter : function(event){ var axis = this.getAxis(event); if(!this.axis){ this.axis = axis; } this.generateEpicenter(axis.x, axis.y, axis.y - this.axis.y); this.axis = axis; }, generateEpicenter : function(x, y, velocity){ if(y < this.height / 2 - this.THRESHOLD || y > this.height / 2 + this.THRESHOLD){ return; } var index = Math.round(x / this.pointInterval); if(index < 0 || index >= this.points.length){ return; } this.points[index].interfere(y, velocity); }, reverseVertical : function(){ this.reverse = !this.reverse; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].reverseVertical(); } }, controlStatus : function(){ for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateSelf(); } for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].updateNeighbors(); } if(this.fishes.length < this.fishCount){ if(--this.intervalCount == 0){ this.intervalCount = this.MAX_INTERVAL_COUNT; this.fishes.push(new FISH(this)); } } }, render : function(){ requestAnimationFrame(this.render); this.controlStatus(); this.context.clearRect(0, 0, this.width, this.height); this.context.fillStyle = 'hsl(0, 0%, 95%)'; for(var i = 0, count = this.fishes.length; i < count; i++){ this.fishes[i].render(this.context); } this.context.save(); this.context.globalCompositeOperation = 'xor'; this.context.beginPath(); this.context.moveTo(0, this.reverse ? 0 : this.height); for(var i = 0, count = this.points.length; i < count; i++){ this.points[i].render(this.context); } this.context.lineTo(this.width, this.reverse ? 0 : this.height); this.context.closePath(); this.context.fill(); this.context.restore(); } }; var SURFACE_POINT = function(renderer, x){ this.renderer = renderer; this.x = x; this.init(); }; SURFACE_POINT.prototype = { SPRING_CONSTANT : 0.03, SPRING_FRICTION : 0.9, WAVE_SPREAD : 0.3, ACCELARATION_RATE : 0.01, init : function(){ this.initHeight = this.renderer.height * this.renderer.INIT_HEIGHT_RATE; this.height = this.initHeight; this.fy = 0; this.force = {previous : 0, next : 0}; }, setPreviousPoint : function(previous){ this.previous = previous; }, setNextPoint : function(next){ this.next = next; }, interfere : function(y, velocity){ this.fy = this.renderer.height * this.ACCELARATION_RATE * ((this.renderer.height - this.height - y) >= 0 ? -1 : 1) * Math.abs(velocity); }, updateSelf : function(){ this.fy += this.SPRING_CONSTANT * (this.initHeight - this.height); this.fy *= this.SPRING_FRICTION; this.height += this.fy; }, updateNeighbors : function(){ if(this.previous){ this.force.previous = this.WAVE_SPREAD * (this.height - this.previous.height); } if(this.next){ this.force.next = this.WAVE_SPREAD * (this.height - this.next.height); } }, render : function(context){ if(this.previous){ this.previous.height += this.force.previous; this.previous.fy += this.force.previous; } if(this.next){ this.next.height += this.force.next; this.next.fy += this.force.next; } context.lineTo(this.x, this.renderer.height - this.height); } }; var FISH = function(renderer){ this.renderer = renderer; this.init(); }; FISH.prototype = { GRAVITY : 0.4, init : function(){ this.direction = Math.random() < 0.5; this.x = this.direction ? (this.renderer.width + this.renderer.THRESHOLD) : -this.renderer.THRESHOLD; this.previousY = this.y; this.vx = this.getRandomValue(4, 10) * (this.direction ? -1 : 1); if(this.renderer.reverse){ this.y = this.getRandomValue(this.renderer.height * 1 / 10, this.renderer.height * 4 / 10); this.vy = this.getRandomValue(2, 5); this.ay = this.getRandomValue(0.05, 0.2); }else{ this.y = this.getRandomValue(this.renderer.height * 6 / 10, this.renderer.height * 9 / 10); this.vy = this.getRandomValue(-5, -2); this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; this.theta = 0; this.phi = 0; }, getRandomValue : function(min, max){ return min + (max - min) * Math.random(); }, reverseVertical : function(){ this.isOut = !this.isOut; this.ay *= -1; }, controlStatus : function(context){ this.previousY = this.y; this.x += this.vx; this.y += this.vy; this.vy += this.ay; if(this.renderer.reverse){ if(this.y > this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy -= this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(0.05, 0.2); } this.isOut = false; } }else{ if(this.y < this.renderer.height * this.renderer.INIT_HEIGHT_RATE){ this.vy += this.GRAVITY; this.isOut = true; }else{ if(this.isOut){ this.ay = this.getRandomValue(-0.2, -0.05); } this.isOut = false; } } if(!this.isOut){ this.theta += Math.PI / 20; this.theta %= Math.PI * 2; this.phi += Math.PI / 30; this.phi %= Math.PI * 2; } this.renderer.generateEpicenter(this.x + (this.direction ? -1 : 1) * this.renderer.THRESHOLD, this.y, this.y - this.previousY); if(this.vx > 0 && this.x > this.renderer.width + this.renderer.THRESHOLD || this.vx < 0 && this.x < -this.renderer.THRESHOLD){ this.init(); } }, render : function(context){ context.save(); context.translate(this.x, this.y); context.rotate(Math.PI + Math.atan2(this.vy, this.vx)); context.scale(1, this.direction ? 1 : -1); context.beginPath(); context.moveTo(-30, 0); context.bezierCurveTo(-20, 15, 15, 10, 40, 0); context.bezierCurveTo(15, -10, -20, -15, -30, 0); context.fill(); context.save(); context.translate(40, 0); context.scale(0.9 + 0.2 * Math.sin(this.theta), 1); context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(5, 10, 20, 8); context.quadraticCurveTo(12, 5, 10, 0); context.quadraticCurveTo(12, -5, 20, -8); context.quadraticCurveTo(5, -10, 0, 0); context.fill(); context.restore(); context.save(); context.translate(-3, 0); context.rotate((Math.PI / 3 + Math.PI / 10 * Math.sin(this.phi)) * (this.renderer.reverse ? -1 : 1)); context.beginPath(); if(this.renderer.reverse){ context.moveTo(5, 0); context.bezierCurveTo(10, 10, 10, 30, 0, 40); context.bezierCurveTo(-12, 25, -8, 10, 0, 0); }else{ context.moveTo(-5, 0); context.bezierCurveTo(-10, -10, -10, -30, 0, -40); context.bezierCurveTo(12, -25, 8, -10, 0, 0); } context.closePath(); context.fill(); context.restore(); context.restore(); this.controlStatus(context); } }; $(function(){ RENDERER.init(); });