Ejemplo n.º 1
0
class notify_sendmsg(object):
    '''
    发送告警短信
    '''
    msg_conf = utils.get_config('msg_config')
    cmdb_conf = utils.get_config('cmdb_config')

    def __init__(self):
        self.__msg_config__ = {
            "host": self.msg_conf['msgdb_host'],
            "port": int(self.msg_conf['msgdb_port']),
            "user": self.msg_conf['msgdb_user'],
            "passwd": self.msg_conf['msgdb_passwd']
        }

        self.__cmdb_config__ = {
            "host": self.cmdb_conf['cmdb_host'],
            "port": int(self.cmdb_conf['cmdb_port']),
            "user": self.cmdb_conf['cmdb_user'],
            "passwd": self.cmdb_conf['cmdb_passwd'],
            "db": self.cmdb_conf['cmdb_dbname'],
            "charset": "utf8"
        }

    def send_msg(self, msg):
        '''
        发送告警短信
        :param msg:
        :return:
        '''
        print(self.__cmdb_config__)
        db_api_ExecQuery = api.db_handler_ExecQuery(self.__cmdb_config__)
        msg_receive_users = db_api_ExecQuery(
            "select name,mobile from user where username != 'admin';")
        msg_receive_users = set(msg_receive_users)
        print(msg_receive_users)
        for user_tu in msg_receive_users:
            username = user_tu[0]
            phoneNu = user_tu[1]
            content_sql = "set names 'gbk';" + "\n" + "insert into ultrax.msgsend (service, srcNo,destNo,  msgcontent) values ('30','10000', {0}, '【万步网】 {1} ');".format(
                phoneNu, msg)
            content_sql = content_sql.encode('gbk')  # 需要重新编码
            #print(content_sql)
            try:
                db_api_ExecQuery_msg = api.db_handler_ExecNonQuery(
                    self.__msg_config__)
                db_api_ExecQuery_msg(content_sql)
                logger.log_hander().debug("向用户 {0} 号码 {1} 发送短信 {2} 成功.".format(
                    username, phoneNu, msg))

            except pymysql.Warning as w:  # 异常处理
                print("Mysql Error  %s" % (w))
Ejemplo n.º 2
0
def log_hander():
    '''
    日志管理
    :return:
    '''
    # config_path = os.path.join("conf/", 'logging.conf')
    # logging.config.fileConfig(config_path)
    # return logging.getLogger()

    log_conf = utils.get_config('log')
    logger_name = log_conf["log_name"]
    logger_level = log_conf["log_level"]
    logger = logging.getLogger(logger_name)
    if not logger.handlers:
        level = eval(logger_level)
        logger.setLevel(level)
        logger_dir = log_conf["log_path"]
        if not os.path.exists(logger_dir):
            os.mkdir(logger_dir)
        logger_file = os.path.join(logger_dir, logger_name)
        fh = logging.FileHandler(logger_file)
        fh.setLevel(level)
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
        fh.setFormatter(formatter)
        logger.addHandler(fh)

    return logger
Ejemplo n.º 3
0
 def __init__(self):
     self.config = get_config()
     data = pd.read_csv(path.join(self.config['input'], 'Train.csv'))
     self.data = data
     self.test = pd.read_csv(path.join(self.config['input'], 'Test.csv'))
     self.state_map = pd.read_csv(
         path.join(self.config['input'], 'NigerianStateNames.csv'))
     self.test_ids = self.test['ID']
     self.preproc_args = get_preproc_params()
Ejemplo n.º 4
0
def main():
    base_dir = Path(__file__).parent
    data_path = base_dir / "beeminder.json"
    config = get_config(base_dir)
    data = get_data(data_path)
    today = dt.datetime.now().strftime("%Y%m%d")
    data_today = data.get(today, {})

    goal_mapping = {"firefox": handle_firefox, "goodreads": handle_goodreads}

    for key, function in goal_mapping.items():
        if f"goal:{key}" in config:
            goal = config.get(f"goal:{key}", "goal")
            original_value = data_today.get(goal)
            try:
                new_value = function(config, original_value)
                if not (new_value is None) and new_value != original_value:
                    submit_data(goal, new_value, config)
                    data_today[goal] = new_value
            except Exception as e:
                print(f"Error in command {key}: {e}")
    data[today] = data_today
    save_data(data_path, data)
Ejemplo n.º 5
0
from mysql.connector import connect, errorcode, Error
from modules.utils import get_config

config = get_config()


def db(f):
    """
    Wrap database connection for database functions.
    :param f: function to be wrapped
    :return:
    """
    def wrap(*args, **kwargs):
        try:
            cnx = connect(**config['database'])
        except Error as err:
            if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
                return_value = {
                    "status":
                    "Error: Unable to access database with given user and password."
                }
            elif err.errno == errorcode.ER_BAD_DB_ERROR:
                return_value = {"status": "Error: Database doesn't exist."}
            else:
                return_value = {"status": "Error: " + str(err)}
        else:
            return_value = f(cnx, *args, **kwargs)
            cnx.close()
        return return_value

    return wrap
Ejemplo n.º 6
0
 def setUp(self):
   self.tester = app.test_client(self)
   self.config = utils.get_config()
Ejemplo n.º 7
0
 def test_get_config(self):
     self.assertTrue(type(utils.get_config()) is dict)
     self.assertFalse(utils.get_config() == None)
Ejemplo n.º 8
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Gongzw"
# Date: 2018/4/11

import os, sys
BaseDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BaseDir)
sys.path.append(BaseDir)

import time
from modules import monitor, sendMsg
from modules import utils

slave_conf = utils.get_config('slave_config')
slave_ip_list = slave_conf["slave_host"].split(',')
print(slave_ip_list)

while True:
    #msgsend_flag = True
    send_count = 0
    last_msg = ''
    alarm_counter = {}

    for host in slave_ip_list:
        conf_dict = {
            'host': host,
            'port': int(slave_conf["slave_port"]),
            'user': slave_conf["slave_user"],
            'passwd': slave_conf["slave_passwd"],
            'charset': "utf8",
Ejemplo n.º 9
0
# -*- coding: utf-8 -*-

"""
    Main Flask App
    Author  :   Alvaro Lizama Molina <*****@*****.**>
"""

from flask import Flask
from modules.utils import get_config


######################################################
###
### Setup Main App
###
######################################################

## Get cfg path
cfg = get_config()

## Creating main app
app = Flask(__name__)
app.config.from_pyfile(cfg, silent=True)
config = app.config
Ejemplo n.º 10
0
class MySQL_monitor(object):
    '''
    监控Mysql状态
    '''
    __error__ = []
    cmdb_conf = utils.get_config('cmdb_config')

    def __init__(self, **kwargs):
        self.__config__ = kwargs
        self.__config__['cursorclass'] = pymysql.cursors.DictCursor
        self.host = kwargs['host']
        self.port = kwargs['port']
        self.__cmdb_config__ = {
            "host": self.cmdb_conf['cmdb_host'],
            "port": int(self.cmdb_conf['cmdb_port']),
            "user": self.cmdb_conf['cmdb_user'],
            "passwd": self.cmdb_conf['cmdb_passwd'],
            "db": self.cmdb_conf['cmdb_dbname'],
            "charset": "utf8"
        }

    def telnet(self, host, port, timeout=5):
        """
        测试服务器地址和端口是否畅通
        :param host: 服务器地址
        :param port: 服务器端口
        :param timeout: 测试超时时间
        :return: Boolean
        """
        try:
            tel = telnetlib.Telnet(host, port, timeout)
            tel.close()
            return True
        except:
            return False

    def connect(self, type):
        """
        创建数据库连接
        :param type:  type分为查询类型ExecQuery和非查询类型NonExecQuery(增删改)
        :return:
        """
        try:
            if self.telnet(self.__config__["host"], self.__config__["port"]):
                print("\033[34;1m数据库连接成功!\033[0m")
                if type == 'ExecQuery':
                    db_api_ExecQuery = api.db_handler_ExecQuery(
                        self.__config__)
                elif type == 'NonExecQuery':
                    db_api_ExecQuery = api.db_handler_NonExecQuery(
                        self.__config__)

                return db_api_ExecQuery
            else:
                print("unable connect mysql server {0}:{1}".format(
                    self.__config__["host"], self.__config__["port"]))
                self.__error__.append(
                    "unable connect mysql server {0}:{1}".format(
                        self.__config__["host"], self.__config__["port"]))
                return False
                # raise Exception("unable connect mysql server {0}:{1}".format(self.__config__["host"],self.__config__["port"]))

        except:
            self.__error__.append("无法连接服务器主机: {0}:{1}".format(
                self.__config__["host"], self.__config__["port"]))
            logger.log_hander().error("无法连接服务器主机: {0}:{1}".format(
                self.__config__["host"], self.__config__["port"]))

            return False

    def isSlave(self):
        """
        数据库同步是否正常
        :return: None同步未开启,False同步中断,True同步正常
        """
        db_api_ExecQuery_slave = self.connect('ExecQuery')
        if db_api_ExecQuery_slave:
            result = db_api_ExecQuery_slave("SHOW SLAVE STATUS")
            print(result)
            if result:
                db_api_ExecNonQuery = api.db_handler_ExecNonQuery(
                    self.__cmdb_config__)
                sql = "select * from seos_1.mysql_slave_status where host = '%s';" % self.host
                # print(sql)
                res = db_api_ExecQuery_slave(sql)
                if len(res) == 0:
                    sql = "insert into seos_1.mysql_slave_status (host,slave_status,delay_status,alarm_count) values ('%s',1,1,0);" % self.host
                    # print(sql)
                    db_api_ExecNonQuery(sql)

                if result[0]["Slave_SQL_Running"] == "Yes" and result[0][
                        "Slave_IO_Running"] == "Yes":
                    if result[0]["Seconds_Behind_Master"] >= 100:
                        print(
                            "\033[31;1m The slave is delay over 100s...\033[0m"
                        )
                        sql = "update seos_1.mysql_slave_status set delay_status=0 where host ='%s';" % self.host
                        db_api_ExecNonQuery(sql)
                        self.__error__.append("The Mysql slave {0}:{1} is delay over 100s...".format(self.__config__[\
                            "host"], self.__config__["port"]))
                        logger.log_hander().warn("The Mysql slave {0}:{1} is delay over 100s...".format(self.__config__[\
                            "host"], self.__config__["port"]))
                        return False
                    else:
                        print("\033[32;1m slave is ok...\033[0m")
                        sql = "update seos_1.mysql_slave_status set slave_status=1 where host ='%s';" % self.host
                        db_api_ExecNonQuery(sql)
                        return True
                else:
                    if result[0]["Slave_SQL_Running"] == "No":
                        print("\033[31;1m slave is error...\033[0m")
                        sql = "update seos_1.mysql_slave_status set slave_status=0 where host ='%s';" % self.host
                        db_api_ExecNonQuery(sql)
                        self.__error__.append(result["Last_SQL_Error"])
                    else:
                        self.__error__.append(result["Last_IO_Error"])
                    return False