码迷,mamicode.com
首页 > 数据库 > 详细

DB系统预警联系人API

时间:2014-12-18 01:36:17      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   ar   io   os   sp   for   

DB系统预警联系人API

 

在我们维护系统时,需要把系统的报警信息即时传递给相应同学,如果把联系方式直接写到脚本里,对以后的维护变更将埋下祸根,尤其是成百上千的系统。
为此这里写了个获取联系人信息的API

数据库配置中心表:

CREATE TABLE `db_alertcontact` (
 `id` INT(11) NULL DEFAULT NULL,
 `levelid` INT(11) NULL DEFAULT NULL COMMENT ‘contact level‘,
 `contact` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘email or phone information‘,
 `type` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘phone/email‘,
 `username` VARCHAR(100) NULL DEFAULT NULL,
 `group` VARCHAR(80) NULL DEFAULT NULL COMMENT ‘contact group‘
)
COLLATE=‘utf8_general_ci‘
ENGINE=InnoDB;

CREATE TABLE `db_alertlevel` (
 `id` INT(11) NULL DEFAULT NULL,
 `levelname` VARCHAR(50) NULL DEFAULT NULL COMMENT ‘info/warn/err‘
)
COLLATE=‘utf8_general_ci‘
ENGINE=InnoDB;


用法帮助:
[root@skatedb55 pytest]# python contactlist.py --help
usage: Contanct API v0.1 ,(C) Copyright Skate 2014 [-h] --group GROUP --type
                                                   TYPE --level LEVEL
                                                   [--interval INTERVAL]
                                                   [--load LOAD]

optional arguments:
  -h, --help           show this help message and exit
  --group GROUP        = The contact group
  --type TYPE          = The mode of contact
  --level LEVEL        = alarm level,info/warn/err
  --interval INTERVAL  = Database query interval(s)
  --load LOAD          = The configure center database,eg:
                       load=user/pass@ip:port:dbname
[root@skatedb55 pytest]#


例子:

INSERT INTO `db_alertcontact` (`id`, `levelid`, `contact`, `type`, `username`, `group`) VALUES
 (1, 1, ‘skate1@163.com‘, ‘email‘, ‘skate1‘, ‘p1‘),
 (2, 2, ‘skate2@163.com‘, ‘email‘, ‘skate2‘, ‘p2‘),
 (3, 1, ‘1300000000‘, ‘phone‘, ‘skate3‘, ‘p2‘),
 (4, 1, ‘1311111111‘, ‘phone‘, ‘skate4‘, ‘p2‘),
 (5, 1, ‘1322222222‘, ‘phone‘, ‘skate5‘, ‘p2‘),
 (6, 2, ‘skate6@163.com‘, ‘email‘, ‘skate6‘, ‘p2‘);


INSERT INTO `db_alertlevel` (`id`, `levelname`) VALUES
 (1, ‘info‘),
 (2, ‘warn‘),
 (3, ‘error‘);


[root@skatedb55 pytest]# python contactlist.py --group=p2 --type=phone --level=info --interval=10--load=root/root@10.20.0.55:3306:test6
1300000000,1311111111,1322222222,
[root@skatedb55 pytest]#

[root@skatedb55 pytest]# python contactlist.py --group=p2 --type=email --level=warn --interval=10--load=root/root@10.20.0.55:3306:test6
skate2@163.com,skate6@163.com,
[root@skatedb55 pytest]#


优点:
1.在变更联系人或联系方式不需要修改代码
2.联系人的相关信息存储在配置中心数据库,为了减少对数据库的查询,默认每天查一次数据库(自己可以指定),把联系信息放在本地,既提高了速度,也减少了对配置中心的依赖
3.如果想在变更联系信息及时生效,只需把本地的临时文件"/tmp/contact_dbinfo"删除即可

 

contactlist.py:

  1. # -*- coding: utf-8 -*-  
  2. #!/usr/bin/python  
  3. #  
  4. # Author:Skate  
  5. # Time:2014/12/10  
  6. # Function: Contact API  
  7.   
  8. import MySQLdb,sys  
  9. import argparse  
  10. import os  
  11. import datetime  
  12.   
  13. class database:  
  14.       def __int__(self,host,user,passwd,port,dbname):  
  15.           self.conn = None  
  16.           pass  
  17.       def conn(self,host,user,passwd,port,dbname):  
  18.           self.host=host  
  19.           self.user=user  
  20.           self.passwd=passwd  
  21.           self.port=port  
  22.           self.dbname=dbname  
  23.           try:   
  24.               self.conn = MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.dbname,port=self.port)   
  25.     
  26.           except MySQLdb.Error, e:   
  27.               print "MySQL Connect Error: %s" % (e.args[1])   
  28.           return self.conn   
  29.       def closeConn(self):  
  30.           self.conn.close()  
  31.       def execute(self,sql,param):  
  32.           if self.conn==None or self.conn.open==False :  
  33.              return -1  
  34.              sys.exit  
  35.           cur = self.conn.cursor()  
  36.           cur.execute(sql,param)  
  37.           self.closeConn()  
  38.           return cur  
  39.   
  40. def contactlist(group,type,level,host,user,passwd,port,dbname,interval=86400):  
  41.      tfile=‘/tmp/contact_dbinfo‘  
  42.      list=‘‘  
  43.      if os.path.isfile(tfile):  
  44.         a1=datetime.datetime.fromtimestamp(os.path.getctime(tfile))  
  45.         a2=datetime.datetime.now()  
  46.         diffsec = (a2 - a1).seconds  
  47.         if diffsec > interval:  
  48.            os.remove(tfile)     
  49.            f=open(tfile,‘a‘)      
  50.            db=database()  
  51.            db.conn(host,user,passwd,port,dbname)  
  52.            sql="select t.contact,t.username,t.group,t.`type`,l.levelname from db_alertcontact t , db_alertlevel  l where  t.levelid=l.id and l.levelname=%s and t.group=%s and t.`type`=%s"  
  53.            param=(level,group,type)  
  54.            cur=db.execute(sql,param)  
  55.            results=cur.fetchall()  
  56.            for row in results:  
  57.                if row[3] ==‘phone‘:  
  58.                   #for r in row:  
  59.                   list = list + row[0] + ‘,‘  
  60.                elif row[3] == ‘email‘:  
  61.                   #for r in row:  
  62.                   list = list + row[0] + ‘,‘  
  63.            if type ==‘phone‘:  
  64.                f.write(‘phonelist=‘+ group + ‘:‘ + list + ‘\n‘)  
  65.                f.close()  
  66.            elif type == ‘email‘:  
  67.                f.write(‘emaillist=‘+ group + ‘:‘ +list + ‘\n‘)  
  68.                f.close()  
  69.         else:  
  70.              strsearch = type + ‘list=‘+ group  
  71.              istype = os.popen(‘cat ‘+ tfile +‘ | grep ‘ + strsearch + ‘ | wc -l‘).readline().strip()  
  72.              if int(istype) > 0:     
  73.                  line = os.popen(‘cat ‘+ tfile +‘ | grep ‘ + strsearch).readline().strip()  
  74.                  b=line.split(‘=‘)  
  75.                  a=b[1].split(":")  
  76.                  if b[0]==‘phonelist‘:  
  77.                      list=a[1]  
  78.                  elif b[0]==‘emaillist‘:  
  79.                      list=a[1]  
  80.              elif int(istype) < 1:  
  81.                   f=open(tfile,‘a‘)  
  82.                   db=database()  
  83.                   db.conn(host,user,passwd,port,dbname)  
  84.                   sql="select t.contact,t.username,t.group,t.`type`,l.levelname from db_alertcontact t , db_alertlevel  l where  t.levelid=l.id and l.levelname=%s and t.group=%s and t.`type`=%s"  
  85.                   param=(level,group,type)  
  86.                   cur=db.execute(sql,param)  
  87.                   results=cur.fetchall()  
  88.                   #list=‘‘  
  89.                   for row in results:  
  90.                       if row[3] ==‘phone‘:  
  91.                           list = list + row[0] + ‘,‘  
  92.                       elif row[3] == ‘email‘:  
  93.                           list = list + row[0] + ‘,‘  
  94.                   if type ==‘phone‘:  
  95.                        f.write(‘phonelist=‘+  group + ‘:‘ + list + ‘\n‘)  
  96.                        f.close()  
  97.                   elif type == ‘email‘:  
  98.                        f.write(‘emaillist=‘+  group + ‘:‘ + list + ‘\n‘)  
  99.                        f.close()  
  100.   
  101.      else:  
  102.            f=open(tfile,‘a‘)  
  103.            db=database()  
  104.            db.conn(host,user,passwd,port,dbname)  
  105.            sql="select t.contact,t.username,t.group,t.`type`,l.levelname from db_alertcontact t , db_alertlevel  l where  t.levelid=l.id and l.levelname=%s and t.group=%s and t.`type`=%s"  
  106.            param=(level,group,type)  
  107.            cur=db.execute(sql,param)  
  108.            results=cur.fetchall()  
  109.   
  110.            for row in results:  
  111.                if row[3] ==‘phone‘:  
  112.                   #for r in row:  
  113.                   list = list + row[0] + ‘,‘  
  114.                elif row[3] == ‘email‘:  
  115.                   #for r in row:  
  116.                   list = list + row[0] + ‘,‘  
  117.   
  118.            if type ==‘phone‘:  
  119.   
  120.                f.write(‘phonelist=‘+  group + ‘:‘ + list + ‘\n‘)  
  121.                f.close()  
  122.            elif type == ‘email‘:  
  123.                f.write(‘emaillist=‘+  group + ‘:‘ + list + ‘\n‘)  
  124.                f.close()  
  125.   
  126.      return list  
  127.   
  128. if __name__ == "__main__":  
  129.   parser = argparse.ArgumentParser("Contanct API v0.1 ,(C) Copyright Skate 2014")  
  130.   parser.add_argument(‘--group‘, action=‘store‘, dest=‘group‘,required=True,  
  131.         help=" = The contact group")  
  132.   
  133.   parser.add_argument(‘--type‘, action=‘store‘, dest=‘type‘,required=True,  
  134.         help=" = The mode of contact")  
  135.   
  136.   parser.add_argument(‘--level‘, action=‘store‘, dest=‘level‘,required=True,  
  137.         help=" = alarm level,info/warn/err")  
  138.   
  139.   parser.add_argument(‘--interval‘, action=‘store‘, dest=‘interval‘,type=int,default=86400,  
  140.         help=" = Database query interval")  
  141.   
  142.   parser.add_argument(‘--load‘, action=‘store‘, dest=‘load‘,default=‘‘,  
  143.         help=" = The configure center database,eg: \n load=user/pass@ip:port:dbname")  
  144.   
  145.   results = parser.parse_args()  
  146.   
  147.   load = results.load  
  148.   group = results.group  
  149.   type = results.type  
  150.   level = results.level  
  151.   interval = results.interval   
  152.   
  153.   if (load !=‘‘):  
  154.      user_info,url =  load.split("@")  
  155.      host,port,db = url.split(":")  
  156.      port=int(port)  
  157.      user,passwd = user_info.split("/",1)  
  158.   
  159.   str = contactlist(group,type,level,host,user,passwd,port,db,interval)  
  160.   print str  

 

DB系统预警联系人API

标签:des   style   blog   http   ar   io   os   sp   for   

原文地址:http://www.cnblogs.com/yishujiayuan/p/4170797.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!