schedule.py 7.8 KB
# import schedule
import os
import paramiko
from .models import MonitorHost, MonitorLog
import datetime
import math
import time
import uuid
import schedule
from app.util.component.RunContinuous import run_continuously
from app.util.component.PGUtil import PGUtil
import configure


def background_job():
    try:
        # print('Hello from the background thread')
        # base_dir = os.getcwd()

        # 命令文件
        # cmd_filepath = os.path.join(base_dir, "file", "monitor.txt")
        # cmd_file = open(cmd_filepath, "r")
        # cmd = cmd_file.read()
        # cmd_file.close()
        # servers = [{'sid': 'src1', 'hostname': '172.26.99.160',
        #             'username': 'monitor', 'password': '123456'},
        #            {'sid': 'src2', 'hostname': '172.26.60.100',
        #             'username': 'root', 'password': 'DMap@123'}]

        cur_time = datetime.datetime.now()
        time_stamp = cur_time.strftime(
            "%Y-%m-%d %H:%M:%S")
        struct_time = time.strptime(time_stamp, "%Y-%m-%d  %H:%M:%S")
        d_minu_stamp = math.floor(struct_time.tm_min/10)
        f_minu_stamp = math.floor(struct_time.tm_min/5)

        sys_session = PGUtil.get_db_session(
            configure.SQLALCHEMY_DATABASE_URI)
        sys_ds = PGUtil.open_pg_data_source(
            0, configure.SQLALCHEMY_DATABASE_URI)

        hosts = sys_session.query(
            MonitorHost.host, MonitorHost.user, MonitorHost.password, MonitorHost.type, MonitorHost.srcid)
        servers = list(map(lambda host:
                           {'hostname': host.host, 'username': host.user,
                            'password': host.password, 'type': host.type,
                            'sid': host.srcid},
                           hosts))
        for info in servers:
            try:
                # 业务逻辑
                client = paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
                client.connect(hostname=info['hostname'],
                               username=info['username'], password=info['password'])

                # cpu
                order = "top -b -n1 | sed -n '3p' | awk '{print $2}'"
                stdin, stdout, stderr = client.exec_command(order)
                cpu_usage = stdout.read().decode().split("\n")[0]  # cpu使用率

                # 内存
                order = "free -m | sed -n '2p' | awk '{print $2}'"
                stdin, stdout, stderr = client.exec_command(order)
                totalMem = stdout.read().decode().split("\n")[0]  # 总内存

                order = "free -m | sed -n '2p' | awk '{print $7}'"
                stdin, stdout, stderr = client.exec_command(order)
                availableMem = stdout.read().decode().split("\n")[0]  # 可用内存

                order = "free -m | sed -n '2p' | awk '{print $3}'"
                stdin, stdout, stderr = client.exec_command(order)
                usedMem = stdout.read().decode().split("\n")[0]  # 已用内存

                # disk
                order = "df -m | grep -v 'overlay\|Filesystem' | awk '{print $1,$2,$3}' | grep /dev | awk '{print $2}' | awk -v total=0 '{total+=$1}END{print total}'"
                stdin, stdout, stderr = client.exec_command(order)
                totalDisk = int(stdout.read().decode().split("\n")
                                [0])  # 总磁盘空间,单位Mb

                order = "df -m | grep -v 'overlay\|Filesystem' | awk '{print $1,$2,$3}' | grep /dev | awk '{print $3}' | awk -v total=0 '{total+=$1}END{print total}'"
                stdin, stdout, stderr = client.exec_command(order)
                usedDisk = int(stdout.read().decode().split("\n")
                               [0])  # 已使用磁盘空间,单位Mb

                # network
                # 接收的字节数
                rx_time = []
                rx_bytes = []
                tx_time = []
                tx_bytes = []

                # 接收的字节数
                order = "ifconfig | grep RX | grep -v 'errors'| awk -v total=0 '{total+=$5}END{print total}'"
                i = 0
                while i < 2:
                    i = i+1
                    stdin, stdout, stderr = client.exec_command(order)
                    rx_time.append(time.time())
                    rx_bytes.append(int(stdout.read().decode().split("\n")[0]))

                # 发送的字节数
                order = "ifconfig | grep TX | grep -v 'errors'| awk -v total=0 '{total+=$5}END{print total}'"
                i = 0
                while i < 2:
                    i = i+1
                    stdin, stdout, stderr = client.exec_command(order)
                    tx_time.append(time.time())
                    tx_bytes.append(int(stdout.read().decode().split("\n")[0]))

                log_guid = uuid.uuid1().__str__()
                monitor_log = MonitorLog(guid=log_guid,
                                         server=info["hostname"],
                                         time_stamp=cur_time,
                                         cpu_usage=float(
                                             "%.2f" % float(cpu_usage)),
                                         total_mem=totalMem,
                                         available_mem=availableMem,
                                         used_mem=usedMem,
                                         disk=totalDisk,
                                         disk_usage=usedDisk,
                                         net_recv=float("%.2f" % float((
                                             rx_bytes[1] - rx_bytes[0])/(rx_time[1]-rx_time[0]))),
                                         net_send=float("%.2f" % float((
                                             tx_bytes[1] - tx_bytes[0])/(tx_time[1]-tx_time[0]))),
                                         date_stamp=cur_time.strftime(
                                             "%Y-%m-%d"),
                                         hour_stamp=struct_time.tm_hour,
                                         minu_stamp=struct_time.tm_min,
                                         d_minu_stamp=1 if d_minu_stamp == 0 else d_minu_stamp,
                                         f_minu_stamp=1 if f_minu_stamp == 0 else f_minu_stamp)

                sys_session.add(monitor_log)
                sys_session.commit()

                # for line in stdout:
                #     data = json.loads(line)
                #     # print(type(data))
                #     print(data)
            except Exception as e:
                sys_session.rollback()
    except e:
        print('发生了异常:', e)
    finally:
        client.close()
        if sys_session:
            sys_session.close()
        if sys_ds:
            sys_ds.Destroy()


# 记录30条记录
logs = []


def start_schedule():
    # # 1分钟巡检一次
    schedule.every(2).minutes.do(background_job)
    # schedule.every(5).seconds.do(background_job)
    stop_run_continuously = run_continuously()
    # Do some other things...
    # # Stop the background thread
    # time.sleep(10)
    # stop_run_continuously.set()


def format_value(value):
    # 1024*1024*1024
    if value > 1_073_741_824:
        value = "{}GB".format(format(value/1_073_741_824, '.1f'))
    elif value > 1_048_576:
        # 1024*1024
        value = "{}MB".format(format(value / 1_048_576, '.1f'))
    elif value > 1024:
        value = "{}KB".format(format(value / 1024.0, '.1f'))
    else:
        value = "{}B".format(format(value, '.1f'))
    return value


def Mb_format_value(value):
    if value > 1024:
        value = "{}GB".format(format(value/1024, '.1f'))
    else:
        value = "{}MB".format(format(value, '.1f'))
    return value