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

数据库配置中心表

 1CREATE TABLE `db_alertcontact` (
 2 `id` INT(11) NULL DEFAULT NULL,
 3 `levelid` INT(11) NULL DEFAULT NULL COMMENT 'contact level',
 4 `contact` VARCHAR(50) NULL DEFAULT NULL COMMENT 'email or phone information',
 5 `type` VARCHAR(50) NULL DEFAULT NULL COMMENT 'phone/email',
 6 `username` VARCHAR(100) NULL DEFAULT NULL,
 7 `group` VARCHAR(80) NULL DEFAULT NULL COMMENT 'contact group'
 8)
 9COLLATE='utf8_general_ci'
10ENGINE=InnoDB;
11CREATE TABLE `db_alertlevel` (
12 `id` INT(11) NULL DEFAULT NULL,
13 `levelname` VARCHAR(50) NULL DEFAULT NULL COMMENT 'info/warn/err'
14)
15COLLATE='utf8_general_ci'
16ENGINE=InnoDB;

用法帮助

 1[root@skatedb55 pytest]# python contactlist.py --help
 2usage: Contanct API v0.1 ,(C) Copyright Skate 2014 [-h] --group GROUP --type
 3                                                   TYPE --level LEVEL
 4                                                   [--interval INTERVAL]
 5                                                   [--load LOAD]
 6optional arguments:
 7  -h, --help           show this help message and exit
 8  --group GROUP        = The contact group
 9  --type TYPE          = The mode of contact
10  --level LEVEL        = alarm level,info/warn/err
11  --interval INTERVAL  = Database query interval(s)
12  --load LOAD          = The configure center database,eg:
13                       load=user/pass@ip:port:dbname
14[root@skatedb55 pytest]#

例子

 1INSERT INTO `db_alertcontact` (`id`, `levelid`, `contact`, `type`, `username`, `group`) VALUES
 2 (1, 1, 'skate1@163.com', 'email', 'skate1', 'p1'),
 3 (2, 2, 'skate2@163.com', 'email', 'skate2', 'p2'),
 4 (3, 1, '1300000000', 'phone', 'skate3', 'p2'),
 5 (4, 1, '1311111111', 'phone', 'skate4', 'p2'),
 6 (5, 1, '1322222222', 'phone', 'skate5', 'p2'),
 7 (6, 2, 'skate6@163.com', 'email', 'skate6', 'p2');
 8INSERT INTO `db_alertlevel` (`id`, `levelname`) VALUES
 9 (1, 'info'),
10 (2, 'warn'),
11 (3, 'error');
12[root@skatedb55 pytest]# python contactlist.py --group=p2 --type=phone --level=info --interval=10--load=root/root@10.20.0.55:3306:test6
131300000000,1311111111,1322222222,
14[root@skatedb55 pytest]#
15[root@skatedb55 pytest]# python contactlist.py --group=p2 --type=email --level=warn --interval=10--load=root/root@10.20.0.55:3306:test6
16skate2@163.com,skate6@163.com,
17[root@skatedb55 pytest]#

优点:

1.在变更联系人或联系方式不需要修改代码

2.联系人的相关信息存储在配置中心数据库,为了减少对数据库的查询,默认每天查一次数据库(自己可以指定),把联系信息放在本地,既提高了速度,也减少了对配置中心的依赖

3.如果想在变更联系信息及时生效,只需把本地的临时文件”/tmp/contact_dbinfo”删除即可

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