DB system alert contact API and db alert api

Source: Internet
Author: User
Tags mysql connect

DB system alert contact API and db alert api

Author: Skate
Time: 2014/12/16

 

Database System Alert contact API

 

When we maintain the system, we need to transmit the system's alarm information to the corresponding students in real time. If we directly write the contact information in the script, it will cause future maintenance changes, in particular, hundreds of systems.
For this reason, an API is provided to obtain contact information.

Database Configuration center table:

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;


Usage help:
[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] #


Example:

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, '123', 'phone', 'skate3 ', 'p2 '),
(4, 1, '000000', 'phone', 'skate', 'p2 '),
(5, 1, '000000', '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
13001000000,13111111, 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] #


Advantages:
1. You do not need to modify the code when changing the contact or contact information.
2. the contact information is stored in the configuration center database. To reduce the number of queries to the database, the database is queried once a day by default (you can specify the contact information yourself), which improves the speed, reduces the dependency on the configuration center.
3. If you want the change contact information to take effect immediately, you only need to delete the local temporary file "/tmp/contact_dbinfo ".

 

Contactlist. py:

# -*- coding: utf-8 -*-#!/usr/bin/python## Author:Skate# Time:2014/12/10# Function: Contact APIimport MySQLdb,sysimport argparseimport osimport datetimeclass database:      def __int__(self,host,user,passwd,port,dbname):          self.conn = None          pass      def conn(self,host,user,passwd,port,dbname):          self.host=host          self.user=user          self.passwd=passwd          self.port=port          self.dbname=dbname          try:               self.conn = MySQLdb.connect(host=self.host, user=self.user, passwd=self.passwd, db=self.dbname,port=self.port)             except MySQLdb.Error, e:               print "MySQL Connect Error: %s" % (e.args[1])           return self.conn       def closeConn(self):          self.conn.close()      def execute(self,sql,param):          if self.conn==None or self.conn.open==False :             return -1             sys.exit          cur = self.conn.cursor()          cur.execute(sql,param)          self.closeConn()          return curdef contactlist(group,type,level,host,user,passwd,port,dbname,interval=86400):     tfile='/tmp/contact_dbinfo'     list=''     if os.path.isfile(tfile):        a1=datetime.datetime.fromtimestamp(os.path.getctime(tfile))        a2=datetime.datetime.now()        diffsec = (a2 - a1).seconds        if diffsec > interval:           os.remove(tfile)              f=open(tfile,'a')               db=database()           db.conn(host,user,passwd,port,dbname)           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"           param=(level,group,type)           cur=db.execute(sql,param)           results=cur.fetchall()           for row in results:               if row[3] =='phone':                  #for r in row:                  list = list + row[0] + ','               elif row[3] == 'email':                  #for r in row:                  list = list + row[0] + ','           if type =='phone':               f.write('phonelist='+ group + ':' + list + '\n')               f.close()           elif type == 'email':               f.write('emaillist='+ group + ':' +list + '\n')               f.close()        else:             strsearch = type + 'list='+ group             istype = os.popen('cat '+ tfile +' | grep ' + strsearch + ' | wc -l').readline().strip()             if int(istype) > 0:                    line = os.popen('cat '+ tfile +' | grep ' + strsearch).readline().strip()                 b=line.split('=')                 a=b[1].split(":")                 if b[0]=='phonelist':                     list=a[1]                 elif b[0]=='emaillist':                     list=a[1]             elif int(istype) < 1:                  f=open(tfile,'a')                  db=database()                  db.conn(host,user,passwd,port,dbname)                  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"                  param=(level,group,type)                  cur=db.execute(sql,param)                  results=cur.fetchall()                  #list=''                  for row in results:                      if row[3] =='phone':                          list = list + row[0] + ','                      elif row[3] == 'email':                          list = list + row[0] + ','                  if type =='phone':                       f.write('phonelist='+  group + ':' + list + '\n')                       f.close()                  elif type == 'email':                       f.write('emaillist='+  group + ':' + list + '\n')                       f.close()     else:           f=open(tfile,'a')           db=database()           db.conn(host,user,passwd,port,dbname)           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"           param=(level,group,type)           cur=db.execute(sql,param)           results=cur.fetchall()           for row in results:               if row[3] =='phone':                  #for r in row:                  list = list + row[0] + ','               elif row[3] == 'email':                  #for r in row:                  list = list + row[0] + ','           if type =='phone':               f.write('phonelist='+  group + ':' + list + '\n')               f.close()           elif type == 'email':               f.write('emaillist='+  group + ':' + list + '\n')               f.close()     return listif __name__ == "__main__":  parser = argparse.ArgumentParser("Contanct API v0.1 ,(C) Copyright Skate 2014")  parser.add_argument('--group', action='store', dest='group',required=True,        help=" = The contact group")  parser.add_argument('--type', action='store', dest='type',required=True,        help=" = The mode of contact")  parser.add_argument('--level', action='store', dest='level',required=True,        help=" = alarm level,info/warn/err")  parser.add_argument('--interval', action='store', dest='interval',type=int,default=86400,        help=" = Database query interval")  parser.add_argument('--load', action='store', dest='load',default='',        help=" = The configure center database,eg: \n load=user/pass@ip:port:dbname")  results = parser.parse_args()  load = results.load  group = results.group  type = results.type  level = results.level  interval = results.interval   if (load !=''):     user_info,url =  load.split("@")     host,port,db = url.split(":")     port=int(port)     user,passwd = user_info.split("/",1)  str = contactlist(group,type,level,host,user,passwd,port,db,interval)  print str



 

You have good comments.


------ End -------

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.