5 from unified_model import cmpCategoryVal
10 from rt import is_host_in_rt_tickets
13 def get_ticket_id(record):
14 if 'ticket_id' in record and record['ticket_id'] is not "" and record['ticket_id'] is not None:
15 return record['ticket_id']
16 elif 'found_rt_ticket' in record and \
17 record['found_rt_ticket'] is not "" and \
18 record['found_rt_ticket'] is not None:
19 return record['found_rt_ticket']
23 # Time to enforce policy
26 # Where to email the summary
27 SUMTO = "soltesz@cs.princeton.edu"
28 TECHEMAIL="tech-%s@sites.planet-lab.org"
29 PIEMAIL="pi-%s@sites.planet-lab.org"
30 SLICEMAIL="%s@slices.planet-lab.org"
31 PLCEMAIL="support@planet-lab.org"
37 PITHRESH = 7 * SPERDAY
38 SLICETHRESH = 7 * SPERDAY
39 # Days before attempting rins again
40 RINSTHRESH = 5 * SPERDAY
42 # Days before calling the node dead.
43 DEADTHRESH = 30 * SPERDAY
44 # Minimum number of nodes up before squeezing
52 from unified_model import *
55 def __init__(self, l_merge):
56 self.merge_list = l_merge
58 # the hostname to loginbase mapping
59 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
61 # Previous actions taken on nodes.
62 self.act_all = database.if_cached_else(1, "act_all", lambda : {})
63 self.findbad = database.if_cached_else(1, "findbad", lambda : {})
65 self.cache_all = database.if_cached_else(1, "act_all", lambda : {})
72 # read data from findbad and act_all
73 self.mergeActionsAndBadDB()
74 # pass node_records to RT
75 return self.getRecordList()
77 def accumSickSites(self):
79 Take all nodes, from l_diagnose, look them up in the act_all database,
80 and insert them into sickdb[] as:
82 sickdb[loginbase][nodename] = fb_record
84 # look at all problems reported by findbad
85 l_nodes = self.findbad['nodes'].keys()
87 for nodename in l_nodes:
88 if nodename not in self.merge_list:
89 continue # skip this node, since it's not wanted
92 loginbase = self.plcdb_hn2lb[nodename]
93 values = self.findbad['nodes'][nodename]['values']
96 fb_record['nodename'] = nodename
98 fb_record['category'] = values['category']
102 print self.findbad['nodes'][nodename]
105 fb_record['state'] = values['state']
106 fb_record['comonstats'] = values['comonstats']
107 fb_record['plcnode'] = values['plcnode']
108 fb_record['kernel'] = self.getKernel(values['kernel'])
109 fb_record['stage'] = "findbad"
110 fb_record['message'] = None
111 fb_record['bootcd'] = values['bootcd']
112 fb_record['args'] = None
113 fb_record['info'] = None
114 fb_record['time'] = time.time()
115 fb_record['date_created'] = time.time()
117 if loginbase not in self.sickdb:
118 self.sickdb[loginbase] = {}
120 self.sickdb[loginbase][nodename] = fb_record
122 print "Found %d nodes" % count
124 def getKernel(self, unamestr):
131 def mergeActionsAndBadDB(self):
133 - Look at the sick node_records as reported in findbad,
134 - Then look at the node_records in act_all.
136 There are four cases:
137 1) Problem in findbad, no problem in act_all
138 this ok, b/c it just means it's a new problem
139 2) Problem in findbad, problem in act_all
140 -Did the problem get better or worse?
141 -If Same, or Worse, then continue looking for open tickets.
142 -If Better, or No problem, then "back-off" penalties.
143 This judgement may need to wait until 'Diagnose()'
145 3) No problem in findbad, problem in act_all
146 The the node is operational again according to Findbad()
148 4) No problem in findbad, no problem in act_all
149 There won't be a record in either db, so there's no code.
152 sorted_sites = self.sickdb.keys()
154 # look at all problems reported by findbad
155 for loginbase in sorted_sites:
156 d_fb_nodes = self.sickdb[loginbase]
157 sorted_nodes = d_fb_nodes.keys()
159 for nodename in sorted_nodes:
160 fb_record = self.sickdb[loginbase][nodename]
162 if loginbase not in self.mergedb:
163 self.mergedb[loginbase] = {}
165 # take the info either from act_all or fb-record.
166 # if node not in act_all
167 # then take it from fbrecord, obviously.
168 # else node in act_all
169 # if act_all == 0 length (no previous records)
170 # then take it from fbrecord.
172 # take it from act_all.
175 # We must compare findbad state with act_all state
176 if nodename not in self.act_all:
177 # 1) ok, b/c it's a new problem. set ticket_id to null
178 self.mergedb[loginbase][nodename] = {}
179 self.mergedb[loginbase][nodename].update(x)
180 self.mergedb[loginbase][nodename]['ticket_id'] = ""
181 self.mergedb[loginbase][nodename]['prev_category'] = "NORECORD"
183 if len(self.act_all[nodename]) == 0:
184 self.mergedb[loginbase][nodename] = {}
185 self.mergedb[loginbase][nodename].update(x)
186 self.mergedb[loginbase][nodename]['ticket_id'] = ""
187 self.mergedb[loginbase][nodename]['prev_category'] = "NORECORD"
189 y = self.act_all[nodename][0]
190 y['prev_category'] = y['category']
192 self.mergedb[loginbase][nodename] = {}
193 self.mergedb[loginbase][nodename].update(y)
194 self.mergedb[loginbase][nodename]['comonstats'] = x['comonstats']
195 self.mergedb[loginbase][nodename]['category'] = x['category']
196 self.mergedb[loginbase][nodename]['state'] = x['state']
197 self.mergedb[loginbase][nodename]['kernel']=x['kernel']
198 self.mergedb[loginbase][nodename]['bootcd']=x['bootcd']
199 self.mergedb[loginbase][nodename]['plcnode']=x['plcnode']
200 ticket = get_ticket_id(self.mergedb[loginbase][nodename])
201 self.mergedb[loginbase][nodename]['rt'] = mailer.getTicketStatus(ticket)
203 # delete the entry from cache_all to keep it out of case 3)
204 del self.cache_all[nodename]
206 # 3) nodes that remin in cache_all were not identified by findbad.
207 # Do we keep them or not?
208 # NOTE: i think that since the categories are performed before this
209 # step now, and by a monitor-controlled agent.
213 def getRecordList(self):
214 sorted_sites = self.mergedb.keys()
218 # look at all problems reported by merge
219 for loginbase in sorted_sites:
220 d_merge_nodes = self.mergedb[loginbase]
221 for nodename in d_merge_nodes.keys():
222 record = self.mergedb[loginbase][nodename]
223 ret_list.append(record)
228 def __init__(self, record_list, dbTickets, l_ticket_blacklist, target = None):
229 # Time of last update of ticket DB
230 self.record_list = record_list
231 self.dbTickets = dbTickets
233 self.l_ticket_blacklist = l_ticket_blacklist
239 for diag_node in self.record_list:
240 if diag_node != None:
241 host = diag_node['nodename']
242 (b_host_inticket, r_ticket) = is_host_in_rt_tickets(host, \
243 self.l_ticket_blacklist, \
245 diag_node['found_rt_ticket'] = None
247 #logger.debug("RT: found tickets for %s" %host)
248 diag_node['found_rt_ticket'] = r_ticket['ticket_id']
251 if r_ticket is not None:
252 print "Ignoring ticket %s" % r_ticket['ticket_id']
253 # TODO: why do i return the ticket id for a
254 # blacklisted ticket id?
255 #diag_node['found_rt_ticket'] = r_ticket['ticket_id']
256 self.count = self.count + 1
258 ret_list.append(diag_node)
260 #print "RT processed %d nodes with noticket" % self.count
261 #logger.debug("RT filtered %d noticket nodes" % self.count)
265 def __init__(self, record_list):
266 self.record_list = record_list
267 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
268 self.findbad = database.if_cached_else(1, "findbad", lambda : {})
270 self.diagnose_in = {}
271 self.diagnose_out = {}
274 self.accumSickSites()
276 #logger.debug("Accumulated %d sick sites" % len(self.diagnose_in.keys()))
279 stats = self.diagnoseAll()
280 except Exception, err:
281 print "----------------"
283 print traceback.print_exc()
285 #if config.policysavedb:
288 #print_stats("sites_observed", stats)
289 #print_stats("sites_diagnosed", stats)
290 #print_stats("nodes_diagnosed", stats)
292 return self.diagnose_out
294 def accumSickSites(self):
296 Take all nodes, from l_diagnose, look them up in the diagnose_out database,
297 and insert them into diagnose_in[] as:
299 diagnose_in[loginbase] = [diag_node1, diag_node2, ...]
301 for node_record in self.record_list:
303 nodename = node_record['nodename']
304 loginbase = self.plcdb_hn2lb[nodename]
306 if loginbase not in self.diagnose_in:
307 self.diagnose_in[loginbase] = {}
309 self.diagnose_in[loginbase][nodename] = node_record
313 def diagnoseAll(self):
315 i_sites_diagnosed = 0
316 i_nodes_diagnosed = 0
321 sorted_sites = self.diagnose_in.keys()
323 self.diagnose_out= {}
324 for loginbase in sorted_sites:
325 l_allsites += [loginbase]
327 d_diag_nodes = self.diagnose_in[loginbase]
328 d_act_records = self.__diagnoseSite(loginbase, d_diag_nodes)
329 # store records in diagnose_out, for saving later.
330 self.diagnose_out.update(d_act_records)
332 if len(d_act_records[loginbase]['nodes'].keys()) > 0:
333 i_nodes_diagnosed += (len(d_act_records[loginbase]['nodes'].keys()))
334 i_sites_diagnosed += 1
335 i_sites_observed += 1
337 return {'sites_observed': i_sites_observed,
338 'sites_diagnosed': i_sites_diagnosed,
339 'nodes_diagnosed': i_nodes_diagnosed,
340 'allsites':l_allsites}
344 def __getDaysDown(self, diag_record, nodename):
346 if diag_record['comonstats']['sshstatus'] != "null":
347 daysdown = int(diag_record['comonstats']['sshstatus']) // (60*60*24)
348 elif diag_record['comonstats']['lastcotop'] != "null":
349 daysdown = int(diag_record['comonstats']['lastcotop']) // (60*60*24)
352 last_contact = diag_record['plcnode']['last_contact']
353 if last_contact == None:
354 # the node has never been up, so give it a break
357 diff = now - last_contact
358 daysdown = diff // (60*60*24)
361 def __getStrDaysDown(self, diag_record, nodename):
362 daysdown = self.__getDaysDown(diag_record, nodename)
364 return "(%d days down)"%daysdown
366 return "Unknown number of days"
368 def __getCDVersion(self, diag_record, nodename):
370 #print "Getting kernel for: %s" % diag_record['nodename']
371 cdversion = diag_record['kernel']
374 def __diagnoseSite(self, loginbase, d_diag_nodes):
376 d_diag_nodes are diagnose_in entries.
378 d_diag_site = {loginbase : { 'config' :
385 sorted_nodes = d_diag_nodes.keys()
387 for nodename in sorted_nodes:
388 node_record = d_diag_nodes[nodename]
389 diag_record = self.__diagnoseNode(loginbase, node_record)
391 if diag_record != None:
392 d_diag_site[loginbase]['nodes'][nodename] = diag_record
394 # NOTE: improvement means, we need to act/squeeze and email.
395 #print "DIAG_RECORD", diag_record
396 if 'monitor-end-record' in diag_record['stage'] or \
397 'nmreset' in diag_record['stage']:
398 # print "resetting loginbase!"
399 d_diag_site[loginbase]['config']['squeeze'] = True
400 d_diag_site[loginbase]['config']['email'] = True
402 # print "NO IMPROVEMENT!!!!"
404 pass # there is nothing to do for this node.
406 # NOTE: these settings can be overridden by command line arguments,
407 # or the state of a record, i.e. if already in RT's Support Queue.
408 pf = PersistFlags(loginbase, 1, db='site_persistflags')
409 nodes_up = pf.nodes_up
411 d_diag_site[loginbase]['config']['squeeze'] = True
413 max_slices = self.getMaxSlices(loginbase)
414 num_nodes = pf.nodes_total #self.getNumNodes(loginbase)
415 # NOTE: when max_slices == 0, this is either a new site (the old way)
416 # or an old disabled site from previous monitor (before site['enabled'])
417 if nodes_up < num_nodes and max_slices != 0:
418 d_diag_site[loginbase]['config']['email'] = True
420 if len(d_diag_site[loginbase]['nodes'].keys()) > 0:
421 print "SITE: %20s : %d nodes up, at most" % (loginbase, nodes_up)
425 def diagRecordByCategory(self, node_record):
426 nodename = node_record['nodename']
427 category = node_record['category']
428 state = node_record['state']
429 loginbase = self.plcdb_hn2lb[nodename]
432 if "ERROR" in category: # i.e. "DOWN"
434 diag_record.update(node_record)
435 daysdown = self.__getDaysDown(diag_record, nodename)
437 # format = "DIAG: %20s : %-40s Down only %s days NOTHING DONE"
438 # print format % (loginbase, nodename, daysdown)
441 s_daysdown = self.__getStrDaysDown(diag_record, nodename)
442 diag_record['message'] = emailTxt.mailtxt.newdown
443 diag_record['args'] = {'nodename': nodename}
444 diag_record['info'] = (nodename, s_daysdown, "")
446 #if 'reboot_node_failed' in node_record:
447 # # there was a previous attempt to use the PCU.
448 # if node_record['reboot_node_failed'] == False:
449 # # then the last attempt apparently, succeeded.
450 # # But, the category is still 'ERROR'. Therefore, the
451 # # PCU-to-Node mapping is broken.
452 # #print "Setting message for ERROR node to PCU2NodeMapping: %s" % nodename
453 # diag_record['message'] = emailTxt.mailtxt.pcutonodemapping
454 # diag_record['email_pcu'] = True
456 if diag_record['ticket_id'] == "":
457 diag_record['log'] = "DOWN: %20s : %-40s == %20s %s" % \
458 (loginbase, nodename, diag_record['info'][1:], diag_record['found_rt_ticket'])
460 diag_record['log'] = "DOWN: %20s : %-40s == %20s %s" % \
461 (loginbase, nodename, diag_record['info'][1:], diag_record['ticket_id'])
463 elif "OLDBOOTCD" in category:
464 # V2 boot cds as determined by findbad
465 s_daysdown = self.__getStrDaysDown(node_record, nodename)
466 s_cdversion = self.__getCDVersion(node_record, nodename)
468 diag_record.update(node_record)
469 #if "2.4" in diag_record['kernel'] or "v2" in diag_record['bootcd']:
470 diag_record['message'] = emailTxt.mailtxt.newbootcd
471 diag_record['args'] = {'nodename': nodename}
472 diag_record['info'] = (nodename, s_daysdown, s_cdversion)
473 if diag_record['ticket_id'] == "":
474 diag_record['log'] = "BTCD: %20s : %-40s == %20s %20s %s" % \
475 (loginbase, nodename, diag_record['kernel'],
476 diag_record['bootcd'], diag_record['found_rt_ticket'])
478 diag_record['log'] = "BTCD: %20s : %-40s == %20s %20s %s" % \
479 (loginbase, nodename, diag_record['kernel'],
480 diag_record['bootcd'], diag_record['ticket_id'])
482 elif "PROD" in category:
484 # Not sure what to do with these yet. Probably need to
486 print "DEBG: %20s : %-40s NOTHING DONE" % (loginbase, nodename)
488 elif "BOOT" in state:
490 # TODO: remove penalties, if any are applied.
492 last_contact = node_record['plcnode']['last_contact']
493 if last_contact == None:
496 time_diff = now - last_contact;
498 if 'improvement' in node_record['stage']:
499 # then we need to pass this on to 'action'
501 diag_record.update(node_record)
502 diag_record['message'] = emailTxt.mailtxt.newthankyou
503 diag_record['args'] = {'nodename': nodename}
504 diag_record['info'] = (nodename, node_record['prev_category'],
505 node_record['category'])
506 #if 'email_pcu' in diag_record:
507 # if diag_record['email_pcu']:
508 # # previously, the pcu failed to reboot, so send
509 # # email. Now, reset these values to try the reboot
511 # diag_record['email_pcu'] = False
512 # del diag_record['reboot_node_failed']
514 if diag_record['ticket_id'] == "":
515 diag_record['log'] = "IMPR: %20s : %-40s == %20s %20s %s %s" % \
516 (loginbase, nodename, diag_record['stage'],
517 state, category, diag_record['found_rt_ticket'])
519 diag_record['log'] = "IMPR: %20s : %-40s == %20s %20s %s %s" % \
520 (loginbase, nodename, diag_record['stage'],
521 state, category, diag_record['ticket_id'])
523 #elif time_diff >= 6*SPERHOUR:
524 # # heartbeat is older than 30 min.
526 # #print "Possible NM problem!! %s - %s = %s" % (now, last_contact, time_diff)
528 # diag_record.update(node_record)
529 # diag_record['message'] = emailTxt.mailtxt.NMReset
530 # diag_record['args'] = {'nodename': nodename}
531 # diag_record['stage'] = "nmreset"
532 # diag_record['info'] = (nodename,
533 # node_record['prev_category'],
534 # node_record['category'])
535 # if diag_record['ticket_id'] == "":
536 # diag_record['log'] = "NM : %20s : %-40s == %20s %20s %s %s" % \
537 # (loginbase, nodename, diag_record['stage'],
538 # state, category, diag_record['found_rt_ticket'])
540 # diag_record['log'] = "NM : %20s : %-40s == %20s" % \
541 # (loginbase, nodename, diag_record['stage'])
549 elif "ALPHA" in category:
551 elif "clock_drift" in category:
553 elif "dns" in category:
555 elif "filerw" in category:
558 print "Unknown category!!!! %s" % category
563 def __diagnoseNode(self, loginbase, node_record):
564 # TODO: change the format of the hostname in this
565 # record to something more natural.
566 nodename = node_record['nodename']
567 category = node_record['category']
568 prev_category = node_record['prev_category']
569 state = node_record['state']
570 #if 'prev_category' in node_record:
571 # prev_category = node_record['prev_category']
573 # prev_category = "ERROR"
574 if node_record['prev_category'] != "NORECORD":
576 val = cmpCategoryVal(category, prev_category)
577 print "%s went from %s -> %s" % (nodename, prev_category, category)
578 if prev_category == "UNKNOWN" and category == "PROD":
579 # sending too many thank you notes to people that don't
581 # TODO: not sure what effect this will have on the node
587 if node_record['ticket_id'] == "" or node_record['ticket_id'] == None:
588 print "closing record with no ticket: ", node_record['nodename']
589 node_record['action'] = ['close_rt']
590 node_record['message'] = None
591 node_record['stage'] = 'monitor-end-record'
594 node_record['stage'] = 'improvement'
596 #if 'monitor-end-record' in node_record['stage']:
597 # # just ignore it if it's already ended.
598 # # otherwise, the status should be worse, and we won't get
600 # print "monitor-end-record: ignoring ", node_record['nodename']
605 # current category is worse than previous, carry on
608 #values are equal, carry on.
609 #print "why are we here?"
612 if 'rt' in node_record and 'Status' in node_record['rt']:
613 if node_record['stage'] == 'ticket_waitforever':
614 if 'resolved' in node_record['rt']['Status']:
615 print "ending waitforever record for: ", node_record['nodename']
616 node_record['action'] = ['noop']
617 node_record['message'] = None
618 node_record['stage'] = 'monitor-end-record'
619 print "oldlog: %s" % node_record['log'],
620 print "%15s" % node_record['action']
622 if 'new' in node_record['rt']['Status'] and \
623 'Queue' in node_record['rt'] and \
624 'Monitor' in node_record['rt']['Queue']:
626 print "RESETTING stage to findbad"
627 node_record['stage'] = 'findbad'
629 #### COMPARE category and prev_category
631 # then assign a stage based on relative priorities
633 # then check category for stats.
634 diag_record = self.diagRecordByCategory(node_record)
635 if diag_record == None:
636 #print "diag_record == None"
640 # TODO: need to record time found, and maybe add a stage for acting on it...
641 # NOTE: after found, if the support ticket is resolved, the block is
642 # not removed. How to remove the block on this?
644 #if 'found_rt_ticket' in diag_record and \
645 # diag_record['found_rt_ticket'] is not None:
646 # if diag_record['stage'] is not 'improvement':
647 # diag_record['stage'] = 'ticket_waitforever'
649 current_time = time.time()
650 # take off four days, for the delay that database caused.
651 # TODO: generalize delays at PLC, and prevent enforcement when there
652 # have been no emails.
653 # NOTE: 7*SPERDAY exists to offset the 'bad week'
654 #delta = current_time - diag_record['time'] - 7*SPERDAY
655 delta = current_time - diag_record['time']
657 message = diag_record['message']
659 act_record.update(diag_record)
662 if 'findbad' in diag_record['stage']:
663 # The node is bad, and there's no previous record of it.
664 act_record['email'] = TECH
665 act_record['action'] = ['noop']
666 act_record['message'] = message[0]
667 act_record['stage'] = 'stage_actinoneweek'
669 elif 'nmreset' in diag_record['stage']:
670 act_record['email'] = ADMIN
671 act_record['action'] = ['reset_nodemanager']
672 act_record['message'] = message[0]
673 act_record['stage'] = 'nmreset'
676 elif 'reboot_node' in diag_record['stage']:
677 act_record['email'] = TECH
678 act_record['action'] = ['noop']
679 act_record['message'] = message[0]
680 act_record['stage'] = 'stage_actinoneweek'
682 elif 'improvement' in diag_record['stage']:
683 # - backoff previous squeeze actions (slice suspend, nocreate)
684 # TODO: add a backoff_squeeze section... Needs to runthrough
685 print "backing off of %s" % nodename
686 act_record['action'] = ['close_rt']
687 act_record['message'] = message[0]
688 act_record['stage'] = 'monitor-end-record'
690 elif 'actinoneweek' in diag_record['stage']:
691 if delta >= 7 * SPERDAY:
692 act_record['email'] = TECH | PI
693 act_record['stage'] = 'stage_actintwoweeks'
694 act_record['message'] = message[1]
695 act_record['action'] = ['nocreate' ]
696 act_record['time'] = current_time # reset clock for waitforever
697 elif delta >= 3* SPERDAY and not 'second-mail-at-oneweek' in act_record:
698 act_record['email'] = TECH
699 act_record['message'] = message[0]
700 act_record['action'] = ['sendmailagain-waitforoneweekaction' ]
701 act_record['second-mail-at-oneweek'] = True
703 act_record['message'] = None
704 act_record['action'] = ['waitforoneweekaction' ]
705 print "ignoring this record for: %s" % act_record['nodename']
706 return None # don't send if there's no action
708 elif 'actintwoweeks' in diag_record['stage']:
709 if delta >= 7 * SPERDAY:
710 act_record['email'] = TECH | PI | USER
711 act_record['stage'] = 'stage_waitforever'
712 act_record['message'] = message[2]
713 act_record['action'] = ['suspendslices']
714 act_record['time'] = current_time # reset clock for waitforever
715 elif delta >= 3* SPERDAY and not 'second-mail-at-twoweeks' in act_record:
716 act_record['email'] = TECH | PI
717 act_record['message'] = message[1]
718 act_record['action'] = ['sendmailagain-waitfortwoweeksaction' ]
719 act_record['second-mail-at-twoweeks'] = True
721 act_record['message'] = None
722 act_record['action'] = ['waitfortwoweeksaction']
723 return None # don't send if there's no action
725 elif 'ticket_waitforever' in diag_record['stage']:
726 act_record['email'] = TECH
727 if 'first-found' not in act_record:
728 act_record['first-found'] = True
729 act_record['log'] += " firstfound"
730 act_record['action'] = ['ticket_waitforever']
731 act_record['message'] = None
732 act_record['time'] = current_time
734 if delta >= 7*SPERDAY:
735 act_record['action'] = ['ticket_waitforever']
736 act_record['message'] = None
737 act_record['time'] = current_time # reset clock
739 act_record['action'] = ['ticket_waitforever']
740 act_record['message'] = None
743 elif 'waitforever' in diag_record['stage']:
744 # more than 3 days since last action
745 # TODO: send only on weekdays.
746 # NOTE: expects that 'time' has been reset before entering waitforever stage
747 if delta >= 3*SPERDAY:
748 act_record['action'] = ['email-againwaitforever']
749 act_record['message'] = message[2]
750 act_record['time'] = current_time # reset clock
752 act_record['action'] = ['waitforever']
753 act_record['message'] = None
754 return None # don't send if there's no action
757 # There is no action to be taken, possibly b/c the stage has
758 # already been performed, but diagnose picked it up again.
760 # 1. stage is unknown, or
761 # 2. delta is not big enough to bump it to the next stage.
762 # TODO: figure out which. for now assume 2.
763 print "UNKNOWN stage for %s; nothing done" % nodename
764 act_record['action'] = ['unknown']
765 act_record['message'] = message[0]
767 act_record['email'] = TECH
768 act_record['action'] = ['noop']
769 act_record['message'] = message[0]
770 act_record['stage'] = 'stage_actinoneweek'
771 act_record['time'] = current_time # reset clock
776 print "%s" % act_record['log'],
777 print "%15s" % act_record['action']
780 def getMaxSlices(self, loginbase):
781 # if sickdb has a loginbase, then it will have at least one node.
784 for nodename in self.diagnose_in[loginbase].keys():
785 if nodename in self.findbad['nodes']:
786 site_stats = self.findbad['nodes'][nodename]['values']['plcsite']
789 if site_stats == None:
790 raise Exception, "loginbase with no nodes in findbad"
792 return site_stats['max_slices']
794 def getNumNodes(self, loginbase):
795 # if sickdb has a loginbase, then it will have at least one node.
798 for nodename in self.diagnose_in[loginbase].keys():
799 if nodename in self.findbad['nodes']:
800 site_stats = self.findbad['nodes'][nodename]['values']['plcsite']
803 if site_stats == None:
804 raise Exception, "loginbase with no nodes in findbad"
806 return site_stats['num_nodes']
809 Returns number of up nodes as the total number *NOT* in act_all with a
810 stage other than 'steady-state' .
812 def getUpAtSite(self, loginbase, d_diag_site):
813 # TODO: THIS DOESN"T WORK!!! it misses all the 'debug' state nodes
814 # that aren't recorded yet.
816 numnodes = self.getNumNodes(loginbase)
817 # NOTE: assume nodes we have no record of are ok. (too conservative)
818 # TODO: make the 'up' value more representative
820 for nodename in d_diag_site[loginbase]['nodes'].keys():
822 rec = d_diag_site[loginbase]['nodes'][nodename]
823 if rec['stage'] != 'monitor-end-record':
826 pass # the node is assumed to be up.
829 # print "ERROR: %s total nodes up and down != %d" % (loginbase, numnodes)
833 def close_rt_backoff(args):
834 if 'ticket_id' in args and (args['ticket_id'] != "" and args['ticket_id'] != None):
835 mailer.closeTicketViaRT(args['ticket_id'],
836 "Ticket CLOSED automatically by SiteAssist.")
837 plc.enableSlices(args['hostname'])
838 plc.enableSliceCreation(args['hostname'])
841 def reboot_node(args):
842 host = args['hostname']
843 return reboot.reboot_policy(host, True, config.debug)
846 def __init__(self, diagnose_out):
847 # the hostname to loginbase mapping
848 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
851 self.diagnose_db = diagnose_out
853 self.act_all = database.if_cached_else(1, "act_all", lambda : {})
855 # A dict of actions to specific functions. PICKLE doesnt' like lambdas.
857 self.actions['suspendslices'] = lambda args: plc.suspendSlices(args['hostname'])
858 self.actions['nocreate'] = lambda args: plc.removeSliceCreation(args['hostname'])
859 self.actions['close_rt'] = lambda args: close_rt_backoff(args)
860 self.actions['rins'] = lambda args: plc.nodeBootState(args['hostname'], "rins")
861 self.actions['noop'] = lambda args: args
862 self.actions['reboot_node'] = lambda args: reboot_node(args)
863 self.actions['reset_nodemanager'] = lambda args: args # reset_nodemanager(args)
865 self.actions['ticket_waitforever'] = lambda args: args
866 self.actions['waitforever'] = lambda args: args
867 self.actions['unknown'] = lambda args: args
868 self.actions['waitforoneweekaction'] = lambda args: args
869 self.actions['waitfortwoweeksaction'] = lambda args: args
870 self.actions['sendmailagain-waitforoneweekaction'] = lambda args: args
871 self.actions['sendmailagain-waitfortwoweeksaction'] = lambda args: args
872 self.actions['email-againwaitforever'] = lambda args: args
873 self.actions['email-againticket_waitforever'] = lambda args: args
879 #logger.debug("Accumulated %d sick sites" % len(self.sickdb.keys()))
882 stats = self.analyseSites()
883 except Exception, err:
884 print "----------------"
886 print traceback.print_exc()
888 if config.policysavedb:
889 print "Saving Databases... act_all"
890 database.dbDump("act_all", self.act_all)
891 database.dbDump("diagnose_out", self.diagnose_db)
894 #print_stats("sites_observed", stats)
895 #print_stats("sites_diagnosed", stats)
896 #print_stats("nodes_diagnosed", stats)
897 self.print_stats("sites_emailed", stats)
898 #print_stats("nodes_actedon", stats)
899 print string.join(stats['allsites'], ",")
901 if config.policysavedb:
902 print "Saving Databases... act_all"
903 #database.dbDump("policy.eventlog", self.eventlog)
904 # TODO: remove 'diagnose_out',
905 # or at least the entries that were acted on.
906 database.dbDump("act_all", self.act_all)
907 database.dbDump("diagnose_out", self.diagnose_db)
909 def accumSites(self):
911 Take all nodes, from l_action, look them up in the diagnose_db database,
912 and insert them into sickdb[] as:
914 This way only the given l_action nodes will be acted on regardless
915 of how many from diagnose_db are available.
917 sickdb[loginbase][nodename] = diag_record
919 self.sickdb = self.diagnose_db
921 def __emailSite(self, loginbase, roles, message, args):
923 loginbase is the unique site abbreviation, prepended to slice names.
924 roles contains TECH, PI, USER roles, and derive email aliases.
925 record contains {'message': [<subj>,<body>], 'args': {...}}
928 args.update({'loginbase':loginbase})
930 if not config.mail and not config.debug and config.bcc:
932 if config.mail and config.debug:
938 contacts += [config.email]
940 contacts += [TECHEMAIL % loginbase]
942 contacts += [PIEMAIL % loginbase]
944 slices = plc.slices(loginbase)
947 contacts += [SLICEMAIL % slice]
948 print "SLIC: %20s : %d slices" % (loginbase, len(slices))
950 print "SLIC: %20s : 0 slices" % loginbase
953 subject = message[0] % args
954 body = message[1] % args
957 if 'ticket_id' in args:
958 subj = "Re: [PL #%s] %s" % (args['ticket_id'], subject)
960 subj = "Re: [PL noticket] %s" % subject
961 mailer.email(subj, body, contacts)
962 ticket_id = args['ticket_id']
964 ticket_id = mailer.emailViaRT(subject, body, contacts, args['ticket_id'])
965 except Exception, err:
966 print "exception on message:"
968 print traceback.print_exc()
974 def _format_diaginfo(self, diag_node):
975 info = diag_node['info']
976 if diag_node['stage'] == 'monitor-end-record':
977 hlist = " %s went from '%s' to '%s'\n" % (info[0], info[1], info[2])
979 hlist = " %s %s - %s\n" % (info[0], info[2], info[1]) #(node,ver,daysdn)
983 def get_email_args(self, act_recordlist, loginbase=None):
986 email_args['hostname_list'] = ""
987 email_args['url_list'] = ""
989 for act_record in act_recordlist:
990 email_args['hostname_list'] += act_record['msg_format']
991 email_args['hostname'] = act_record['nodename']
992 email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/iso/%s.iso\n"
993 email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/usb/%s.usb\n"
994 email_args['url_list'] += "\n"
995 if 'plcnode' in act_record and \
996 'pcu_ids' in act_record['plcnode'] and \
997 len(act_record['plcnode']['pcu_ids']) > 0:
998 print "setting 'pcu_id' for email_args %s"%email_args['hostname']
999 email_args['pcu_id'] = act_record['plcnode']['pcu_ids'][0]
1001 email_args['pcu_id'] = "-1"
1003 if 'ticket_id' in act_record:
1004 if act_record['ticket_id'] == 0 or act_record['ticket_id'] == '0':
1005 print "Enter the ticket_id for %s @ %s" % (loginbase, act_record['nodename'])
1007 line = sys.stdin.readline()
1009 ticket_id = int(line)
1011 print "could not get ticket_id from stdin..."
1014 ticket_id = act_record['ticket_id']
1016 email_args['ticket_id'] = ticket_id
1020 def get_unique_issues(self, act_recordlist):
1021 # NOTE: only send one email per site, per problem...
1023 for act_record in act_recordlist:
1024 act_key = act_record['action'][0]
1025 if act_key not in unique_issues:
1026 unique_issues[act_key] = []
1028 unique_issues[act_key] += [act_record]
1030 return unique_issues
1033 def __actOnSite(self, loginbase, site_record):
1039 for nodename in site_record['nodes'].keys():
1040 diag_record = site_record['nodes'][nodename]
1041 act_record = self.__actOnNode(diag_record)
1042 #print "nodename: %s %s" % (nodename, act_record)
1043 if act_record is not None:
1044 act_recordlist += [act_record]
1046 unique_issues = self.get_unique_issues(act_recordlist)
1048 for issue in unique_issues.keys():
1049 print "\tworking on issue: %s" % issue
1050 issue_record_list = unique_issues[issue]
1051 email_args = self.get_email_args(issue_record_list, loginbase)
1054 #for act_record in issue_record_list:
1055 # # if there's a pcu record and email config is set
1056 # if 'email_pcu' in act_record:
1057 # if act_record['message'] != None and act_record['email_pcu'] and site_record['config']['email']:
1058 # # and 'reboot_node' in act_record['stage']:
1060 # email_args['hostname'] = act_record['nodename']
1061 # ticket_id = self.__emailSite(loginbase,
1062 # act_record['email'],
1063 # emailTxt.mailtxt.pcudown[0],
1065 # if ticket_id == 0:
1067 # print "got a ticket_id == 0!!!! %s" % act_record['nodename']
1070 # email_args['ticket_id'] = ticket_id
1073 act_record = issue_record_list[0]
1074 # send message before squeezing
1075 print "\t\tconfig.email: %s and %s" % (act_record['message'] != None,
1076 site_record['config']['email'])
1077 if act_record['message'] != None and site_record['config']['email']:
1078 ticket_id = self.__emailSite(loginbase, act_record['email'],
1079 act_record['message'], email_args)
1083 print "ticket_id == 0 for %s %s" % (loginbase, act_record['nodename'])
1088 # Add ticket_id to ALL nodenames
1089 for act_record in issue_record_list:
1090 nodename = act_record['nodename']
1091 # update node record with RT ticket_id
1092 if nodename in self.act_all:
1093 self.act_all[nodename][0]['ticket_id'] = "%s" % ticket_id
1094 # if the ticket was previously resolved, reset it to new.
1095 if 'rt' in act_record and \
1096 'Status' in act_record['rt'] and \
1097 act_record['rt']['Status'] == 'resolved':
1098 mailer.setTicketStatus(ticket_id, "new")
1099 status = mailer.getTicketStatus(ticket_id)
1100 self.act_all[nodename][0]['rt'] = status
1101 if config.mail: i_nodes_emailed += 1
1103 print "\t\tconfig.squeeze: %s and %s" % (config.squeeze,
1104 site_record['config']['squeeze'])
1105 if config.squeeze and site_record['config']['squeeze']:
1106 for act_key in act_record['action']:
1107 self.actions[act_key](email_args)
1108 i_nodes_actedon += 1
1110 if config.policysavedb:
1111 #print "Saving Databases... act_all, diagnose_out"
1112 #database.dbDump("act_all", self.act_all)
1113 # remove site record from diagnose_out, it's in act_all as done.
1114 del self.diagnose_db[loginbase]
1115 #database.dbDump("diagnose_out", self.diagnose_db)
1117 print "sleeping for 1 sec"
1119 #print "Hit enter to continue..."
1121 #line = sys.stdin.readline()
1123 return (i_nodes_actedon, i_nodes_emailed)
1125 def __actOnNode(self, diag_record):
1126 nodename = diag_record['nodename']
1127 message = diag_record['message']
1130 act_record.update(diag_record)
1131 act_record['nodename'] = nodename
1132 act_record['msg_format'] = self._format_diaginfo(diag_record)
1133 print "act_record['stage'] == %s " % act_record['stage']
1135 # avoid end records, and nmreset records
1136 # reboot_node_failed, is set below, so don't reboot repeatedly.
1138 #if 'monitor-end-record' not in act_record['stage'] and \
1139 # 'nmreset' not in act_record['stage'] and \
1140 # 'reboot_node_failed' not in act_record:
1142 # if "DOWN" in act_record['log'] and \
1143 # 'pcu_ids' in act_record['plcnode'] and \
1144 # len(act_record['plcnode']['pcu_ids']) > 0:
1146 # print "%s" % act_record['log'],
1147 # print "%15s" % (['reboot_node'],)
1148 # # Set node to re-install
1149 # plc.nodeBootState(act_record['nodename'], "rins")
1151 # ret = reboot_node({'hostname': act_record['nodename']})
1152 # except Exception, exc:
1153 # print "exception on reboot_node:"
1155 # print traceback.print_exc()
1158 # if ret: # and ( 'reboot_node_failed' not in act_record or act_record['reboot_node_failed'] == False):
1159 # # Reboot Succeeded
1160 # print "reboot succeeded for %s" % act_record['nodename']
1162 # act_record2.update(act_record)
1163 # act_record2['action'] = ['reboot_node']
1164 # act_record2['stage'] = "reboot_node"
1165 # act_record2['reboot_node_failed'] = False
1166 # act_record2['email_pcu'] = False
1168 # if nodename not in self.act_all:
1169 # self.act_all[nodename] = []
1170 # print "inserting 'reboot_node' record into act_all"
1171 # self.act_all[nodename].insert(0,act_record2)
1173 # # return None to avoid further action
1174 # print "Taking no further action"
1177 # print "reboot failed for %s" % act_record['nodename']
1178 # # set email_pcu to also send pcu notice for this record.
1179 # act_record['reboot_node_failed'] = True
1180 # act_record['email_pcu'] = True
1182 # print "%s" % act_record['log'],
1183 # print "%15s" % act_record['action']
1185 if act_record['stage'] is not 'monitor-end-record' and \
1186 act_record['stage'] is not 'nmreset':
1187 if nodename not in self.act_all:
1188 self.act_all[nodename] = []
1190 self.act_all[nodename].insert(0,act_record)
1192 print "Not recording %s in act_all" % nodename
1196 def analyseSites(self):
1197 i_sites_observed = 0
1198 i_sites_diagnosed = 0
1199 i_nodes_diagnosed = 0
1204 sorted_sites = self.sickdb.keys()
1206 for loginbase in sorted_sites:
1207 site_record = self.sickdb[loginbase]
1208 print "sites: %s" % loginbase
1210 i_nodes_diagnosed += len(site_record.keys())
1211 i_sites_diagnosed += 1
1213 (na,ne) = self.__actOnSite(loginbase, site_record)
1215 i_sites_observed += 1
1216 i_nodes_actedon += na
1217 i_sites_emailed += ne
1219 l_allsites += [loginbase]
1221 return {'sites_observed': i_sites_observed,
1222 'sites_diagnosed': i_sites_diagnosed,
1223 'nodes_diagnosed': i_nodes_diagnosed,
1224 'sites_emailed': i_sites_emailed,
1225 'nodes_actedon': i_nodes_actedon,
1226 'allsites':l_allsites}
1228 def print_stats(self, key, stats):
1229 print "%20s : %d" % (key, stats[key])