update of all changes in the last week that fine-tuned the behavior of Monitor
[monitor.git] / unified_model.py
1 #!/usr/bin/python
2
3 from monitor import database
4
5 import plc
6 api = plc.getAuthAPI()
7
8 import mailer
9 import time
10
11 from model import *
12 from const import *
13 import util.file
14 import config
15
16 def gethostlist(hostlist_file):
17         return util.file.getListFromFile(hostlist_file)
18         
19         #nodes = api.GetNodes({'peer_id' : None}, ['hostname'])
20         #return [ n['hostname'] for n in nodes ]
21
22 def array_to_priority_map(array):
23         """ Create a mapping where each entry of array is given a priority equal
24         to its position in the array.  This is useful for subsequent use in the
25         cmpMap() function."""
26         map = {}
27         count = 0
28         for i in array:
29                 map[i] = count
30                 count += 1
31         return map
32
33 def cmpValMap(v1, v2, map):
34         if v1 in map and v2 in map and map[v1] < map[v2]:
35                 return 1
36         elif v1 in map and v2 in map and map[v1] > map[v2]:
37                 return -1
38         elif v1 in map and v2 in map:
39                 return 0
40         else:
41                 raise Exception("No index %s or %s in map" % (v1, v2))
42
43 def cmpCategoryVal(v1, v2):
44         map = array_to_priority_map([ None, 'ALPHA', 'PROD', 'OLDBOOTCD', 'UNKNOWN', 'FORCED', 'ERROR', ])
45         return cmpValMap(v1,v2,map)
46
47
48 class PCU:
49         def __init__(self, hostname):
50                 self.hostname = hostname
51
52         def reboot(self):
53                 return True
54         def available(self):
55                 return True
56         def previous_attempt(self):
57                 return True
58         def setValidMapping(self):
59                 pass
60
61 class Penalty:
62         def __init__(self, key, valuepattern, action):
63                 pass
64
65 class PenaltyMap:
66         def __init__(self):
67                 pass
68
69         # connect one penalty to another, in a FSM diagram.  After one
70         #       condition/penalty is applied, move to the next phase.
71
72
73 #fb = database.dbLoad("findbad")
74
75 class RT(object):
76         def __init__(self, ticket_id = None):
77                 self.ticket_id = ticket_id
78                 if self.ticket_id:
79                         print "getting ticket status",
80                         self.status = mailer.getTicketStatus(self.ticket_id)
81                         print self.status
82
83         def setTicketStatus(self, status):
84                 mailer.setTicketStatus(self.ticket_id, status)
85                 self.status = mailer.getTicketStatus(self.ticket_id)
86                 return True
87         
88         def getTicketStatus(self):
89                 if not self.status:
90                         self.status = mailer.getTicketStatus(self.ticket_id)
91                 return self.status
92
93         def closeTicket(self):
94                 mailer.closeTicketViaRT(self.ticket_id, "Ticket CLOSED automatically by SiteAssist.") 
95
96         def email(self, subject, body, to):
97                 self.ticket_id = mailer.emailViaRT(subject, body, to, self.ticket_id)
98                 return self.ticket_id
99
100 class Message(object):
101         def __init__(self, subject, message, via_rt=True, ticket_id=None, **kwargs):
102                 self.via_rt = via_rt
103                 self.subject = subject
104                 self.message = message
105                 self.rt = RT(ticket_id)
106
107         def send(self, to):
108                 if self.via_rt:
109                         return self.rt.email(self.subject, self.message, to)
110                 else:
111                         return mailer.email(self.subject, self.message, to)
112
113 class Recent(object):
114         def __init__(self, withintime):
115                 self.withintime = withintime
116
117                 try:
118                         self.time = self.__getattribute__('time')
119                 except:
120                         self.time = time.time()- 7*24*60*60
121
122                 #self.time = time.time()
123                 #self.action_taken = False
124
125         def isRecent(self):
126                 if self.time + self.withintime < time.time():
127                         self.action_taken = False
128
129                 if self.time + self.withintime > time.time() and self.action_taken:
130                         return True
131                 else:
132                         return False
133
134         def unsetRecent(self):
135                 self.action_taken = False
136                 self.time = time.time()
137                 return True
138
139         def setRecent(self):
140                 self.action_taken = True
141                 self.time = time.time()
142                 return True
143                 
144 class PersistFlags(Recent):
145         def __new__(typ, id, *args, **kwargs):
146                 if 'db' in kwargs:
147                         db = kwargs['db']
148                         del kwargs['db']
149                 else:
150                         db = "persistflags"
151
152                 try:
153                         pm = database.dbLoad(db)
154                 except:
155                         database.dbDump(db, {})
156                         pm = database.dbLoad(db)
157                 #print pm
158                 if id in pm:
159                         obj = pm[id]
160                 else:
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
166
167                 obj.db = db
168                 return obj
169
170         def __init__(self, id, withintime, **kwargs):
171                 self.id = id
172                 Recent.__init__(self, withintime)
173
174         def save(self):
175                 pm = database.dbLoad(self.db)
176                 pm[self.id] = self
177                 database.dbDump(self.db, pm)
178
179         def resetFlag(self, name):
180                 self.__setattr__(name, False)
181
182         def setFlag(self, name):
183                 self.__setattr__(name, True)
184                 
185         def getFlag(self, name):
186                 try:
187                         return self.__getattribute__(name)
188                 except:
189                         self.__setattr__(name, False)
190                         return False
191
192         def resetRecentFlag(self, name):
193                 self.resetFlag(name)
194                 self.unsetRecent()
195
196         def setRecentFlag(self, name):
197                 self.setFlag(name)
198                 self.setRecent()
199
200         def getRecentFlag(self, name):
201                 # if recent and flag set -> true
202                 # else false
203                 try:
204                         return self.isRecent() & self.__getattribute__(name)
205                 except:
206                         self.__setattr__(name, False)
207                         return False
208
209         def checkattr(self, name):
210                 try:
211                         x = self.__getattribute__(name)
212                         return True
213                 except:
214                         return False
215                 
216
217 class PersistMessage(Message):
218         def __new__(typ, id, subject, message, via_rt, **kwargs):
219                 if 'db' in kwargs:
220                         db = kwargs['db']
221                 else:
222                         db = "persistmessages"
223
224                 try:
225                         pm = database.dbLoad(db)
226                 except:
227                         database.dbDump(db, {})
228                         pm = database.dbLoad(db)
229
230                 #print pm
231                 if id in pm:
232                         #print "Using existing object"
233                         obj = pm[id]
234                 else:
235                         #print "creating new object"
236                         obj = super(PersistMessage, typ).__new__(typ, [id, subject, message, via_rt], **kwargs)
237                         obj.id = id
238                         obj.actiontracker = Recent(3*60*60*24)
239                         obj.ticket_id = None
240
241                 if 'ticket_id' in kwargs and kwargs['ticket_id'] is not None:
242                         obj.ticket_id = kwargs['ticket_id']
243
244                 obj.db = db
245                 return obj
246
247         def __init__(self, id, subject, message, via_rt=True, **kwargs):
248                 print "initializing object: %s" % self.ticket_id
249                 self.id = id
250                 Message.__init__(self, subject, message, via_rt, self.ticket_id)
251
252         def reset(self):
253                 self.actiontracker.unsetRecent()
254
255         def save(self):
256                 pm = database.dbLoad(self.db)
257                 pm[self.id] = self
258                 database.dbDump(self.db, pm)
259
260         def send(self, to):
261                 if not self.actiontracker.isRecent():
262                         self.ticket_id = Message.send(self, to)
263                         self.actiontracker.setRecent()
264                         self.save()
265                 else:
266                         # NOTE: only send a new message every week, regardless.
267                         print "Not sending to host b/c not within window of %s days" % (self.actiontracker.withintime // (60*60*24))
268
269 class MonitorMessage(object):
270         def __new__(typ, id, *args, **kwargs):
271                 if 'db' in kwargs:
272                         db = kwargs['db']
273                 else:
274                         db = "monitormessages"
275
276                 try:
277                         if 'reset' in kwargs and kwargs['reset'] == True:
278                                 database.dbDump(db, {})
279                         pm = database.dbLoad(db)
280                 except:
281                         database.dbDump(db, {})
282                         pm = database.dbLoad(db)
283
284                 #print pm
285                 if id in pm:
286                         print "Using existing object"
287                         obj = pm[id]
288                 else:
289                         print "creating new object"
290                         obj = super(object, typ).__new__(typ, id, *args, **kwargs)
291                         obj.id = id
292                         obj.sp = PersistSitePenalty(id, 0)
293
294                 obj.db = db
295                 return obj
296
297         def __init__(self, id, message):
298                 pass
299                 
300
301 class SitePenalty(object):
302         penalty_map = [] 
303         penalty_map.append( { 'name': 'noop',                   'enable'   : lambda host: None,
304                                                                                                         'disable'  : lambda host: None } )
305         penalty_map.append( { 'name': 'nocreate',               'enable'   : lambda host: plc.removeSliceCreation(host),
306                                                                                                         'disable'  : lambda host: plc.enableSliceCreation(host) } )
307         penalty_map.append( { 'name': 'suspendslices',  'enable'   : lambda host: plc.suspendSlices(host),
308                                                                                                         'disable'  : lambda host: plc.enableSlices(host) } )
309
310         #def __init__(self, index=0, **kwargs):
311         #       self.index = index
312
313         def get_penalties(self):
314                 # TODO: get penalties actually applied to a node from PLC DB.
315                 return [ n['name'] for n in SitePenalty.penalty_map ] 
316
317         def increase(self):
318                 self.index = self.index + 1
319                 if self.index > len(SitePenalty.penalty_map)-1: self.index = len(SitePenalty.penalty_map)-1
320                 return True
321
322         def decrease(self):
323                 self.index = self.index - 1
324                 if self.index < 0: self.index = 0
325                 return True
326
327         def apply(self, host):
328
329                 for i in range(len(SitePenalty.penalty_map)-1,self.index,-1):
330                         print "\tdisabling %s on %s" % (SitePenalty.penalty_map[i]['name'], host)
331                         SitePenalty.penalty_map[i]['disable'](host)
332
333                 for i in range(0,self.index+1):
334                         print "\tapplying %s on %s" % (SitePenalty.penalty_map[i]['name'], host)
335                         SitePenalty.penalty_map[i]['enable'](host)
336
337                 return
338
339
340
341 class PersistSitePenalty(SitePenalty):
342         def __new__(typ, id, index, **kwargs):
343                 if 'db' in kwargs:
344                         db = kwargs['db']
345                 else:
346                         db = "persistpenalties"
347
348                 try:
349                         if 'reset' in kwargs and kwargs['reset'] == True:
350                                 database.dbDump(db, {})
351                         pm = database.dbLoad(db)
352                 except:
353                         database.dbDump(db, {})
354                         pm = database.dbLoad(db)
355
356                 #print pm
357                 if id in pm:
358                         print "Using existing object"
359                         obj = pm[id]
360                 else:
361                         print "creating new object"
362                         obj = super(PersistSitePenalty, typ).__new__(typ, [index], **kwargs)
363                         obj.id = id
364                         obj.index = index
365
366                 obj.db = db
367                 return obj
368
369         def __init__(self, id, index, **kwargs):
370                 self.id = id
371
372         def save(self):
373                 pm = database.dbLoad(self.db)
374                 pm[self.id] = self
375                 database.dbDump(self.db, pm)
376
377
378 class Target:
379         """
380                 Each host has a target set of attributes.  Some may be set manually,
381                 or others are set globally for the preferred target.
382
383                 For instance:
384                         All nodes in the Alpha or Beta group would have constraints like:
385                                 [ { 'state' : 'BOOT', 'kernel' : '2.6.22' } ]
386         """
387         def __init__(self, constraints):
388                 self.constraints = constraints
389
390         def verify(self, data):
391                 """
392                         self.constraints is a list of key, value pairs.
393                         # [ {... : ...}==AND , ... , ... , ] == OR
394                 """
395                 con_or_true = False
396                 for con in self.constraints:
397                         #print "con: %s" % con
398                         con_and_true = True
399                         for key in con.keys():
400                                 #print "looking at key: %s" % key
401                                 if key in data: 
402                                         #print "%s %s" % (con[key], data[key])
403                                         con_and_true = con_and_true & (con[key] in data[key])
404                                 elif key not in data:
405                                         print "missing key %s" % key
406                                         con_and_true = False
407
408                         con_or_true = con_or_true | con_and_true
409
410                 return con_or_true
411
412 class Record(object):
413
414         def __init__(self, hostname, data):
415                 self.hostname = hostname
416                 self.data = data
417                 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
418                 self.loginbase = self.plcdb_hn2lb[self.hostname]
419                 return
420
421
422         def stageIswaitforever(self):
423                 if 'waitforever' in self.data['stage']:
424                         return True
425                 else:
426                         return False
427
428         def severity(self):
429                 category = self.data['category']
430                 prev_category = self.data['prev_category']
431                 #print "SEVERITY: ", category, prev_category
432                 val = cmpCategoryVal(category, prev_category)
433                 return val 
434
435         def improved(self):
436                 return self.severity() > 0
437         
438         def end_record(self):
439                 return node_end_record(self.hostname)
440
441         def reset_stage(self):
442                 self.data['stage'] = 'findbad'
443                 return True
444         
445         def getCategory(self):
446                 return self.data['category'].lower()
447
448         def getState(self):
449                 return self.data['state'].lower()
450
451         def getDaysDown(cls, diag_record):
452                 daysdown = -1
453                 if diag_record['comonstats']['uptime'] != "null":
454                         daysdown = - int(float(diag_record['comonstats']['uptime'])) // (60*60*24)
455                 #elif diag_record['comonstats']['sshstatus'] != "null":
456                 #       daysdown = int(diag_record['comonstats']['sshstatus']) // (60*60*24)
457                 #elif diag_record['comonstats']['lastcotop'] != "null":
458                 #       daysdown = int(diag_record['comonstats']['lastcotop']) // (60*60*24)
459                 else:
460                         now = time.time()
461                         last_contact = diag_record['plcnode']['last_contact']
462                         if last_contact == None:
463                                 # the node has never been up, so give it a break
464                                 daysdown = -1
465                         else:
466                                 diff = now - last_contact
467                                 daysdown = diff // (60*60*24)
468                 return daysdown
469         getDaysDown = classmethod(getDaysDown)
470
471         def getStrDaysDown(cls, diag_record):
472                 daysdown = "unknown"
473                 last_contact = diag_record['plcnode']['last_contact']
474                 date_created = diag_record['plcnode']['date_created']
475
476                 if      diag_record['comonstats']['uptime'] != "null" and \
477                         diag_record['comonstats']['uptime'] != "-1":
478                         daysdown = int(float(diag_record['comonstats']['uptime'])) // (60*60*24)
479                         daysdown = "%d days up" % daysdown
480
481                 elif last_contact is None:
482                         if date_created is not None:
483                                 now = time.time()
484                                 diff = now - date_created
485                                 daysdown = diff // (60*60*24)
486                                 daysdown = "Never contacted PLC, created %s days ago" % daysdown
487                         else:
488                                 daysdown = "Never contacted PLC"
489                 else:
490                         now = time.time()
491                         diff = now - last_contact
492                         daysdown = diff // (60*60*24)
493                         daysdown = "%s days down" % daysdown
494                 return daysdown
495         getStrDaysDown = classmethod(getStrDaysDown)
496
497         #def getStrDaysDown(cls, diag_record):
498         #       daysdown = cls.getDaysDown(diag_record)
499         #       if daysdown > 0:
500         #               return "%d days down"%daysdown
501         #       elif daysdown == -1:
502         #               return "Never online"
503         #       else:
504         #               return "%d days up"% -daysdown
505         #getStrDaysDown = classmethod(getStrDaysDown)
506
507         def takeAction(self):
508                 pp = PersistSitePenalty(self.hostname, 0, db='persistpenalty_hostnames')
509                 if 'improvement' in self.data['stage'] or self.improved() or \
510                         'monitor-end-record' in self.data['stage']:
511                         print "takeAction: decreasing penalty for %s"%self.hostname
512                         pp.decrease()
513                         pp.decrease()
514                 else:
515                         print "takeAction: increasing penalty for %s"%self.hostname
516                         pp.increase()
517                 pp.apply(self.hostname)
518                 pp.save()
519
520         def _format_diaginfo(self):
521                 info = self.data['info']
522                 print "FORMAT : STAGE: ", self.data['stage']
523                 if self.data['stage'] == 'monitor-end-record':
524                         if info[2] == "ALPHA": info = (info[0], info[1], "PROD")
525                         hlist = "    %s went from '%s' to '%s'\n" % (info[0], info[1], info[2]) 
526                 else:
527                         hlist = "    %s %s - %s\n" % (info[0], info[2], info[1]) #(node,ver,daysdn)
528                 return hlist
529         def saveAction(self):
530                 if 'save-act-all' in self.data and self.data['save-act-all'] == True:
531                         return True
532                 else:
533                         return False
534
535         def getMessage(self, ticket_id=None):
536                 self.data['args']['hostname'] = self.hostname
537                 self.data['args']['loginbase'] = self.loginbase
538                 self.data['args']['hostname_list'] = self._format_diaginfo()
539                 #print self.data['message']
540                 if self.data['message']:
541                         message = PersistMessage(self.hostname, 
542                                                                  self.data['message'][0] % self.data['args'],
543                                                                  self.data['message'][1] % self.data['args'],
544                                                                  True, db='monitor_persistmessages',
545                                                                  ticket_id=ticket_id)
546                         return message
547                 else:
548                         return None
549         
550         def getContacts(self):
551                 roles = self.data['email']
552
553                 if not config.mail and not config.debug and config.bcc:
554                         roles = ADMIN
555                 if config.mail and config.debug:
556                         roles = ADMIN
557
558                 # build targets
559                 contacts = []
560                 if ADMIN & roles:
561                         contacts += [config.email]
562                 if TECH & roles:
563                         contacts += [TECHEMAIL % self.loginbase]
564                 if PI & roles:
565                         contacts += [PIEMAIL % self.loginbase]
566                 if USER & roles:
567                         slices = plc.slices(self.loginbase)
568                         if len(slices) >= 1:
569                                 for slice in slices:
570                                         contacts += [SLICEMAIL % slice]
571                                 print "SLIC: %20s : %d slices" % (self.loginbase, len(slices))
572                         else:
573                                 print "SLIC: %20s : 0 slices" % self.loginbase
574
575                 return contacts
576
577
578 class NodeRecord:
579         def __init__(self, hostname, target):
580                 self.hostname = hostname
581                 self.ticket = None
582                 self.target = target
583                 #if hostname in fb['nodes']:
584                 #       self.data = fb['nodes'][hostname]['values']
585                 #else:
586                 #       raise Exception("Hostname not in scan database")
587
588         def stageIswaitforever(self):
589                 if 'waitforever' in self.data['stage']:
590                         return True
591                 else:
592                         return False
593
594         def severity(self):
595                 category = self.data['category']
596                 prev_category = self.data['prev_category']
597                 print "IMPROVED: ", category, prev_category
598                 val = cmpCategoryVal(category, prev_category)
599                 return val 
600
601         def improved(self):
602                 return self.severity() > 0
603         
604         def end_record(self):
605                 return node_end_record(self.hostname)
606
607         def reset_stage(self):
608                 self.data['stage'] = 'findbad'
609                 return True
610
611         def open_tickets(self):
612                 if self.ticket and self.ticket.status['status'] == 'open':
613                         return 1
614                 return 0
615         def setIntrospect(self):
616                 pass
617
618         def email_notice(self):
619                 message = self._get_message_for_condition()
620                 message.send(self._get_contacts_for_condition())
621                 return True
622         def close_ticket(self):
623                 if self.ticket:
624                         self.ticket.closeTicket()
625
626         def exempt_from_penalties(self):
627                 bl = database.dbLoad("l_blacklist")
628                 return self.hostname in bl
629
630         def penalties(self):
631                 return []
632         def escellate_penalty(self):
633                 return True
634         def reduce_penalty(self):
635                 return True
636
637
638         def atTarget(self):
639                 return self.target.verify(self.data)
640
641         def _get_condition(self):
642                 return self.data['category'].lower()
643
644         def _get_stage(self):
645                 "improvement"
646                 "firstnotice_noop"
647                 "secondnotice_noslicecreation"
648                 "thirdnotice_disableslices"
649
650                 delta = current_time - self.data['time']
651
652         def _get_message_for_condition(self):
653                 pass
654         def _get_contacts_for_condition(self):
655                 pass
656
657 class Action(MonRecord):
658         def __init__(self, host, data):
659                 self.host = host
660                 MonRecord.__init__(self, data)
661                 return
662
663         def deltaDays(self, delta):
664                 t = datetime.fromtimestamp(self.__dict__['time'])
665                 d = t + timedelta(delta)
666                 self.__dict__['time'] = time.mktime(d.timetuple())
667                 
668 def node_end_record(node):
669         act_all = database.dbLoad("act_all")
670         if node not in act_all:
671                 del act_all
672                 return False
673
674         if len(act_all[node]) == 0:
675                 del act_all
676                 return False
677
678         pm = database.dbLoad("monitor_persistmessages")
679         if node not in pm:
680                 del pm
681                 return False
682         else:
683                 print "deleting node record"
684                 del pm[node]
685                 database.dbDump("monitor_persistmessages", pm)
686
687         a = Action(node, act_all[node][0])
688         a.delField('rt')
689         a.delField('found_rt_ticket')
690         a.delField('second-mail-at-oneweek')
691         a.delField('second-mail-at-twoweeks')
692         a.delField('first-found')
693         rec = a.get()
694         rec['action'] = ["close_rt"]
695         rec['category'] = "ALPHA"       # assume that it's up...
696         rec['stage'] = "monitor-end-record"
697         rec['ticket_id'] = None
698         rec['time'] = time.time() - 7*60*60*24
699         act_all[node].insert(0,rec)
700         database.dbDump("act_all", act_all)
701         del act_all
702         return True
703
704 if __name__ == "__main__":
705         #r = RT()
706         #r.email("test", "body of test message", ['database@cs.princeton.edu'])
707         #from emailTxt import mailtxt
708         print "loaded"
709         #database.dbDump("persistmessages", {});
710         #args = {'url_list': 'http://www.planet-lab.org/bootcds/planet1.usb\n','hostname': 'planet1','hostname_list': ' blahblah -  days down\n'}
711         #m = PersistMessage("blue", "test 1", mailtxt.newdown_one[1] % args, True)
712         #m.send(['soltesz@cs.utk.edu'])
713         #m = PersistMessage("blue", "test 1 - part 2", mailtxt.newalphacd_one[1] % args, True)
714         # TRICK timer to thinking some time has passed.
715         #m.actiontracker.time = time.time() - 6*60*60*24
716         #m.send(['soltesz@cs.utk.edu'])