3 from monitor import database
5 from monitor.wrapper import plc, plccache
6 from monitor.wrapper import mailer
9 from monitor.const import *
10 from monitor import util
11 from monitor import config
14 from datetime import datetime, timedelta
17 def gethostlist(hostlist_file):
18 return util.file.getListFromFile(hostlist_file)
20 def array_to_priority_map(array):
21 """ Create a mapping where each entry of array is given a priority equal
22 to its position in the array. This is useful for subsequent use in the
31 def cmpValMap(v1, v2, map):
32 if v1 in map and v2 in map and map[v1] < map[v2]:
34 elif v1 in map and v2 in map and map[v1] > map[v2]:
36 elif v1 in map and v2 in map:
39 raise Exception("No index %s or %s in map" % (v1, v2))
41 def cmpCategoryVal(v1, v2):
42 # Terrible hack to manage migration to no more 'ALPHA' states.
43 if v1 == 'ALPHA': v1 = "PROD"
44 if v2 == 'ALPHA': v2 = "PROD"
45 #map = array_to_priority_map([ None, 'PROD', 'ALPHA', 'OLDBOOTCD', 'UNKNOWN', 'FORCED', 'ERROR', ])
46 map = array_to_priority_map([ None, 'ALPHA', 'PROD', 'OLDBOOTCD', 'UNKNOWN', 'FORCED', 'ERROR', ])
47 return cmpValMap(v1,v2,map)
51 def __init__(self, hostname):
52 self.hostname = hostname
58 def previous_attempt(self):
60 def setValidMapping(self):
64 def __init__(self, key, valuepattern, action):
71 # connect one penalty to another, in a FSM diagram. After one
72 # condition/penalty is applied, move to the next phase.
76 def __init__(self, ticket_id = None):
77 self.ticket_id = ticket_id
79 print "getting ticket status",
80 self.status = mailer.getTicketStatus(self.ticket_id)
83 def setTicketStatus(self, status):
84 mailer.setTicketStatus(self.ticket_id, status)
85 self.status = mailer.getTicketStatus(self.ticket_id)
88 def getTicketStatus(self):
90 self.status = mailer.getTicketStatus(self.ticket_id)
93 def closeTicket(self):
94 mailer.closeTicketViaRT(self.ticket_id, "Ticket CLOSED automatically by SiteAssist.")
96 def email(self, subject, body, to):
97 self.ticket_id = mailer.emailViaRT(subject, body, to, self.ticket_id)
100 class Message(object):
101 def __init__(self, subject, message, via_rt=True, ticket_id=None, **kwargs):
103 self.subject = subject
104 self.message = message
105 self.rt = RT(ticket_id)
109 return self.rt.email(self.subject, self.message, to)
111 return mailer.email(self.subject, self.message, to)
113 class Recent(object):
114 def __init__(self, withintime):
115 self.withintime = withintime
118 self.time = self.__getattribute__('time')
120 self.time = time.time()- 7*24*60*60
122 #self.time = time.time()
123 #self.action_taken = False
126 if self.time + self.withintime < time.time():
127 self.action_taken = False
129 if self.time + self.withintime > time.time() and self.action_taken:
134 def unsetRecent(self):
135 self.action_taken = False
136 self.time = time.time()
140 self.action_taken = True
141 self.time = time.time()
144 class PersistFlags(Recent):
145 def __new__(typ, id, *args, **kwargs):
153 pm = database.dbLoad(db)
155 database.dbDump(db, {})
156 pm = database.dbLoad(db)
161 obj = super(PersistFlags, typ).__new__(typ, *args, **kwargs)
162 for key in kwargs.keys():
163 obj.__setattr__(key, kwargs[key])
164 obj.time = time.time()
165 obj.action_taken = False
170 def __init__(self, id, withintime, **kwargs):
172 Recent.__init__(self, withintime)
175 pm = database.dbLoad(self.db)
177 database.dbDump(self.db, pm)
179 def resetFlag(self, name):
180 self.__setattr__(name, False)
182 def setFlag(self, name):
183 self.__setattr__(name, True)
185 def getFlag(self, name):
187 return self.__getattribute__(name)
189 self.__setattr__(name, False)
192 def resetRecentFlag(self, name):
196 def setRecentFlag(self, name):
200 def getRecentFlag(self, name):
201 # if recent and flag set -> true
204 return self.isRecent() & self.__getattribute__(name)
206 self.__setattr__(name, False)
209 def checkattr(self, name):
211 x = self.__getattribute__(name)
217 class PersistMessage(Message):
218 def __new__(typ, id, subject, message, via_rt, **kwargs):
222 db = "persistmessages"
225 pm = database.dbLoad(db)
227 database.dbDump(db, {})
228 pm = database.dbLoad(db)
232 #print "Using existing object"
235 #print "creating new object"
236 obj = super(PersistMessage, typ).__new__(typ, [id, subject, message, via_rt], **kwargs)
238 obj.actiontracker = Recent(1*60*60*24)
241 if 'ticket_id' in kwargs and kwargs['ticket_id'] is not None:
242 obj.ticket_id = kwargs['ticket_id']
247 def __init__(self, id, subject, message, via_rt=True, **kwargs):
248 print "initializing object: %s" % self.ticket_id
250 Message.__init__(self, subject, message, via_rt, self.ticket_id)
253 self.actiontracker.unsetRecent()
256 pm = database.dbLoad(self.db)
258 database.dbDump(self.db, pm)
261 if not self.actiontracker.isRecent():
262 self.ticket_id = Message.send(self, to)
263 self.actiontracker.setRecent()
266 # NOTE: only send a new message every week, regardless.
267 # NOTE: can cause thank-you messages to be lost, for instance when node comes back online within window.
268 print "Not sending to host b/c not within window of %s days" % (self.actiontracker.withintime // (60*60*24))
270 class MonitorMessage(object):
271 def __new__(typ, id, *args, **kwargs):
275 db = "monitormessages"
278 if 'reset' in kwargs and kwargs['reset'] == True:
279 database.dbDump(db, {})
280 pm = database.dbLoad(db)
282 database.dbDump(db, {})
283 pm = database.dbLoad(db)
287 print "Using existing object"
290 print "creating new object"
291 obj = super(object, typ).__new__(typ, id, *args, **kwargs)
293 obj.sp = PersistSitePenalty(id, 0)
298 def __init__(self, id, message):
302 class SitePenalty(object):
304 penalty_map.append( { 'name': 'noop', 'enable' : lambda host: None,
305 'disable' : lambda host: None } )
306 penalty_map.append( { 'name': 'nocreate', 'enable' : lambda host: plc.removeSliceCreation(host),
307 'disable' : lambda host: plc.enableSliceCreation(host) } )
308 penalty_map.append( { 'name': 'suspendslices', 'enable' : lambda host: plc.suspendSlices(host),
309 'disable' : lambda host: plc.enableSlices(host) } )
311 #def __init__(self, index=0, **kwargs):
314 def get_penalties(self):
315 # TODO: get penalties actually applied to a node from PLC DB.
316 return [ n['name'] for n in SitePenalty.penalty_map ]
319 self.index = self.index + 1
320 if self.index > len(SitePenalty.penalty_map)-1: self.index = len(SitePenalty.penalty_map)-1
324 self.index = self.index - 1
325 if self.index < 0: self.index = 0
328 def apply(self, host):
330 for i in range(len(SitePenalty.penalty_map)-1,self.index,-1):
331 print "\tdisabling %s on %s" % (SitePenalty.penalty_map[i]['name'], host)
332 SitePenalty.penalty_map[i]['disable'](host)
334 for i in range(0,self.index+1):
335 print "\tapplying %s on %s" % (SitePenalty.penalty_map[i]['name'], host)
336 SitePenalty.penalty_map[i]['enable'](host)
342 class PersistSitePenalty(SitePenalty):
343 def __new__(typ, id, index, **kwargs):
347 db = "persistpenalties"
350 if 'reset' in kwargs and kwargs['reset'] == True:
351 database.dbDump(db, {})
352 pm = database.dbLoad(db)
354 database.dbDump(db, {})
355 pm = database.dbLoad(db)
359 print "Using existing object"
362 print "creating new object"
363 obj = super(PersistSitePenalty, typ).__new__(typ, [index], **kwargs)
370 def __init__(self, id, index, **kwargs):
374 pm = database.dbLoad(self.db)
376 database.dbDump(self.db, pm)
381 Each host has a target set of attributes. Some may be set manually,
382 or others are set globally for the preferred target.
385 All nodes in the Alpha or Beta group would have constraints like:
386 [ { 'state' : 'BOOT', 'kernel' : '2.6.22' } ]
388 def __init__(self, constraints):
389 self.constraints = constraints
391 def verify(self, data):
393 self.constraints is a list of key, value pairs.
394 # [ {... : ...}==AND , ... , ... , ] == OR
397 for con in self.constraints:
398 #print "con: %s" % con
400 for key in con.keys():
401 #print "looking at key: %s" % key
403 #print "%s %s" % (con[key], data[key])
404 con_and_true = con_and_true & (con[key] in data[key])
405 elif key not in data:
406 print "missing key %s" % key
409 con_or_true = con_or_true | con_and_true
413 class Record(object):
415 def __init__(self, hostname, data):
416 self.hostname = hostname
418 self.plcdb_hn2lb = plccache.plcdb_hn2lb
419 self.loginbase = self.plcdb_hn2lb[self.hostname]
423 def stageIswaitforever(self):
424 if 'waitforever' in self.data['stage']:
430 category = self.data['category']
431 prev_category = self.data['prev_category']
432 #print "SEVERITY: ", category, prev_category
433 val = cmpCategoryVal(category, prev_category)
437 return self.severity() > 0
439 def end_record(self):
440 return node_end_record(self.hostname)
442 def reset_stage(self):
443 self.data['stage'] = 'findbad'
446 def getCategory(self):
447 return self.data['category'].lower()
450 return self.data['state'].lower()
452 def getDaysDown(cls, diag_record):
454 if diag_record['comonstats']['uptime'] != "null" and diag_record['comonstats']['uptime'] != "-1":
455 daysdown = - int(float(diag_record['comonstats']['uptime'])) // (60*60*24)
456 #elif diag_record['comonstats']['sshstatus'] != "null":
457 # daysdown = int(diag_record['comonstats']['sshstatus']) // (60*60*24)
458 #elif diag_record['comonstats']['lastcotop'] != "null":
459 # daysdown = int(diag_record['comonstats']['lastcotop']) // (60*60*24)
462 last_contact = diag_record['plcnode']['last_contact']
463 if last_contact == None:
464 # the node has never been up, so give it a break
467 diff = now - last_contact
468 daysdown = diff // (60*60*24)
470 getDaysDown = classmethod(getDaysDown)
472 def getStrDaysDown(cls, diag_record):
474 last_contact = diag_record['plcnode']['last_contact']
475 date_created = diag_record['plcnode']['date_created']
477 if diag_record['comonstats']['uptime'] != "null" and \
478 diag_record['comonstats']['uptime'] != "-1":
479 daysdown = int(float(diag_record['comonstats']['uptime'])) // (60*60*24)
480 daysdown = "%d days up" % daysdown
482 elif last_contact is None:
483 if date_created is not None:
485 diff = now - date_created
486 daysdown = diff // (60*60*24)
487 daysdown = "Never contacted PLC, created %s days ago" % daysdown
489 daysdown = "Never contacted PLC"
492 diff = now - last_contact
493 daysdown = diff // (60*60*24)
494 daysdown = "%s days down" % daysdown
496 getStrDaysDown = classmethod(getStrDaysDown)
498 def getSendEmailFlag(self):
502 # resend if open & created longer than 30 days ago.
503 if 'rt' in self.data and \
504 'Status' in self.data['rt'] and \
505 "open" in self.data['rt']['Status'] and \
506 self.data['rt']['Created'] > int(time.time() - 60*60*24*30):
507 # if created-time is greater than the thirty days ago from the current time
512 def getMostRecentStage(self):
513 lastact = self.data['last_action_record']
516 def getMostRecentTime(self):
517 lastact = self.data['last_action_record']
518 return lastact.date_action_taken
520 def takeAction(self, index=0):
521 pp = PersistSitePenalty(self.hostname, 0, db='persistpenalty_hostnames')
522 if 'improvement' in self.data['stage'] or self.improved() or \
523 'monitor-end-record' in self.data['stage']:
524 print "takeAction: decreasing penalty for %s"%self.hostname
528 print "takeAction: increasing penalty for %s"%self.hostname
531 print "takeAction: applying penalty to %s as index %s"% (self.hostname, index)
533 pp.apply(self.hostname)
536 def _format_diaginfo(self):
537 info = self.data['info']
538 print "FORMAT : STAGE: ", self.data['stage']
539 if self.data['stage'] == 'monitor-end-record':
540 if info[2] == "ALPHA": info = (info[0], info[1], "PROD")
541 hlist = " %s went from '%s' to '%s'\n" % (info[0], info[1], info[2])
543 hlist = " %s %s - %s\n" % (info[0], info[2], info[1]) #(node,ver,daysdn)
545 def saveAction(self):
546 if 'save_act_all' in self.data and self.data['save_act_all'] == True:
551 def getMessage(self, ticket_id=None):
552 self.data['args']['hostname'] = self.hostname
553 self.data['args']['loginbase'] = self.loginbase
554 self.data['args']['hostname_list'] = self._format_diaginfo()
555 #print self.data['message']
556 if self.data['message']:
557 message = PersistMessage(self.hostname,
558 self.data['message'][0] % self.data['args'],
559 self.data['message'][1] % self.data['args'],
560 True, db='monitor_persistmessages',
562 if self.data['stage'] == "improvement":
568 def getContacts(self):
569 roles = self.data['email']
571 if not config.mail and not config.debug and config.bcc:
573 if config.mail and config.debug:
579 contacts += [config.email]
581 #contacts += [TECHEMAIL % self.loginbase]
582 contacts += plc.getTechEmails(self.loginbase)
584 #contacts += [PIEMAIL % self.loginbase]
585 contacts += plc.getPIEmails(self.loginbase)
587 contacts += plc.getSliceUserEmails(self.loginbase)
588 slices = plc.slices(self.loginbase)
590 #for slice in slices:
591 # contacts += [SLICEMAIL % slice]
592 print "SLIC: %20s : %d slices" % (self.loginbase, len(slices))
594 print "SLIC: %20s : 0 slices" % self.loginbase
600 def __init__(self, hostname, target):
601 self.hostname = hostname
606 class MonRecord(object):
607 def __init__(self, data):
608 self.keys = data.keys()
610 self.__dict__.update(data)
616 ret[k] = self.__dict__[k]
621 str += self.host + "\n"
623 if "message" in k or "msg" in k:
626 s_time=time.strftime("%Y/%m/%d %H:%M:%S",
627 time.gmtime(self.__dict__[k]))
628 str += "\t'%s' : %s\n" % (k, s_time)
630 str += "\t'%s' : %s\n" % (k, self.__dict__[k])
634 def delField(self, field):
635 if field in self.__dict__:
636 del self.__dict__[field]
638 if field in self.keys:
639 for i in range(0,len(self.keys)):
640 if self.keys[i] == field:
644 class Action(MonRecord):
645 def __init__(self, host, data):
647 MonRecord.__init__(self, data)
650 def deltaDays(self, delta):
651 t = datetime.fromtimestamp(self.__dict__['time'])
652 d = t + timedelta(delta)
653 self.__dict__['time'] = time.mktime(d.timetuple())
655 def node_end_record(node):
656 act_all = database.dbLoad("act_all")
657 if node not in act_all:
661 if len(act_all[node]) == 0:
665 pm = database.dbLoad("monitor_persistmessages")
670 print "deleting node record"
672 database.dbDump("monitor_persistmessages", pm)
674 a = Action(node, act_all[node][0])
676 a.delField('found_rt_ticket')
677 a.delField('second-mail-at-oneweek')
678 a.delField('second-mail-at-twoweeks')
679 a.delField('first-found')
681 rec['action'] = ["close_rt"]
682 rec['category'] = "ALPHA" # assume that it's up...
683 rec['stage'] = "monitor-end-record"
684 rec['ticket_id'] = None
685 rec['time'] = time.time() - 7*60*60*24
686 act_all[node].insert(0,rec)
687 database.dbDump("act_all", act_all)
693 def __init__(self, list=None):
695 if self.list == None:
698 def find(self, host, filter, timerange):
699 if host not in self.list:
702 host_log_list = self.list[host]
703 for log in host_log_list:
704 for key in filter.keys():
705 #print "searching key %s in log keys" % key
707 #print "%s in log.keys" % key
708 cmp = re.compile(filter[key])
709 res = cmp.search(log.__getattribute__(key))
711 #print "found match in log: %s %s ~=~ %s" % (log, key, filter[key])
712 if log.time > time.time() - timerange:
713 print "returning log b/c it occured within time."
719 if host in self.list:
720 return self.list[host][0]
725 if log.host not in self.list:
726 self.list[log.host] = []
728 self.list[log.host].insert(0,log)
730 class Log(MonRecord):
731 def __init__(self, host, data):
733 MonRecord.__init__(self, data)
738 str += self.host + " : { "
740 if "message" in k or "msg" in k:
743 s_time=time.strftime("%Y/%m/%d %H:%M:%S",
744 time.gmtime(self.__dict__[k]))
745 #str += " '%s' : %s, " % (k, s_time)
747 str += "'%s' : %s, " % (k, self.__dict__[k])
752 class Diagnose(MonRecord):
753 def __init__(self, host):
755 MonRecord.__init__(self, data)
760 if __name__ == "__main__":
762 #r.email("test", "body of test message", ['database@cs.princeton.edu'])
763 #from emailTxt import mailtxt
765 #database.dbDump("persistmessages", {});
766 #args = {'url_list': 'http://www.planet-lab.org/bootcds/planet1.usb\n','hostname': 'planet1','hostname_list': ' blahblah - days down\n'}
767 #m = PersistMessage("blue", "test 1", mailtxt.newdown_one[1] % args, True)
768 #m.send(['soltesz@cs.utk.edu'])
769 #m = PersistMessage("blue", "test 1 - part 2", mailtxt.newalphacd_one[1] % args, True)
770 # TRICK timer to thinking some time has passed.
771 #m.actiontracker.time = time.time() - 6*60*60*24
772 #m.send(['soltesz@cs.utk.edu'])