changes for 3.0
[monitor.git] / monitor_policy.py
1 import config
2 import database
3 import time
4 import mailer
5 from unified_model import cmpCategoryVal
6 import sys
7 import emailTxt
8 import string
9
10 from rt import is_host_in_rt_tickets
11 import plc
12
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']
20         else:
21                 return None
22
23 # Time to enforce policy
24 POLSLEEP = 7200
25
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"
32
33 #Thresholds (DAYS)
34 SPERMIN = 60
35 SPERHOUR = 60*60
36 SPERDAY = 86400
37 PITHRESH = 7 * SPERDAY
38 SLICETHRESH = 7 * SPERDAY
39 # Days before attempting rins again
40 RINSTHRESH = 5 * SPERDAY
41
42 # Days before calling the node dead.
43 DEADTHRESH = 30 * SPERDAY
44 # Minimum number of nodes up before squeezing
45 MINUP = 2
46
47 TECH=1
48 PI=2
49 USER=4
50 ADMIN=8
51
52 from unified_model import *
53
54 class Merge:
55         def __init__(self, l_merge):
56                 self.merge_list = l_merge
57
58                 # the hostname to loginbase mapping
59                 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
60
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 : {})
64
65                 self.cache_all = database.if_cached_else(1, "act_all", lambda : {})
66                 self.sickdb = {}
67                 self.mergedb = {}
68
69         def run(self):
70                 # populate sickdb
71                 self.accumSickSites()
72                 # read data from findbad and act_all
73                 self.mergeActionsAndBadDB()
74                 # pass node_records to RT
75                 return self.getRecordList()
76
77         def accumSickSites(self):
78                 """
79                 Take all nodes, from l_diagnose, look them up in the act_all database, 
80                 and insert them into sickdb[] as:
81
82                         sickdb[loginbase][nodename] = fb_record
83                 """
84                 # look at all problems reported by findbad
85                 l_nodes = self.findbad['nodes'].keys()
86                 count = 0
87                 for nodename in l_nodes:
88                         if nodename not in self.merge_list:
89                                 continue                # skip this node, since it's not wanted
90
91                         count += 1
92                         loginbase = self.plcdb_hn2lb[nodename]
93                         values = self.findbad['nodes'][nodename]['values']
94
95                         fb_record = {}
96                         fb_record['nodename'] = nodename
97                         try:
98                                 fb_record['category'] = values['category']
99                         except:
100                                 print values
101                                 print nodename
102                                 print self.findbad['nodes'][nodename]
103                                 count -= 1
104                                 continue
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()
116
117                         if loginbase not in self.sickdb:
118                                 self.sickdb[loginbase] = {}
119
120                         self.sickdb[loginbase][nodename] = fb_record
121
122                 print "Found %d nodes" % count
123
124         def getKernel(self, unamestr):
125                 s = unamestr.split()
126                 if len(s) > 2:
127                         return s[2]
128                 else:
129                         return ""
130
131         def mergeActionsAndBadDB(self): 
132                 """
133                 - Look at the sick node_records as reported in findbad, 
134                 - Then look at the node_records in act_all.  
135
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()'
144
145                 3) No problem in findbad, problem in act_all
146                         The the node is operational again according to Findbad()
147
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.
150                 """
151
152                 sorted_sites = self.sickdb.keys()
153                 sorted_sites.sort()
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()
158                         sorted_nodes.sort()
159                         for nodename in sorted_nodes:
160                                 fb_record = self.sickdb[loginbase][nodename]
161                                 x = fb_record
162                                 if loginbase not in self.mergedb:
163                                         self.mergedb[loginbase] = {}
164
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.
171                                 #   else
172                                 #           take it from act_all.
173                                 #   
174
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" 
182                                 else: 
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" 
188                                         else:
189                                                 y = self.act_all[nodename][0]
190                                                 y['prev_category'] = y['category']
191
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)
202
203                                         # delete the entry from cache_all to keep it out of case 3)
204                                         del self.cache_all[nodename]
205
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.
210
211                 return
212
213         def getRecordList(self):
214                 sorted_sites = self.mergedb.keys()
215                 sorted_sites.sort()
216                 ret_list = []
217
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)
224
225                 return ret_list
226
227 class RT:
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
232                 self.lastupdated = 0
233                 self.l_ticket_blacklist = l_ticket_blacklist
234                 self.tickets = {}
235
236         def run(self):
237                 self.count = 0
238                 ret_list = []
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, \
244                                                                                                         self.dbTickets)
245                                 diag_node['found_rt_ticket'] = None
246                                 if b_host_inticket:
247                                         #logger.debug("RT: found tickets for %s" %host)
248                                         diag_node['found_rt_ticket'] = r_ticket['ticket_id']
249
250                                 else:
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
257
258                                 ret_list.append(diag_node)
259
260                 #print "RT processed %d nodes with noticket" % self.count
261                 #logger.debug("RT filtered %d noticket nodes" % self.count)
262                 return ret_list
263
264 class Diagnose:
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 : {})
269
270                 self.diagnose_in = {}
271                 self.diagnose_out = {}
272
273         def run(self):
274                 self.accumSickSites()
275
276                 #logger.debug("Accumulated %d sick sites" % len(self.diagnose_in.keys()))
277
278                 try:
279                         stats = self.diagnoseAll()
280                 except Exception, err:
281                         print "----------------"
282                         import traceback
283                         print traceback.print_exc()
284                         from nodecommon import email_exception
285                         email_exception()
286                         print err
287                         #if config.policysavedb:
288                         sys.exit(1)
289
290                 #print_stats("sites_observed", stats)
291                 #print_stats("sites_diagnosed", stats)
292                 #print_stats("nodes_diagnosed", stats)
293
294                 return self.diagnose_out
295
296         def accumSickSites(self):
297                 """
298                 Take all nodes, from l_diagnose, look them up in the diagnose_out database, 
299                 and insert them into diagnose_in[] as:
300
301                         diagnose_in[loginbase] = [diag_node1, diag_node2, ...]
302                 """
303                 for node_record in self.record_list:
304
305                         nodename = node_record['nodename']
306                         loginbase = self.plcdb_hn2lb[nodename]
307
308                         if loginbase not in self.diagnose_in:
309                                 self.diagnose_in[loginbase] = {}
310
311                         self.diagnose_in[loginbase][nodename] = node_record
312
313                 return
314
315         def diagnoseAll(self):
316                 i_sites_observed = 0
317                 i_sites_diagnosed = 0
318                 i_nodes_diagnosed = 0
319                 i_nodes_actedon = 0
320                 i_sites_emailed = 0
321                 l_allsites = []
322
323                 sorted_sites = self.diagnose_in.keys()
324                 sorted_sites.sort()
325                 self.diagnose_out= {}
326                 for loginbase in sorted_sites:
327                         l_allsites += [loginbase]
328
329                         d_diag_nodes = self.diagnose_in[loginbase]
330                         d_act_records = self.__diagnoseSite(loginbase, d_diag_nodes)
331                         # store records in diagnose_out, for saving later.
332                         self.diagnose_out.update(d_act_records)
333                         
334                         if len(d_act_records[loginbase]['nodes'].keys()) > 0:
335                                 i_nodes_diagnosed += (len(d_act_records[loginbase]['nodes'].keys()))
336                                 i_sites_diagnosed += 1
337                         i_sites_observed += 1
338
339                 return {'sites_observed': i_sites_observed, 
340                                 'sites_diagnosed': i_sites_diagnosed, 
341                                 'nodes_diagnosed': i_nodes_diagnosed, 
342                                 'allsites':l_allsites}
343
344                 pass
345                 
346         def __getDaysDown(self, diag_record, nodename):
347                 daysdown = -1
348                 if diag_record['comonstats']['sshstatus'] != "null":
349                         daysdown = int(diag_record['comonstats']['sshstatus']) // (60*60*24)
350                 elif diag_record['comonstats']['lastcotop'] != "null":
351                         daysdown = int(diag_record['comonstats']['lastcotop']) // (60*60*24)
352                 else:
353                         now = time.time()
354                         last_contact = diag_record['plcnode']['last_contact']
355                         if last_contact == None:
356                                 # the node has never been up, so give it a break
357                                 daysdown = -1
358                         else:
359                                 diff = now - last_contact
360                                 daysdown = diff // (60*60*24)
361                 return daysdown
362
363         def __getStrDaysDown(self, diag_record, nodename):
364                 daysdown = self.__getDaysDown(diag_record, nodename)
365                 if daysdown > 0:
366                         return "(%d days down)"%daysdown
367                 else:
368                         return "Unknown number of days"
369
370         def __getCDVersion(self, diag_record, nodename):
371                 cdversion = ""
372                 #print "Getting kernel for: %s" % diag_record['nodename']
373                 cdversion = diag_record['kernel']
374                 return cdversion
375
376         def __diagnoseSite(self, loginbase, d_diag_nodes):
377                 """
378                 d_diag_nodes are diagnose_in entries.
379                 """
380                 d_diag_site = {loginbase : { 'config' : 
381                                                                                                 {'squeeze': False,
382                                                                                                  'email': False
383                                                                                                 }, 
384                                                                         'nodes': {}
385                                                                         }
386                                            }
387                 sorted_nodes = d_diag_nodes.keys()
388                 sorted_nodes.sort()
389                 for nodename in sorted_nodes:
390                         node_record = d_diag_nodes[nodename]
391                         diag_record = self.__diagnoseNode(loginbase, node_record)
392
393                         if diag_record != None:
394                                 d_diag_site[loginbase]['nodes'][nodename] = diag_record
395
396                                 # NOTE: improvement means, we need to act/squeeze and email.
397                                 #print "DIAG_RECORD", diag_record
398                                 if 'monitor-end-record' in diag_record['stage'] or \
399                                    'nmreset' in diag_record['stage']:
400                                 #       print "resetting loginbase!" 
401                                         d_diag_site[loginbase]['config']['squeeze'] = True
402                                         d_diag_site[loginbase]['config']['email'] = True
403                                 #else:
404                                 #       print "NO IMPROVEMENT!!!!"
405                         else:
406                                 pass # there is nothing to do for this node.
407
408                 # NOTE: these settings can be overridden by command line arguments,
409                 #       or the state of a record, i.e. if already in RT's Support Queue.
410                 pf = PersistFlags(loginbase, 1, db='site_persistflags')
411                 nodes_up = pf.nodes_up
412                 if nodes_up < MINUP:
413                         d_diag_site[loginbase]['config']['squeeze'] = True
414
415                 max_slices = self.getMaxSlices(loginbase)
416                 num_nodes = pf.nodes_total #self.getNumNodes(loginbase)
417                 # NOTE: when max_slices == 0, this is either a new site (the old way)
418                 #       or an old disabled site from previous monitor (before site['enabled'])
419                 if nodes_up < num_nodes and max_slices != 0:
420                         d_diag_site[loginbase]['config']['email'] = True
421
422                 if len(d_diag_site[loginbase]['nodes'].keys()) > 0:
423                         print "SITE: %20s : %d nodes up, at most" % (loginbase, nodes_up)
424
425                 return d_diag_site
426
427         def diagRecordByCategory(self, node_record):
428                 nodename = node_record['nodename']
429                 category = node_record['category']
430                 state    = node_record['state']
431                 loginbase = self.plcdb_hn2lb[nodename]
432                 diag_record = None
433
434                 if  "ERROR" in category:        # i.e. "DOWN"
435                         diag_record = {}
436                         diag_record.update(node_record)
437                         daysdown = self.__getDaysDown(diag_record, nodename) 
438                         #if daysdown < 7:
439                         #       format = "DIAG: %20s : %-40s Down only %s days  NOTHING DONE"
440                         #       print format % (loginbase, nodename, daysdown)
441                         #       return None
442
443                         s_daysdown = self.__getStrDaysDown(diag_record, nodename)
444                         diag_record['message'] = emailTxt.mailtxt.newdown
445                         diag_record['args'] = {'nodename': nodename}
446                         diag_record['info'] = (nodename, s_daysdown, "")
447
448                         #if 'reboot_node_failed' in node_record:
449                         #       # there was a previous attempt to use the PCU.
450                         #       if node_record['reboot_node_failed'] == False:
451                         #               # then the last attempt apparently, succeeded.
452                         #               # But, the category is still 'ERROR'.  Therefore, the
453                         #               # PCU-to-Node mapping is broken.
454                         #               #print "Setting message for ERROR node to PCU2NodeMapping: %s" % nodename
455                         #               diag_record['message'] = emailTxt.mailtxt.pcutonodemapping
456                         #               diag_record['email_pcu'] = True
457
458                         if diag_record['ticket_id'] == "":
459                                 diag_record['log'] = "DOWN: %20s : %-40s == %20s %s" % \
460                                         (loginbase, nodename, diag_record['info'][1:], diag_record['found_rt_ticket'])
461                         else:
462                                 diag_record['log'] = "DOWN: %20s : %-40s == %20s %s" % \
463                                         (loginbase, nodename, diag_record['info'][1:], diag_record['ticket_id'])
464
465                 elif "OLDBOOTCD" in category:
466                         # V2 boot cds as determined by findbad
467                         s_daysdown = self.__getStrDaysDown(node_record, nodename)
468                         s_cdversion = self.__getCDVersion(node_record, nodename)
469                         diag_record = {}
470                         diag_record.update(node_record)
471                         #if "2.4" in diag_record['kernel'] or "v2" in diag_record['bootcd']:
472                         diag_record['message'] = emailTxt.mailtxt.newbootcd
473                         diag_record['args'] = {'nodename': nodename}
474                         diag_record['info'] = (nodename, s_daysdown, s_cdversion)
475                         if diag_record['ticket_id'] == "":
476                                 diag_record['log'] = "BTCD: %20s : %-40s == %20s %20s %s" % \
477                                                                         (loginbase, nodename, diag_record['kernel'], 
478                                                                          diag_record['bootcd'], diag_record['found_rt_ticket'])
479                         else:
480                                 diag_record['log'] = "BTCD: %20s : %-40s == %20s %20s %s" % \
481                                                                         (loginbase, nodename, diag_record['kernel'], 
482                                                                          diag_record['bootcd'], diag_record['ticket_id'])
483
484                 elif "PROD" in category:
485                         if "DEBUG" in state:
486                                 # Not sure what to do with these yet.  Probably need to
487                                 # reboot, and email.
488                                 print "DEBG: %20s : %-40s  NOTHING DONE" % (loginbase, nodename)
489                                 return None
490                         elif "BOOT" in state:
491                                 # no action needed.
492                                 # TODO: remove penalties, if any are applied.
493                                 now = time.time()
494                                 last_contact = node_record['plcnode']['last_contact']
495                                 if last_contact == None:
496                                         time_diff = 0
497                                 else:
498                                         time_diff = now - last_contact;
499
500                                 if 'improvement' in node_record['stage']:
501                                         # then we need to pass this on to 'action'
502                                         diag_record = {}
503                                         diag_record.update(node_record)
504                                         diag_record['message'] = emailTxt.mailtxt.newthankyou
505                                         diag_record['args'] = {'nodename': nodename}
506                                         diag_record['info'] = (nodename, node_record['prev_category'], 
507                                                                                                          node_record['category'])
508                                         #if 'email_pcu' in diag_record:
509                                         #       if diag_record['email_pcu']:
510                                         #               # previously, the pcu failed to reboot, so send
511                                         #               # email. Now, reset these values to try the reboot
512                                         #               # again.
513                                         #               diag_record['email_pcu'] = False
514                                         #               del diag_record['reboot_node_failed']
515
516                                         if diag_record['ticket_id'] == "":
517                                                 diag_record['log'] = "IMPR: %20s : %-40s == %20s %20s %s %s" % \
518                                                                         (loginbase, nodename, diag_record['stage'], 
519                                                                          state, category, diag_record['found_rt_ticket'])
520                                         else:
521                                                 diag_record['log'] = "IMPR: %20s : %-40s == %20s %20s %s %s" % \
522                                                                         (loginbase, nodename, diag_record['stage'], 
523                                                                          state, category, diag_record['ticket_id'])
524                                         return diag_record
525                                 #elif time_diff >= 6*SPERHOUR:
526                                 #       # heartbeat is older than 30 min.
527                                 #       # then reset NM.
528                                 #       #print "Possible NM problem!! %s - %s = %s" % (now, last_contact, time_diff)
529                                 #       diag_record = {}
530                                 #       diag_record.update(node_record)
531                                 #       diag_record['message'] = emailTxt.mailtxt.NMReset
532                                 #       diag_record['args'] = {'nodename': nodename}
533                                 #       diag_record['stage'] = "nmreset"
534                                 #       diag_record['info'] = (nodename, 
535                                 #                                                       node_record['prev_category'], 
536                                 #                                                       node_record['category'])
537                                 #       if diag_record['ticket_id'] == "":
538                                 #               diag_record['log'] = "NM  : %20s : %-40s == %20s %20s %s %s" % \
539                                 #                                       (loginbase, nodename, diag_record['stage'], 
540                                 #                                        state, category, diag_record['found_rt_ticket'])
541                                 #       else:
542                                 #               diag_record['log'] = "NM  : %20s : %-40s == %20s" % \
543                                 #                                       (loginbase, nodename, diag_record['stage'])
544 #
545 #                                       return diag_record
546                                 else:
547                                         return None
548                         else:
549                                 # unknown
550                                 pass
551                 elif "ALPHA"    in category:
552                         pass
553                 elif "clock_drift" in category:
554                         pass
555                 elif "dns"    in category:
556                         pass
557                 elif "filerw"    in category:
558                         pass
559                 else:
560                         print "Unknown category!!!! %s" % category
561                         sys.exit(1)
562
563                 return diag_record
564
565         def __diagnoseNode(self, loginbase, node_record):
566                 # TODO: change the format of the hostname in this 
567                 #               record to something more natural.
568                 nodename                = node_record['nodename']
569                 category                = node_record['category']
570                 prev_category   = node_record['prev_category']
571                 state                   = node_record['state']
572                 #if 'prev_category' in node_record:
573                 #       prev_category = node_record['prev_category']
574                 #else:
575                 #       prev_category = "ERROR"
576                 if node_record['prev_category'] != "NORECORD":
577                 
578                         val = cmpCategoryVal(category, prev_category)
579                         print "%s went from %s -> %s" % (nodename, prev_category, category)
580                         if prev_category == "UNKNOWN" and category == "PROD":
581                                 # sending too many thank you notes to people that don't
582                                 # deserve them.
583                                 # TODO: not sure what effect this will have on the node
584                                 # status, though...
585                                 return None
586
587                         if val == 1:
588                                 # improved
589                                 if node_record['ticket_id'] == "" or node_record['ticket_id'] == None:
590                                         print "closing record with no ticket: ", node_record['nodename']
591                                         node_record['action'] = ['close_rt']
592                                         node_record['message'] = None
593                                         node_record['stage'] = 'monitor-end-record'
594                                         return node_record
595                                 else:
596                                         node_record['stage'] = 'improvement'
597
598                                 #if 'monitor-end-record' in node_record['stage']:
599                                 #       # just ignore it if it's already ended.
600                                 #       # otherwise, the status should be worse, and we won't get
601                                 #       # here.
602                                 #       print "monitor-end-record: ignoring ", node_record['nodename']
603                                 #       return None
604 #
605 #                                       #return None
606                         elif val == -1:
607                                 # current category is worse than previous, carry on
608                                 pass
609                         else:
610                                 #values are equal, carry on.
611                                 #print "why are we here?"
612                                 pass
613
614                 if 'rt' in node_record and 'Status' in node_record['rt']:
615                         if node_record['stage'] == 'ticket_waitforever':
616                                 if 'resolved' in node_record['rt']['Status']:
617                                         print "ending waitforever record for: ", node_record['nodename']
618                                         node_record['action'] = ['noop']
619                                         node_record['message'] = None
620                                         node_record['stage'] = 'monitor-end-record'
621                                         print "oldlog: %s" % node_record['log'],
622                                         print "%15s" % node_record['action']
623                                         return node_record
624                                 if 'new' in node_record['rt']['Status'] and \
625                                         'Queue' in node_record['rt'] and \
626                                         'Monitor' in node_record['rt']['Queue']:
627
628                                         print "RESETTING stage to findbad"
629                                         node_record['stage'] = 'findbad'
630                         
631                 #### COMPARE category and prev_category
632                 # if not_equal
633                 #       then assign a stage based on relative priorities
634                 # else equal
635                 #       then check category for stats.
636                 diag_record = self.diagRecordByCategory(node_record)
637                 if diag_record == None:
638                         #print "diag_record == None"
639                         return None
640
641                 #### found_RT_ticket
642                 # TODO: need to record time found, and maybe add a stage for acting on it...
643                 # NOTE: after found, if the support ticket is resolved, the block is
644                 #               not removed. How to remove the block on this?
645
646                 #if 'found_rt_ticket' in diag_record and \
647                 #       diag_record['found_rt_ticket'] is not None:
648                 #       if diag_record['stage'] is not 'improvement':
649                 #               diag_record['stage'] = 'ticket_waitforever'
650                                 
651                 current_time = time.time()
652                 # take off four days, for the delay that database caused.
653                 # TODO: generalize delays at PLC, and prevent enforcement when there
654                 #               have been no emails.
655                 # NOTE: 7*SPERDAY exists to offset the 'bad week'
656                 #delta = current_time - diag_record['time'] - 7*SPERDAY
657                 delta = current_time - diag_record['time']
658
659                 message = diag_record['message']
660                 act_record = {}
661                 act_record.update(diag_record)
662
663                 #### DIAGNOSE STAGES 
664                 if   'findbad' in diag_record['stage']:
665                         # The node is bad, and there's no previous record of it.
666                         act_record['email'] = TECH
667                         act_record['action'] = ['noop']
668                         act_record['message'] = message[0]
669                         act_record['stage'] = 'stage_actinoneweek'
670
671                 elif 'nmreset' in diag_record['stage']:
672                         act_record['email']  = ADMIN 
673                         act_record['action'] = ['reset_nodemanager']
674                         act_record['message'] = message[0]
675                         act_record['stage']  = 'nmreset'
676                         return None
677
678                 elif 'reboot_node' in diag_record['stage']:
679                         act_record['email'] = TECH
680                         act_record['action'] = ['noop']
681                         act_record['message'] = message[0]
682                         act_record['stage'] = 'stage_actinoneweek'
683                         
684                 elif 'improvement' in diag_record['stage']:
685                         # - backoff previous squeeze actions (slice suspend, nocreate)
686                         # TODO: add a backoff_squeeze section... Needs to runthrough
687                         print "backing off of %s" % nodename
688                         act_record['action'] = ['close_rt']
689                         act_record['message'] = message[0]
690                         act_record['stage'] = 'monitor-end-record'
691
692                 elif 'actinoneweek' in diag_record['stage']:
693                         if delta >= 7 * SPERDAY: 
694                                 act_record['email'] = TECH | PI
695                                 act_record['stage'] = 'stage_actintwoweeks'
696                                 act_record['message'] = message[1]
697                                 act_record['action'] = ['nocreate' ]
698                                 act_record['time'] = current_time               # reset clock for waitforever
699                         elif delta >= 3* SPERDAY and not 'second-mail-at-oneweek' in act_record:
700                                 act_record['email'] = TECH 
701                                 act_record['message'] = message[0]
702                                 act_record['action'] = ['sendmailagain-waitforoneweekaction' ]
703                                 act_record['second-mail-at-oneweek'] = True
704                         else:
705                                 act_record['message'] = None
706                                 act_record['action'] = ['waitforoneweekaction' ]
707                                 print "ignoring this record for: %s" % act_record['nodename']
708                                 return None                     # don't send if there's no action
709
710                 elif 'actintwoweeks' in diag_record['stage']:
711                         if delta >= 7 * SPERDAY:
712                                 act_record['email'] = TECH | PI | USER
713                                 act_record['stage'] = 'stage_waitforever'
714                                 act_record['message'] = message[2]
715                                 act_record['action'] = ['suspendslices']
716                                 act_record['time'] = current_time               # reset clock for waitforever
717                         elif delta >= 3* SPERDAY and not 'second-mail-at-twoweeks' in act_record:
718                                 act_record['email'] = TECH | PI
719                                 act_record['message'] = message[1]
720                                 act_record['action'] = ['sendmailagain-waitfortwoweeksaction' ]
721                                 act_record['second-mail-at-twoweeks'] = True
722                         else:
723                                 act_record['message'] = None
724                                 act_record['action'] = ['waitfortwoweeksaction']
725                                 return None                     # don't send if there's no action
726
727                 elif 'ticket_waitforever' in diag_record['stage']:
728                         act_record['email'] = TECH
729                         if 'first-found' not in act_record:
730                                 act_record['first-found'] = True
731                                 act_record['log'] += " firstfound"
732                                 act_record['action'] = ['ticket_waitforever']
733                                 act_record['message'] = None
734                                 act_record['time'] = current_time
735                         else:
736                                 if delta >= 7*SPERDAY:
737                                         act_record['action'] = ['ticket_waitforever']
738                                         act_record['message'] = None
739                                         act_record['time'] = current_time               # reset clock
740                                 else:
741                                         act_record['action'] = ['ticket_waitforever']
742                                         act_record['message'] = None
743                                         return None
744
745                 elif 'waitforever' in diag_record['stage']:
746                         # more than 3 days since last action
747                         # TODO: send only on weekdays.
748                         # NOTE: expects that 'time' has been reset before entering waitforever stage
749                         if delta >= 3*SPERDAY:
750                                 act_record['action'] = ['email-againwaitforever']
751                                 act_record['message'] = message[2]
752                                 act_record['time'] = current_time               # reset clock
753                         else:
754                                 act_record['action'] = ['waitforever']
755                                 act_record['message'] = None
756                                 return None                     # don't send if there's no action
757
758                 else:
759                         # There is no action to be taken, possibly b/c the stage has
760                         # already been performed, but diagnose picked it up again.
761                         # two cases, 
762                         #       1. stage is unknown, or 
763                         #       2. delta is not big enough to bump it to the next stage.
764                         # TODO: figure out which. for now assume 2.
765                         print "UNKNOWN stage for %s; nothing done" % nodename
766                         act_record['action'] = ['unknown']
767                         act_record['message'] = message[0]
768
769                         act_record['email'] = TECH
770                         act_record['action'] = ['noop']
771                         act_record['message'] = message[0]
772                         act_record['stage'] = 'stage_actinoneweek'
773                         act_record['time'] = current_time               # reset clock
774                         #print "Exiting..."
775                         #return None
776                         #sys.exit(1)
777
778                 print "%s" % act_record['log'],
779                 print "%15s" % act_record['action']
780                 return act_record
781
782         def getMaxSlices(self, loginbase):
783                 # if sickdb has a loginbase, then it will have at least one node.
784                 site_stats = None
785
786                 for nodename in self.diagnose_in[loginbase].keys():
787                         if nodename in self.findbad['nodes']:
788                                 site_stats = self.findbad['nodes'][nodename]['values']['plcsite']
789                                 break
790
791                 if site_stats == None:
792                         raise Exception, "loginbase with no nodes in findbad"
793                 else:
794                         return site_stats['max_slices']
795
796         def getNumNodes(self, loginbase):
797                 # if sickdb has a loginbase, then it will have at least one node.
798                 site_stats = None
799
800                 for nodename in self.diagnose_in[loginbase].keys():
801                         if nodename in self.findbad['nodes']:
802                                 site_stats = self.findbad['nodes'][nodename]['values']['plcsite']
803                                 break
804
805                 if site_stats == None:
806                         raise Exception, "loginbase with no nodes in findbad"
807                 else:
808                         return site_stats['num_nodes']
809
810         """
811         Returns number of up nodes as the total number *NOT* in act_all with a
812         stage other than 'steady-state' .
813         """
814         def getUpAtSite(self, loginbase, d_diag_site):
815                 # TODO: THIS DOESN"T WORK!!! it misses all the 'debug' state nodes
816                 #               that aren't recorded yet.
817
818                 numnodes = self.getNumNodes(loginbase)
819                 # NOTE: assume nodes we have no record of are ok. (too conservative)
820                 # TODO: make the 'up' value more representative
821                 up = numnodes
822                 for nodename in d_diag_site[loginbase]['nodes'].keys():
823
824                         rec = d_diag_site[loginbase]['nodes'][nodename]
825                         if rec['stage'] != 'monitor-end-record':
826                                 up -= 1
827                         else:
828                                 pass # the node is assumed to be up.
829
830                 #if up != numnodes:
831                 #       print "ERROR: %s total nodes up and down != %d" % (loginbase, numnodes)
832
833                 return up
834
835 def close_rt_backoff(args):
836         if 'ticket_id' in args and (args['ticket_id'] != "" and args['ticket_id'] != None):
837                 mailer.closeTicketViaRT(args['ticket_id'], 
838                                                                 "Ticket CLOSED automatically by SiteAssist.")
839                 plc.enableSlices(args['hostname'])
840                 plc.enableSliceCreation(args['hostname'])
841         return
842
843 def reboot_node(args):
844         host = args['hostname']
845         return reboot.reboot_policy(host, True, config.debug)
846
847 class Action:
848         def __init__(self, diagnose_out):
849                 # the hostname to loginbase mapping
850                 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
851
852                 # Actions to take.
853                 self.diagnose_db = diagnose_out
854                 # Actions taken.
855                 self.act_all   = database.if_cached_else(1, "act_all", lambda : {})
856
857                 # A dict of actions to specific functions. PICKLE doesnt' like lambdas.
858                 self.actions = {}
859                 self.actions['suspendslices'] = lambda args: plc.suspendSlices(args['hostname'])
860                 self.actions['nocreate'] = lambda args: plc.removeSliceCreation(args['hostname'])
861                 self.actions['close_rt'] = lambda args: close_rt_backoff(args)
862                 self.actions['rins'] = lambda args: plc.nodeBootState(args['hostname'], "rins") 
863                 self.actions['noop'] = lambda args: args
864                 self.actions['reboot_node'] = lambda args: reboot_node(args)
865                 self.actions['reset_nodemanager'] = lambda args: args # reset_nodemanager(args)
866
867                 self.actions['ticket_waitforever'] = lambda args: args
868                 self.actions['waitforever'] = lambda args: args
869                 self.actions['unknown'] = lambda args: args
870                 self.actions['waitforoneweekaction'] = lambda args: args
871                 self.actions['waitfortwoweeksaction'] = lambda args: args
872                 self.actions['sendmailagain-waitforoneweekaction'] = lambda args: args
873                 self.actions['sendmailagain-waitfortwoweeksaction'] = lambda args: args
874                 self.actions['email-againwaitforever'] = lambda args: args
875                 self.actions['email-againticket_waitforever'] = lambda args: args
876                                 
877                 self.sickdb = {}
878
879         def run(self):
880                 self.accumSites()
881                 #logger.debug("Accumulated %d sick sites" % len(self.sickdb.keys()))
882
883                 try:
884                         stats = self.analyseSites()
885                 except Exception, err:
886                         print "----------------"
887                         import traceback
888                         print traceback.print_exc()
889                         from nodecommon import email_exception
890                         email_exception()
891                         print err
892                         if config.policysavedb:
893                                 print "Saving Databases... act_all"
894                                 database.dbDump("act_all", self.act_all)
895                                 database.dbDump("diagnose_out", self.diagnose_db)
896                         sys.exit(1)
897
898                 #print_stats("sites_observed", stats)
899                 #print_stats("sites_diagnosed", stats)
900                 #print_stats("nodes_diagnosed", stats)
901                 self.print_stats("sites_emailed", stats)
902                 #print_stats("nodes_actedon", stats)
903                 print string.join(stats['allsites'], ",")
904
905                 if config.policysavedb:
906                         print "Saving Databases... act_all"
907                         #database.dbDump("policy.eventlog", self.eventlog)
908                         # TODO: remove 'diagnose_out', 
909                         #       or at least the entries that were acted on.
910                         database.dbDump("act_all", self.act_all)
911                         database.dbDump("diagnose_out", self.diagnose_db)
912
913         def accumSites(self):
914                 """
915                 Take all nodes, from l_action, look them up in the diagnose_db database, 
916                 and insert them into sickdb[] as:
917
918                 This way only the given l_action nodes will be acted on regardless
919                 of how many from diagnose_db are available.
920
921                         sickdb[loginbase][nodename] = diag_record
922                 """
923                 self.sickdb = self.diagnose_db
924
925         def __emailSite(self, loginbase, roles, message, args):
926                 """
927                 loginbase is the unique site abbreviation, prepended to slice names.
928                 roles contains TECH, PI, USER roles, and derive email aliases.
929                 record contains {'message': [<subj>,<body>], 'args': {...}} 
930                 """
931                 ticket_id = 0
932                 args.update({'loginbase':loginbase})
933
934                 if not config.mail and not config.debug and config.bcc:
935                         roles = ADMIN
936                 if config.mail and config.debug:
937                         roles = ADMIN
938
939                 # build targets
940                 contacts = []
941                 if ADMIN & roles:
942                         contacts += [config.email]
943                 if TECH & roles:
944                         #contacts += [TECHEMAIL % loginbase]
945                         contacts += plc.getTechEmails(loginbase)
946                 if PI & roles:
947                         #contacts += [PIEMAIL % loginbase]
948                         contacts += plc.getPIEmails(loginbase)
949                 if USER & roles:
950                         contacts += plc.getSliceUserEmails(loginbase)
951                         slices = plc.slices(loginbase)
952                         if len(slices) >= 1:
953                                 print "SLIC: %20s : %d slices" % (loginbase, len(slices))
954                         else:
955                                 print "SLIC: %20s : 0 slices" % loginbase
956
957                 unique_contacts = set(contacts)
958                 contacts = [ c for c in unique_contacts ]       # convert back into list
959
960                 try:
961                         subject = message[0] % args
962                         body = message[1] % args
963                         if ADMIN & roles:
964                                 # send only to admin
965                                 if 'ticket_id' in args:
966                                         subj = "Re: [PL #%s] %s" % (args['ticket_id'], subject)
967                                 else:
968                                         subj = "Re: [PL noticket] %s" % subject
969                                 mailer.email(subj, body, contacts)
970                                 ticket_id = args['ticket_id']
971                         else:
972                                 ticket_id = mailer.emailViaRT(subject, body, contacts, args['ticket_id'])
973                 except Exception, err:
974                         print "exception on message:"
975                         import traceback
976                         print traceback.print_exc()
977                         from nodecommon import email_exception
978                         email_exception()
979                         print message
980
981                 return ticket_id
982
983
984         def _format_diaginfo(self, diag_node):
985                 info = diag_node['info']
986                 if diag_node['stage'] == 'monitor-end-record':
987                         hlist = "    %s went from '%s' to '%s'\n" % (info[0], info[1], info[2]) 
988                 else:
989                         hlist = "    %s %s - %s\n" % (info[0], info[2], info[1]) #(node,ver,daysdn)
990                 return hlist
991
992
993         def get_email_args(self, act_recordlist, loginbase=None):
994
995                 email_args = {}
996                 email_args['hostname_list'] = ""
997                 email_args['url_list'] = ""
998
999                 for act_record in act_recordlist:
1000                         email_args['hostname_list'] += act_record['msg_format']
1001                         email_args['hostname'] = act_record['nodename']
1002                         email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/iso/%s.iso\n"
1003                         email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/usb/%s.usb\n"
1004                         email_args['url_list'] += "\n"
1005                         if  'plcnode' in act_record and \
1006                                 'pcu_ids' in act_record['plcnode'] and \
1007                                 len(act_record['plcnode']['pcu_ids']) > 0:
1008                                 print "setting 'pcu_id' for email_args %s"%email_args['hostname']
1009                                 email_args['pcu_id'] = act_record['plcnode']['pcu_ids'][0]
1010                         else:
1011                                 email_args['pcu_id'] = "-1"
1012                                         
1013                         if 'ticket_id' in act_record:
1014                                 if act_record['ticket_id'] == 0 or act_record['ticket_id'] == '0':
1015                                         print "Enter the ticket_id for %s @ %s" % (loginbase, act_record['nodename'])
1016                                         sys.stdout.flush()
1017                                         line = sys.stdin.readline()
1018                                         try:
1019                                                 ticket_id = int(line)
1020                                         except:
1021                                                 print "could not get ticket_id from stdin..."
1022                                                 os._exit(1)
1023                                 else:
1024                                         ticket_id = act_record['ticket_id']
1025                                         
1026                                 email_args['ticket_id'] = ticket_id
1027
1028                 return email_args
1029
1030         def get_unique_issues(self, act_recordlist):
1031                 # NOTE: only send one email per site, per problem...
1032                 unique_issues = {}
1033                 for act_record in act_recordlist:
1034                         act_key = act_record['action'][0]
1035                         if act_key not in unique_issues:
1036                                 unique_issues[act_key] = []
1037                                 
1038                         unique_issues[act_key] += [act_record]
1039                         
1040                 return unique_issues
1041                         
1042
1043         def __actOnSite(self, loginbase, site_record):
1044                 i_nodes_actedon = 0
1045                 i_nodes_emailed = 0
1046
1047                 act_recordlist = []
1048
1049                 for nodename in site_record['nodes'].keys():
1050                         diag_record = site_record['nodes'][nodename]
1051                         act_record  = self.__actOnNode(diag_record)
1052                         #print "nodename: %s %s" % (nodename, act_record)
1053                         if act_record is not None:
1054                                 act_recordlist += [act_record]
1055
1056                 unique_issues = self.get_unique_issues(act_recordlist)
1057
1058                 for issue in unique_issues.keys():
1059                         print "\tworking on issue: %s" % issue
1060                         issue_record_list = unique_issues[issue]
1061                         email_args = self.get_email_args(issue_record_list, loginbase)
1062
1063                         # for each record.
1064                         #for act_record in issue_record_list:
1065                         #       # if there's a pcu record and email config is set
1066                         #       if 'email_pcu' in act_record:
1067                         #               if act_record['message'] != None and act_record['email_pcu'] and site_record['config']['email']:
1068                         #                       # and 'reboot_node' in act_record['stage']:
1069
1070                         #                       email_args['hostname'] = act_record['nodename']
1071                         #                       ticket_id = self.__emailSite(loginbase, 
1072                         #                                                               act_record['email'], 
1073                         #                                                               emailTxt.mailtxt.pcudown[0],
1074                         #                                                               email_args)
1075                         #                       if ticket_id == 0:
1076                         #                               # error.
1077                         #                               print "got a ticket_id == 0!!!! %s" % act_record['nodename']
1078                         #                               os._exit(1)
1079                         #                               pass
1080                         #                       email_args['ticket_id'] = ticket_id
1081
1082                         
1083                         act_record = issue_record_list[0]
1084                         # send message before squeezing
1085                         print "\t\tconfig.email: %s and %s" % (act_record['message'] != None, 
1086                                                                                                 site_record['config']['email'])
1087                         if act_record['message'] != None and site_record['config']['email']:
1088                                 ticket_id = self.__emailSite(loginbase, act_record['email'], 
1089                                                                                          act_record['message'], email_args)
1090
1091                                 if ticket_id == 0:
1092                                         # error.
1093                                         print "ticket_id == 0 for %s %s" % (loginbase, act_record['nodename'])
1094                                         import os
1095                                         os._exit(1)
1096                                         pass
1097
1098                                 # Add ticket_id to ALL nodenames
1099                                 for act_record in issue_record_list:
1100                                         nodename = act_record['nodename']
1101                                         # update node record with RT ticket_id
1102                                         if nodename in self.act_all:
1103                                                 self.act_all[nodename][0]['ticket_id'] = "%s" % ticket_id
1104                                                 # if the ticket was previously resolved, reset it to new.
1105                                                 if 'rt' in act_record and \
1106                                                         'Status' in act_record['rt'] and \
1107                                                         act_record['rt']['Status'] == 'resolved':
1108                                                         mailer.setTicketStatus(ticket_id, "new")
1109                                                 status = mailer.getTicketStatus(ticket_id)
1110                                                 self.act_all[nodename][0]['rt'] = status
1111                                         if config.mail: i_nodes_emailed += 1
1112
1113                         print "\t\tconfig.squeeze: %s and %s" % (config.squeeze,
1114                                                                                                         site_record['config']['squeeze'])
1115                         if config.squeeze and site_record['config']['squeeze']:
1116                                 for act_key in act_record['action']:
1117                                         self.actions[act_key](email_args)
1118                                 i_nodes_actedon += 1
1119                 
1120                 if config.policysavedb:
1121                         #print "Saving Databases... act_all, diagnose_out"
1122                         #database.dbDump("act_all", self.act_all)
1123                         # remove site record from diagnose_out, it's in act_all as done.
1124                         del self.diagnose_db[loginbase]
1125                         #database.dbDump("diagnose_out", self.diagnose_db)
1126
1127                 print "sleeping for 1 sec"
1128                 time.sleep(1)
1129                 #print "Hit enter to continue..."
1130                 #sys.stdout.flush()
1131                 #line = sys.stdin.readline()
1132
1133                 return (i_nodes_actedon, i_nodes_emailed)
1134
1135         def __actOnNode(self, diag_record):
1136                 nodename = diag_record['nodename']
1137                 message = diag_record['message']
1138
1139                 act_record = {}
1140                 act_record.update(diag_record)
1141                 act_record['nodename'] = nodename
1142                 act_record['msg_format'] = self._format_diaginfo(diag_record)
1143                 print "act_record['stage'] == %s " % act_record['stage']
1144
1145                 # avoid end records, and nmreset records                                        
1146                 # reboot_node_failed, is set below, so don't reboot repeatedly.
1147
1148                 #if 'monitor-end-record' not in act_record['stage'] and \
1149                 #   'nmreset' not in act_record['stage'] and \
1150                 #   'reboot_node_failed' not in act_record:
1151
1152                 #       if "DOWN" in act_record['log'] and \
1153                 #                       'pcu_ids' in act_record['plcnode'] and \
1154                 #                       len(act_record['plcnode']['pcu_ids']) > 0:
1155 #
1156 #                               print "%s" % act_record['log'],
1157 #                               print "%15s" % (['reboot_node'],)
1158 #                               # Set node to re-install
1159 #                               plc.nodeBootState(act_record['nodename'], "rins")       
1160 #                               try:
1161 #                                       ret = reboot_node({'hostname': act_record['nodename']})
1162 #                               except Exception, exc:
1163 #                                       print "exception on reboot_node:"
1164 #                                       import traceback
1165 #                                       print traceback.print_exc()
1166 #                                       ret = False
1167 #
1168 #                               if ret: # and ( 'reboot_node_failed' not in act_record or act_record['reboot_node_failed'] == False):
1169 #                                       # Reboot Succeeded
1170 #                                       print "reboot succeeded for %s" % act_record['nodename']
1171 #                                       act_record2 = {}
1172 #                                       act_record2.update(act_record)
1173 #                                       act_record2['action'] = ['reboot_node']
1174 #                                       act_record2['stage'] = "reboot_node"
1175 #                                       act_record2['reboot_node_failed'] = False
1176 #                                       act_record2['email_pcu'] = False
1177 #
1178 #                                       if nodename not in self.act_all: 
1179 #                                               self.act_all[nodename] = []
1180 #                                       print "inserting 'reboot_node' record into act_all"
1181 #                                       self.act_all[nodename].insert(0,act_record2)
1182 #
1183 #                                       # return None to avoid further action
1184 #                                       print "Taking no further action"
1185 #                                       return None
1186 #                               else:
1187 #                                       print "reboot failed for %s" % act_record['nodename']
1188 #                                       # set email_pcu to also send pcu notice for this record.
1189 #                                       act_record['reboot_node_failed'] = True
1190 #                                       act_record['email_pcu'] = True
1191 #
1192 #                       print "%s" % act_record['log'],
1193 #                       print "%15s" % act_record['action']
1194
1195                 if act_record['stage'] is not 'monitor-end-record' and \
1196                    act_record['stage'] is not 'nmreset':
1197                         if nodename not in self.act_all: 
1198                                 self.act_all[nodename] = []
1199
1200                         self.act_all[nodename].insert(0,act_record)
1201                 else:
1202                         print "Not recording %s in act_all" % nodename
1203
1204                 return act_record
1205
1206         def analyseSites(self):
1207                 i_sites_observed = 0
1208                 i_sites_diagnosed = 0
1209                 i_nodes_diagnosed = 0
1210                 i_nodes_actedon = 0
1211                 i_sites_emailed = 0
1212                 l_allsites = []
1213
1214                 sorted_sites = self.sickdb.keys()
1215                 sorted_sites.sort()
1216                 for loginbase in sorted_sites:
1217                         site_record = self.sickdb[loginbase]
1218                         print "sites: %s" % loginbase
1219                         
1220                         i_nodes_diagnosed += len(site_record.keys())
1221                         i_sites_diagnosed += 1
1222
1223                         (na,ne) = self.__actOnSite(loginbase, site_record)
1224
1225                         i_sites_observed += 1
1226                         i_nodes_actedon += na
1227                         i_sites_emailed += ne
1228
1229                         l_allsites += [loginbase]
1230
1231                 return {'sites_observed': i_sites_observed, 
1232                                 'sites_diagnosed': i_sites_diagnosed, 
1233                                 'nodes_diagnosed': i_nodes_diagnosed, 
1234                                 'sites_emailed': i_sites_emailed, 
1235                                 'nodes_actedon': i_nodes_actedon, 
1236                                 'allsites':l_allsites}
1237
1238         def print_stats(self, key, stats):
1239                 print "%20s : %d" % (key, stats[key])
1240