def GetUserEmailAddress(user_list): ''' 根据用户列表获得邮件地址列表 ''' emails=[] if user_list == 'ALL': email_list = select('SELECT oEmail FROM osa_users') #email_list是元组 for email in email_list: emails.append(email[0]) return emails else: for user in user_list.split(','): email = select("SELECT oEmail FROM osa_users WHERE oUserName='******'") #这里是防止没有填写邮箱的情况 if email: emails.append(email[0][0]) return emails
def get_email_byname(username): ''' @通过Username来获取用户对应的邮箱 ''' sql = "select oEmail from osa_users where oUserName='******'" result = cmdtosql.select(sql) if not result or result == None: return '' return result[0][0]
def monitor_get_iteminfo(id): ''' @获取监控项目的信息 ''' sql = "select * from osa_monitors where id = "+str(id) result = cmdtosql.select(sql) if not result or result == None: return False return result
def server_get_ipinfo(ipid): ''' @根据ipid获取服务器信息 ''' sql = "select * from osa_device where oIpid = "+str(ipid) result = cmdtosql.select(sql) if not result or result == None: return False return result
def ExistInserverinfo(oMonitorId,oIpOrUrl): ''' 在osa_serverinfo里查找某条记录。若存在,返回这条记录 ''' sql = "SELECT * FROM osa_serverinfo WHERE oMonitorId = "+str(oMonitorId)+" AND oIpOrUrl='"+oIpOrUrl+"'" result = select(sql) if result: return list(result[0]) else: return None
def getoRunCycle(): ''' @获取执行周期,具体执行时间等数据 @oRunNextTime 默认为空 ''' qsql = "SELECT * from `osa_taskplan` WHERE oRunNextTime is null or oRunNextTime = '0000-00-00 00:00:00' or oRunNextTime <= '"+str(cmdtosql._get_time(flag=1))+"'" return cmdtosql.select(qsql)
def get_notice_item(): ''' @获取osa_monitor_alarm中的记录 @条件:oIsNoticeNext == 1 ''' alarmtime = (date.today()).strftime("%Y-%m-%d") + " 08:00:00" sql = "select * from osa_monitor_alarm where oIsNoticeNext = 1 and oNoticeNextTime = '"+str(alarmtime)+"'" result = cmdtosql.select(sql) if not result or result == None: return False return result
def mongodb_get_itemdata(itemid): """ @osaMonitor monogdb 获取osa_monitor_record记录 """ sql = "select * from osa_monitor_record where oItemid=" + itemid + " order by id desc limit 1" result = cmdtosql.select(sql) if not result or result == None: return None list = simplejson.loads(result[0][3]) if not list or list == None: return None return list["page_faults"]
def monitor_get_iteminfos(): ''' @osaMonitor 获取当前需要监控的项目信息 @满足时间条件和 oIsStop = 0 ''' try : time_now = cmdtosql._get_time(1) sql = "select * from osa_monitors where (oNextCheckTime is null or oNextCheckTime <='"+time_now+"') and oIsStop = 0 " log_debug("monitor_get_iteminfos()执行sql语句:"+str(sql)) return cmdtosql.select(sql) except Exception as e: log_error("monitor_get_iteminfos():"+str(e))
def monitor_get_lastReason(itemid): ''' @获取项目恢复提醒上一次的原因 ''' try: sql = "select oAlarmText from osa_monitor_alarm where oItemid="+str(itemid)+" order by id desc limit 1" result = cmdtosql.select(sql) if result: return result[0][0] else: return '' except Exception as e: log_error("monitor_get_lastReason():"+str(e))
def server_get_lastreason(ipid): ''' #获取服务器上次发生故障时间 ''' try: sql = "select oAlarmText from osa_collect_alarm where oIpid="+str(ipid)+" order by id desc limit 1" result = cmdtosql.select(sql) if result: return result[0][0] else: return '' except Exception as e: log_error("server_get_lastreason():"+str(e))
def get_mailto_users(user_list='ALL'): ''' @根据user_list的值来获取需要通知的用户列表 ''' userlist = [] if user_list=='ALL': users = cmdtosql.select("select oUserName from osa_users where oStatus='0'") for user in users: userlist.append(user[0]) return userlist else: for user in user_list.split(','): userlist.append(user) return userlist
def mysql_get_itemdata(itemid): """ @osaMonitor 获取mysql 上一次采集的数据 """ # 取距离现在最近的一条记录 sql = "select * from osa_monitor_record where oItemid =" + str(itemid) + " order by id desc limit 1" result = cmdtosql.select(sql) if not result or result == None: # 不存在结果,情况:项目第一次开始监控 return None, None if result[0][3] == "" or result[0][3] == None: return None, None list = eval(result[0][3]) if not list or list == None: # 上次结果为空,情况:上次出现exception return None, None return list["Aborted_clients"], list["Aborted_connects"]
def getoCombinCmd(Taskid,oCmdType): ''' @根据指令类型获取具体指令 ''' defaultDict = { 'BATCH_CONFIG_UPDATE':'osa_configupdate', 'BATCH_CONFIG_BACKUP':'osa_configbackup', 'BATCH_DATABASE_BACKUP':'osa_databackup', 'BATCH_DOCUMENT_DISTRIBUTION':'osa_operations', 'BATCH_FILE_CLEANER':'osa_operations', 'BATCH_SERVICE_RESTART':'osa_operations', 'BATCH_COMMAND':'osa_operations', 'BATCH_INSTALLATION':'osa_operations', 'BATCH_DISKSPACE_CHECK':'osa_operations', 'BATCH_LOADSTATE_CHECK':'osa_operations' } tabName = defaultDict[oCmdType] sql = "SELECT oCombinCmd from "+tabName+" WHERE oTaskplanid = "+str(Taskid) return cmdtosql.select(sql)
def _get_monitime(): ''' 获取采集数据入库时间 ''' sql = 'SELECT oMonTime FROM osa_monitor order by id desc limit 1' r = cmdtosql.select(sql) if not r: lasttime = '1979-01-01 00:00:00' else: lasttime = str((r[0])[0]) ltime = time.mktime(time.strptime(lasttime, "%Y-%m-%d %H:%M:%S")) ntime = time.time() if (ntime - ltime) > 600: montime = cmdtosql._get_time(1) #如果当前时间小于数据库的时间 elif (ntime - ltime) <= 0: sys.exit() else: Ltime = time.localtime( ltime + 300 ) montime = time.strftime('%Y-%m-%d %H:%M:%S', Ltime) return montime
def sendMail(subject,content,mailto): ''' @邮件发送函数 @逻辑:从osa_email_config获取邮件服务信息,进行邮件发送 ''' sql = "select * from osa_email_config limit 1" result = cmdtosql.select(sql) if not result or result == None: log_error('SMTP不能用,原因:数据表osa_email_config为空') return smtp_server = result[0][2] smtp_from = result[0][5] smtp_user = result[0][1] smtp_pass = result[0][4] smtp_port = result[0][3] msg = MIMEMultipart() msg['Subject'] = Header(subject,'utf-8') msg['From'] = smtp_from msg['To'] = mailto part = MIMEText(content,'plain','utf-8') msg.attach(part) try: smtpServer = smtplib.SMTP(smtp_server,str(smtp_port)) except Exception as e: log_error('SMTP连接邮件服务器失败,可能原因:'+str(e)) return False try: smtpServer.login(smtp_user,smtp_pass) smtpServer.sendmail(smtp_from,mailto,msg.as_string()) log_info('send mail to:'+mailto) except smtplib.SMTPException as e: log_error('SMTP发送邮件失败,可能原因:'+str(e)) finally: smtpServer.quit() return True
def ServerIsAlive(): ''' 单进程的入口函数,每隔10秒去检测服务器的状态 ''' while True: try: ipinfo = select('SELECT * FROM osa_ipinfo') except Exception as e: save_log('ERROR','select table osa_ipinfo fail:'+str(e)) AllUserEmailAddress = GetUserEmailAddress('ALL') if ipinfo: for each_ipinfo in ipinfo: try: t=threading.Thread(target=ThreadForEachServer,args=[each_ipinfo,AllUserEmailAddress]) #主进程退出后,子线程不跟着退出。 t.setDaemon(0) t.start() except Exception as e: save_log('ERROR','ServerIsAlive subThreed is error:'+str(e)) time.sleep(MONITOR['interval'])
def _get_monitime(): ''' 获取采集数据入库时间 ''' sql = 'SELECT oMonTime FROM osa_monitor order by id desc limit 1' r = cmdtosql.select(sql) if not r: lasttime = '1979-01-01 00:00:00' else: lasttime = str((r[0])[0]) ltime = time.mktime(time.strptime(lasttime, "%Y-%m-%d %H:%M:%S")) ntime = time.time() if (ntime - ltime) > 600: montime = cmdtosql._get_time(1) #如果当前时间小于数据库的时间 elif (ntime - ltime) <= 0: sys.exit() else: Ltime = time.localtime(ltime + 300) montime = time.strftime('%Y-%m-%d %H:%M:%S', Ltime) return montime
def notice_email_personality(username,itemtype,alarmlevel,itemobject): ''' @个性化设置判断该用户是否需要通知 @username:用户名,itemtype:监控项目类型,alarmlevel:报警级别,itemobject:应用对象 @return 三种类型,'not-send':不发送,'now-send':现在发送,时间字符串:表示转为下次发送时间 ''' #根据用户名来获取该用户的个性化设置 sql = "select * from osa_global_config where oUserName='******' limit 1" res = cmdtosql.select(sql) #默认一个列表,列表默认需要服务器判断的类型 typelist=['server','tcp','udp'] if not res or res == None: #说明该用户没有个性化设置,直接返回true return 'now-send' if res[0][5]:#总开关 closelist = get_list(res[0][5]) email = 'email' if email in closelist: return 'not-send' if res[0][3]: #说明个性化设置里面含有只接收指定服务器的报警 iplist = get_list(res[0][3]) if itemtype in typelist: if itemobject not in iplist: return 'not-send' if res[0][2]: #故障级别判断 levellist = get_list(res[0][2]) if str(alarmlevel) not in levellist: return 'not-send' if res[0][1]: return switch_time(res[0][1])
def GetItemNeedRun(): ''' 检查oNextCheckTime字段,返回需要运行的监控条目 ''' return cmdtosql.select(tablename="osa_alarms",condition="(oNextCheckTime is null or oNextCheckTime <= '"+str(cmdtosql._get_time(flag=1))+"') and oIsAllow=1")