DB System alert Contact API

Source: Internet
Author: User
Tags mysql connect readline

Author:skate
Time:2014/12/16

DB System alert Contact API

When we maintain the system, we need to send the system's alarm information to the corresponding students immediately, if the contact method is written directly into the script, the future maintenance changes will be buried in the curse, especially hundreds of thousands of systems.
So here's an API for getting contact information.

Database Configuration Center table:

CREATE TABLE ' Db_alertcontact ' (
' ID ' INT (one) null DEFAULT null,
' Levelid ' INT (one) null DEFAULT null COMMENT ' contact level ',
' Contact ' VARCHAR (+) null DEFAULT null COMMENT ' email or phone information ',
' Type ' VARCHAR ($) null DEFAULT null COMMENT ' Phone/email ',
' Username ' VARCHAR (+) null DEFAULT null,
' group ' VARCHAR null DEFAULT null COMMENT ' Contact Group '
)
Collate= ' Utf8_general_ci '
Engine=innodb;

CREATE TABLE ' Db_alertlevel ' (
' ID ' INT (one) null DEFAULT null,
' LevelName ' VARCHAR (+) null DEFAULT null COMMENT ' Info/warn/err '
)
Collate= ' Utf8_general_ci '
Engine=innodb;


usage Help:
[email protected] pytest]# python contactlist.py--help
Usage:contanct API v0.1, (C) Copyright skate [-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
--load Load = The Configure Center Database,eg:
load=user/[email protected]:p ort:dbname
[Email protected] pytest]#


Example:

INSERT into ' db_alertcontact ' (' IDs ', ' levelid ', ' contact ', ' type ', ' username ', ' group ') VALUES
(1, 1, '[email protected]', ' email ', ' skate1 ', ' P1 '),
(2, 2, '[email protected]', ' email ', ' skate2 ', ' P2 '),
(3, 1, ' 1300000000 ', ' phone ', ' skate3 ', ' P2 '),
(4, 1, ' 1311111111 ', ' phone ', ' skate4 ', ' P2 '),
(5, 1, ' 1322222222 ', ' phone ', ' skate5 ', ' P2 '),
(6, 2, '[email protected]', ' email ', ' skate6 ', ' P2 ');


INSERT into ' db_alertlevel ' (' id ', ' levelname ') VALUES
(1, ' info '),
(2, ' warn '),
(3, ' Error ');


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

[email protected] pytest]# python contactlist.py--group=p2--type=email--level=warn--interval=10--load=root/[ Email protected]: 3306:test6
[email protected],[email protected],
[Email protected] pytest]#


Advantages:
1. Change the contact or contact no need to change the code
2. Contact information is stored in the Configuration center database, in order to reduce the database query, the database is checked once a day, the contact information on-premises, both to improve the speed and reduce the dependency on the configuration center
3. If you want to make changes to the contact information in a timely manner, simply remove the local temporary file "/tmp/contact_dbinfo"

contactlist.py:

#-*-Coding:utf-8-*-#!/usr/bin/python
# author:skate# TIME:2014/12/10
Import mysqldb,sysimport argparseimport osimport datetimeclass database:def __int__ (Self,host,user,passwd,port,dbnam          E): 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.C onn.open==false:return-1 sys.exit cur = self.conn.cursor () cur.execute (SQL,PA RAM) Self.closeconn () return curdef contactlist (group,type,level,host,user,passwd,port,dbname,interval=8 6400): 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.remov           E (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.level Id=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_aler               Tcontact 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 ': lis                  t = 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,ty PE) 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") parser.add_argument ('--group ', action= ' store ', dest= ' Group ', required=true, help= "= the Contact Group") parser.add_argument ('--type ', action= ' store ', dest= ' type ', Requi Red=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=" = Databas E query Interval ") parser.add_argument ('--load ', action= ' store ', dest= ' load ', default= ', help=" = The Configure CE Nter Database,eg: \ n load=user/[email protected]:p ort:dbname ") results = Parser.parse_args () load = results.load g Roup = Results.group Type = Results.type level = Results.level interval = Results.interval if (load! = "): User_i  Nfo,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


Everyone has a good opinion, welcome to put forward


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

DB System alert Contact API

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.