merge from:
[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                         print err
285                         #if config.policysavedb:
286                         sys.exit(1)
287
288                 #print_stats("sites_observed", stats)
289                 #print_stats("sites_diagnosed", stats)
290                 #print_stats("nodes_diagnosed", stats)
291
292                 return self.diagnose_out
293
294         def accumSickSites(self):
295                 """
296                 Take all nodes, from l_diagnose, look them up in the diagnose_out database, 
297                 and insert them into diagnose_in[] as:
298
299                         diagnose_in[loginbase] = [diag_node1, diag_node2, ...]
300                 """
301                 for node_record in self.record_list:
302
303                         nodename = node_record['nodename']
304                         loginbase = self.plcdb_hn2lb[nodename]
305
306                         if loginbase not in self.diagnose_in:
307                                 self.diagnose_in[loginbase] = {}
308
309                         self.diagnose_in[loginbase][nodename] = node_record
310
311                 return
312
313         def diagnoseAll(self):
314                 i_sites_observed = 0
315                 i_sites_diagnosed = 0
316                 i_nodes_diagnosed = 0
317                 i_nodes_actedon = 0
318                 i_sites_emailed = 0
319                 l_allsites = []
320
321                 sorted_sites = self.diagnose_in.keys()
322                 sorted_sites.sort()
323                 self.diagnose_out= {}
324                 for loginbase in sorted_sites:
325                         l_allsites += [loginbase]
326
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)
331                         
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
336
337                 return {'sites_observed': i_sites_observed, 
338                                 'sites_diagnosed': i_sites_diagnosed, 
339                                 'nodes_diagnosed': i_nodes_diagnosed, 
340                                 'allsites':l_allsites}
341
342                 pass
343                 
344         def __getDaysDown(self, diag_record, nodename):
345                 daysdown = -1
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)
350                 else:
351                         now = time.time()
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
355                                 daysdown = -1
356                         else:
357                                 diff = now - last_contact
358                                 daysdown = diff // (60*60*24)
359                 return daysdown
360
361         def __getStrDaysDown(self, diag_record, nodename):
362                 daysdown = self.__getDaysDown(diag_record, nodename)
363                 if daysdown > 0:
364                         return "(%d days down)"%daysdown
365                 else:
366                         return "Unknown number of days"
367
368         def __getCDVersion(self, diag_record, nodename):
369                 cdversion = ""
370                 #print "Getting kernel for: %s" % diag_record['nodename']
371                 cdversion = diag_record['kernel']
372                 return cdversion
373
374         def __diagnoseSite(self, loginbase, d_diag_nodes):
375                 """
376                 d_diag_nodes are diagnose_in entries.
377                 """
378                 d_diag_site = {loginbase : { 'config' : 
379                                                                                                 {'squeeze': False,
380                                                                                                  'email': False
381                                                                                                 }, 
382                                                                         'nodes': {}
383                                                                         }
384                                            }
385                 sorted_nodes = d_diag_nodes.keys()
386                 sorted_nodes.sort()
387                 for nodename in sorted_nodes:
388                         node_record = d_diag_nodes[nodename]
389                         diag_record = self.__diagnoseNode(loginbase, node_record)
390
391                         if diag_record != None:
392                                 d_diag_site[loginbase]['nodes'][nodename] = diag_record
393
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
401                                 #else:
402                                 #       print "NO IMPROVEMENT!!!!"
403                         else:
404                                 pass # there is nothing to do for this node.
405
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
410                 if nodes_up < MINUP:
411                         d_diag_site[loginbase]['config']['squeeze'] = True
412
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
419
420                 if len(d_diag_site[loginbase]['nodes'].keys()) > 0:
421                         print "SITE: %20s : %d nodes up, at most" % (loginbase, nodes_up)
422
423                 return d_diag_site
424
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]
430                 diag_record = None
431
432                 if  "ERROR" in category:        # i.e. "DOWN"
433                         diag_record = {}
434                         diag_record.update(node_record)
435                         daysdown = self.__getDaysDown(diag_record, nodename) 
436                         #if daysdown < 7:
437                         #       format = "DIAG: %20s : %-40s Down only %s days  NOTHING DONE"
438                         #       print format % (loginbase, nodename, daysdown)
439                         #       return None
440
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, "")
445
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
455
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'])
459                         else:
460                                 diag_record['log'] = "DOWN: %20s : %-40s == %20s %s" % \
461                                         (loginbase, nodename, diag_record['info'][1:], diag_record['ticket_id'])
462
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)
467                         diag_record = {}
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'])
477                         else:
478                                 diag_record['log'] = "BTCD: %20s : %-40s == %20s %20s %s" % \
479                                                                         (loginbase, nodename, diag_record['kernel'], 
480                                                                          diag_record['bootcd'], diag_record['ticket_id'])
481
482                 elif "PROD" in category:
483                         if "DEBUG" in state:
484                                 # Not sure what to do with these yet.  Probably need to
485                                 # reboot, and email.
486                                 print "DEBG: %20s : %-40s  NOTHING DONE" % (loginbase, nodename)
487                                 return None
488                         elif "BOOT" in state:
489                                 # no action needed.
490                                 # TODO: remove penalties, if any are applied.
491                                 now = time.time()
492                                 last_contact = node_record['plcnode']['last_contact']
493                                 if last_contact == None:
494                                         time_diff = 0
495                                 else:
496                                         time_diff = now - last_contact;
497
498                                 if 'improvement' in node_record['stage']:
499                                         # then we need to pass this on to 'action'
500                                         diag_record = {}
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
510                                         #               # again.
511                                         #               diag_record['email_pcu'] = False
512                                         #               del diag_record['reboot_node_failed']
513
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'])
518                                         else:
519                                                 diag_record['log'] = "IMPR: %20s : %-40s == %20s %20s %s %s" % \
520                                                                         (loginbase, nodename, diag_record['stage'], 
521                                                                          state, category, diag_record['ticket_id'])
522                                         return diag_record
523                                 #elif time_diff >= 6*SPERHOUR:
524                                 #       # heartbeat is older than 30 min.
525                                 #       # then reset NM.
526                                 #       #print "Possible NM problem!! %s - %s = %s" % (now, last_contact, time_diff)
527                                 #       diag_record = {}
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'])
539                                 #       else:
540                                 #               diag_record['log'] = "NM  : %20s : %-40s == %20s" % \
541                                 #                                       (loginbase, nodename, diag_record['stage'])
542 #
543 #                                       return diag_record
544                                 else:
545                                         return None
546                         else:
547                                 # unknown
548                                 pass
549                 elif "ALPHA"    in category:
550                         pass
551                 elif "clock_drift" in category:
552                         pass
553                 elif "dns"    in category:
554                         pass
555                 elif "filerw"    in category:
556                         pass
557                 else:
558                         print "Unknown category!!!! %s" % category
559                         sys.exit(1)
560
561                 return diag_record
562
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']
572                 #else:
573                 #       prev_category = "ERROR"
574                 if node_record['prev_category'] != "NORECORD":
575                 
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
580                                 # deserve them.
581                                 # TODO: not sure what effect this will have on the node
582                                 # status, though...
583                                 return None
584
585                         if val == 1:
586                                 # improved
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'
592                                         return node_record
593                                 else:
594                                         node_record['stage'] = 'improvement'
595
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
599                                 #       # here.
600                                 #       print "monitor-end-record: ignoring ", node_record['nodename']
601                                 #       return None
602 #
603 #                                       #return None
604                         elif val == -1:
605                                 # current category is worse than previous, carry on
606                                 pass
607                         else:
608                                 #values are equal, carry on.
609                                 #print "why are we here?"
610                                 pass
611
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']
621                                         return node_record
622                                 if 'new' in node_record['rt']['Status'] and \
623                                         'Queue' in node_record['rt'] and \
624                                         'Monitor' in node_record['rt']['Queue']:
625
626                                         print "RESETTING stage to findbad"
627                                         node_record['stage'] = 'findbad'
628                         
629                 #### COMPARE category and prev_category
630                 # if not_equal
631                 #       then assign a stage based on relative priorities
632                 # else equal
633                 #       then check category for stats.
634                 diag_record = self.diagRecordByCategory(node_record)
635                 if diag_record == None:
636                         #print "diag_record == None"
637                         return None
638
639                 #### found_RT_ticket
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?
643
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'
648                                 
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']
656
657                 message = diag_record['message']
658                 act_record = {}
659                 act_record.update(diag_record)
660
661                 #### DIAGNOSE STAGES 
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'
668
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'
674                         return None
675
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'
681                         
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'
689
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
702                         else:
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
707
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
720                         else:
721                                 act_record['message'] = None
722                                 act_record['action'] = ['waitfortwoweeksaction']
723                                 return None                     # don't send if there's no action
724
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
733                         else:
734                                 if delta >= 7*SPERDAY:
735                                         act_record['action'] = ['ticket_waitforever']
736                                         act_record['message'] = None
737                                         act_record['time'] = current_time               # reset clock
738                                 else:
739                                         act_record['action'] = ['ticket_waitforever']
740                                         act_record['message'] = None
741                                         return None
742
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
751                         else:
752                                 act_record['action'] = ['waitforever']
753                                 act_record['message'] = None
754                                 return None                     # don't send if there's no action
755
756                 else:
757                         # There is no action to be taken, possibly b/c the stage has
758                         # already been performed, but diagnose picked it up again.
759                         # two cases, 
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]
766
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
772                         #print "Exiting..."
773                         #return None
774                         #sys.exit(1)
775
776                 print "%s" % act_record['log'],
777                 print "%15s" % act_record['action']
778                 return act_record
779
780         def getMaxSlices(self, loginbase):
781                 # if sickdb has a loginbase, then it will have at least one node.
782                 site_stats = None
783
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']
787                                 break
788
789                 if site_stats == None:
790                         raise Exception, "loginbase with no nodes in findbad"
791                 else:
792                         return site_stats['max_slices']
793
794         def getNumNodes(self, loginbase):
795                 # if sickdb has a loginbase, then it will have at least one node.
796                 site_stats = None
797
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']
801                                 break
802
803                 if site_stats == None:
804                         raise Exception, "loginbase with no nodes in findbad"
805                 else:
806                         return site_stats['num_nodes']
807
808         """
809         Returns number of up nodes as the total number *NOT* in act_all with a
810         stage other than 'steady-state' .
811         """
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.
815
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
819                 up = numnodes
820                 for nodename in d_diag_site[loginbase]['nodes'].keys():
821
822                         rec = d_diag_site[loginbase]['nodes'][nodename]
823                         if rec['stage'] != 'monitor-end-record':
824                                 up -= 1
825                         else:
826                                 pass # the node is assumed to be up.
827
828                 #if up != numnodes:
829                 #       print "ERROR: %s total nodes up and down != %d" % (loginbase, numnodes)
830
831                 return up
832
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'])
839         return
840
841 def reboot_node(args):
842         host = args['hostname']
843         return reboot.reboot_policy(host, True, config.debug)
844
845 class Action:
846         def __init__(self, diagnose_out):
847                 # the hostname to loginbase mapping
848                 self.plcdb_hn2lb = database.dbLoad("plcdb_hn2lb")
849
850                 # Actions to take.
851                 self.diagnose_db = diagnose_out
852                 # Actions taken.
853                 self.act_all   = database.if_cached_else(1, "act_all", lambda : {})
854
855                 # A dict of actions to specific functions. PICKLE doesnt' like lambdas.
856                 self.actions = {}
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)
864
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
874                                 
875                 self.sickdb = {}
876
877         def run(self):
878                 self.accumSites()
879                 #logger.debug("Accumulated %d sick sites" % len(self.sickdb.keys()))
880
881                 try:
882                         stats = self.analyseSites()
883                 except Exception, err:
884                         print "----------------"
885                         import traceback
886                         print traceback.print_exc()
887                         print err
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)
892                         sys.exit(1)
893
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'], ",")
900
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)
908
909         def accumSites(self):
910                 """
911                 Take all nodes, from l_action, look them up in the diagnose_db database, 
912                 and insert them into sickdb[] as:
913
914                 This way only the given l_action nodes will be acted on regardless
915                 of how many from diagnose_db are available.
916
917                         sickdb[loginbase][nodename] = diag_record
918                 """
919                 self.sickdb = self.diagnose_db
920
921         def __emailSite(self, loginbase, roles, message, args):
922                 """
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': {...}} 
926                 """
927                 ticket_id = 0
928                 args.update({'loginbase':loginbase})
929
930                 if not config.mail and not config.debug and config.bcc:
931                         roles = ADMIN
932                 if config.mail and config.debug:
933                         roles = ADMIN
934
935                 # build targets
936                 contacts = []
937                 if ADMIN & roles:
938                         contacts += [config.email]
939                 if TECH & roles:
940                         #contacts += [TECHEMAIL % loginbase]
941                         contacts += plc.getTechEmails(loginbase)
942                 if PI & roles:
943                         #contacts += [PIEMAIL % loginbase]
944                         contacts += plc.getPIEmails(loginbase)
945                 if USER & roles:
946                         contacts += plc.getSliceUserEmails(loginbase)
947                         slices = plc.slices(loginbase)
948                         if len(slices) >= 1:
949                                 print "SLIC: %20s : %d slices" % (loginbase, len(slices))
950                         else:
951                                 print "SLIC: %20s : 0 slices" % loginbase
952
953                 unique_contacts = set(contacts)
954                 contacts = [ c for c in unique_contacts ]       # convert back into list
955
956                 try:
957                         subject = message[0] % args
958                         body = message[1] % args
959                         if ADMIN & roles:
960                                 # send only to admin
961                                 if 'ticket_id' in args:
962                                         subj = "Re: [PL #%s] %s" % (args['ticket_id'], subject)
963                                 else:
964                                         subj = "Re: [PL noticket] %s" % subject
965                                 mailer.email(subj, body, contacts)
966                                 ticket_id = args['ticket_id']
967                         else:
968                                 ticket_id = mailer.emailViaRT(subject, body, contacts, args['ticket_id'])
969                 except Exception, err:
970                         print "exception on message:"
971                         import traceback
972                         print traceback.print_exc()
973                         print message
974
975                 return ticket_id
976
977
978         def _format_diaginfo(self, diag_node):
979                 info = diag_node['info']
980                 if diag_node['stage'] == 'monitor-end-record':
981                         hlist = "    %s went from '%s' to '%s'\n" % (info[0], info[1], info[2]) 
982                 else:
983                         hlist = "    %s %s - %s\n" % (info[0], info[2], info[1]) #(node,ver,daysdn)
984                 return hlist
985
986
987         def get_email_args(self, act_recordlist, loginbase=None):
988
989                 email_args = {}
990                 email_args['hostname_list'] = ""
991                 email_args['url_list'] = ""
992
993                 for act_record in act_recordlist:
994                         email_args['hostname_list'] += act_record['msg_format']
995                         email_args['hostname'] = act_record['nodename']
996                         email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/iso/%s.iso\n"
997                         email_args['url_list'] += "\thttp://boot2.planet-lab.org/premade-bootcd-alpha/usb/%s.usb\n"
998                         email_args['url_list'] += "\n"
999                         if  'plcnode' in act_record and \
1000                                 'pcu_ids' in act_record['plcnode'] and \
1001                                 len(act_record['plcnode']['pcu_ids']) > 0:
1002                                 print "setting 'pcu_id' for email_args %s"%email_args['hostname']
1003                                 email_args['pcu_id'] = act_record['plcnode']['pcu_ids'][0]
1004                         else:
1005                                 email_args['pcu_id'] = "-1"
1006                                         
1007                         if 'ticket_id' in act_record:
1008                                 if act_record['ticket_id'] == 0 or act_record['ticket_id'] == '0':
1009                                         print "Enter the ticket_id for %s @ %s" % (loginbase, act_record['nodename'])
1010                                         sys.stdout.flush()
1011                                         line = sys.stdin.readline()
1012                                         try:
1013                                                 ticket_id = int(line)
1014                                         except:
1015                                                 print "could not get ticket_id from stdin..."
1016                                                 os._exit(1)
1017                                 else:
1018                                         ticket_id = act_record['ticket_id']
1019                                         
1020                                 email_args['ticket_id'] = ticket_id
1021
1022                 return email_args
1023
1024         def get_unique_issues(self, act_recordlist):
1025                 # NOTE: only send one email per site, per problem...
1026                 unique_issues = {}
1027                 for act_record in act_recordlist:
1028                         act_key = act_record['action'][0]
1029                         if act_key not in unique_issues:
1030                                 unique_issues[act_key] = []
1031                                 
1032                         unique_issues[act_key] += [act_record]
1033                         
1034                 return unique_issues
1035                         
1036
1037         def __actOnSite(self, loginbase, site_record):
1038                 i_nodes_actedon = 0
1039                 i_nodes_emailed = 0
1040
1041                 act_recordlist = []
1042
1043                 for nodename in site_record['nodes'].keys():
1044                         diag_record = site_record['nodes'][nodename]
1045                         act_record  = self.__actOnNode(diag_record)
1046                         #print "nodename: %s %s" % (nodename, act_record)
1047                         if act_record is not None:
1048                                 act_recordlist += [act_record]
1049
1050                 unique_issues = self.get_unique_issues(act_recordlist)
1051
1052                 for issue in unique_issues.keys():
1053                         print "\tworking on issue: %s" % issue
1054                         issue_record_list = unique_issues[issue]
1055                         email_args = self.get_email_args(issue_record_list, loginbase)
1056
1057                         # for each record.
1058                         #for act_record in issue_record_list:
1059                         #       # if there's a pcu record and email config is set
1060                         #       if 'email_pcu' in act_record:
1061                         #               if act_record['message'] != None and act_record['email_pcu'] and site_record['config']['email']:
1062                         #                       # and 'reboot_node' in act_record['stage']:
1063
1064                         #                       email_args['hostname'] = act_record['nodename']
1065                         #                       ticket_id = self.__emailSite(loginbase, 
1066                         #                                                               act_record['email'], 
1067                         #                                                               emailTxt.mailtxt.pcudown[0],
1068                         #                                                               email_args)
1069                         #                       if ticket_id == 0:
1070                         #                               # error.
1071                         #                               print "got a ticket_id == 0!!!! %s" % act_record['nodename']
1072                         #                               os._exit(1)
1073                         #                               pass
1074                         #                       email_args['ticket_id'] = ticket_id
1075
1076                         
1077                         act_record = issue_record_list[0]
1078                         # send message before squeezing
1079                         print "\t\tconfig.email: %s and %s" % (act_record['message'] != None, 
1080                                                                                                 site_record['config']['email'])
1081                         if act_record['message'] != None and site_record['config']['email']:
1082                                 ticket_id = self.__emailSite(loginbase, act_record['email'], 
1083                                                                                          act_record['message'], email_args)
1084
1085                                 if ticket_id == 0:
1086                                         # error.
1087                                         print "ticket_id == 0 for %s %s" % (loginbase, act_record['nodename'])
1088                                         import os
1089                                         os._exit(1)
1090                                         pass
1091
1092                                 # Add ticket_id to ALL nodenames
1093                                 for act_record in issue_record_list:
1094                                         nodename = act_record['nodename']
1095                                         # update node record with RT ticket_id
1096                                         if nodename in self.act_all:
1097                                                 self.act_all[nodename][0]['ticket_id'] = "%s" % ticket_id
1098                                                 # if the ticket was previously resolved, reset it to new.
1099                                                 if 'rt' in act_record and \
1100                                                         'Status' in act_record['rt'] and \
1101                                                         act_record['rt']['Status'] == 'resolved':
1102                                                         mailer.setTicketStatus(ticket_id, "new")
1103                                                 status = mailer.getTicketStatus(ticket_id)
1104                                                 self.act_all[nodename][0]['rt'] = status
1105                                         if config.mail: i_nodes_emailed += 1
1106
1107                         print "\t\tconfig.squeeze: %s and %s" % (config.squeeze,
1108                                                                                                         site_record['config']['squeeze'])
1109                         if config.squeeze and site_record['config']['squeeze']:
1110                                 for act_key in act_record['action']:
1111                                         self.actions[act_key](email_args)
1112                                 i_nodes_actedon += 1
1113                 
1114                 if config.policysavedb:
1115                         #print "Saving Databases... act_all, diagnose_out"
1116                         #database.dbDump("act_all", self.act_all)
1117                         # remove site record from diagnose_out, it's in act_all as done.
1118                         del self.diagnose_db[loginbase]
1119                         #database.dbDump("diagnose_out", self.diagnose_db)
1120
1121                 print "sleeping for 1 sec"
1122                 time.sleep(1)
1123                 #print "Hit enter to continue..."
1124                 #sys.stdout.flush()
1125                 #line = sys.stdin.readline()
1126
1127                 return (i_nodes_actedon, i_nodes_emailed)
1128
1129         def __actOnNode(self, diag_record):
1130                 nodename = diag_record['nodename']
1131                 message = diag_record['message']
1132
1133                 act_record = {}
1134                 act_record.update(diag_record)
1135                 act_record['nodename'] = nodename
1136                 act_record['msg_format'] = self._format_diaginfo(diag_record)
1137                 print "act_record['stage'] == %s " % act_record['stage']
1138
1139                 # avoid end records, and nmreset records                                        
1140                 # reboot_node_failed, is set below, so don't reboot repeatedly.
1141
1142                 #if 'monitor-end-record' not in act_record['stage'] and \
1143                 #   'nmreset' not in act_record['stage'] and \
1144                 #   'reboot_node_failed' not in act_record:
1145
1146                 #       if "DOWN" in act_record['log'] and \
1147                 #                       'pcu_ids' in act_record['plcnode'] and \
1148                 #                       len(act_record['plcnode']['pcu_ids']) > 0:
1149 #
1150 #                               print "%s" % act_record['log'],
1151 #                               print "%15s" % (['reboot_node'],)
1152 #                               # Set node to re-install
1153 #                               plc.nodeBootState(act_record['nodename'], "rins")       
1154 #                               try:
1155 #                                       ret = reboot_node({'hostname': act_record['nodename']})
1156 #                               except Exception, exc:
1157 #                                       print "exception on reboot_node:"
1158 #                                       import traceback
1159 #                                       print traceback.print_exc()
1160 #                                       ret = False
1161 #
1162 #                               if ret: # and ( 'reboot_node_failed' not in act_record or act_record['reboot_node_failed'] == False):
1163 #                                       # Reboot Succeeded
1164 #                                       print "reboot succeeded for %s" % act_record['nodename']
1165 #                                       act_record2 = {}
1166 #                                       act_record2.update(act_record)
1167 #                                       act_record2['action'] = ['reboot_node']
1168 #                                       act_record2['stage'] = "reboot_node"
1169 #                                       act_record2['reboot_node_failed'] = False
1170 #                                       act_record2['email_pcu'] = False
1171 #
1172 #                                       if nodename not in self.act_all: 
1173 #                                               self.act_all[nodename] = []
1174 #                                       print "inserting 'reboot_node' record into act_all"
1175 #                                       self.act_all[nodename].insert(0,act_record2)
1176 #
1177 #                                       # return None to avoid further action
1178 #                                       print "Taking no further action"
1179 #                                       return None
1180 #                               else:
1181 #                                       print "reboot failed for %s" % act_record['nodename']
1182 #                                       # set email_pcu to also send pcu notice for this record.
1183 #                                       act_record['reboot_node_failed'] = True
1184 #                                       act_record['email_pcu'] = True
1185 #
1186 #                       print "%s" % act_record['log'],
1187 #                       print "%15s" % act_record['action']
1188
1189                 if act_record['stage'] is not 'monitor-end-record' and \
1190                    act_record['stage'] is not 'nmreset':
1191                         if nodename not in self.act_all: 
1192                                 self.act_all[nodename] = []
1193
1194                         self.act_all[nodename].insert(0,act_record)
1195                 else:
1196                         print "Not recording %s in act_all" % nodename
1197
1198                 return act_record
1199
1200         def analyseSites(self):
1201                 i_sites_observed = 0
1202                 i_sites_diagnosed = 0
1203                 i_nodes_diagnosed = 0
1204                 i_nodes_actedon = 0
1205                 i_sites_emailed = 0
1206                 l_allsites = []
1207
1208                 sorted_sites = self.sickdb.keys()
1209                 sorted_sites.sort()
1210                 for loginbase in sorted_sites:
1211                         site_record = self.sickdb[loginbase]
1212                         print "sites: %s" % loginbase
1213                         
1214                         i_nodes_diagnosed += len(site_record.keys())
1215                         i_sites_diagnosed += 1
1216
1217                         (na,ne) = self.__actOnSite(loginbase, site_record)
1218
1219                         i_sites_observed += 1
1220                         i_nodes_actedon += na
1221                         i_sites_emailed += ne
1222
1223                         l_allsites += [loginbase]
1224
1225                 return {'sites_observed': i_sites_observed, 
1226                                 'sites_diagnosed': i_sites_diagnosed, 
1227                                 'nodes_diagnosed': i_nodes_diagnosed, 
1228                                 'sites_emailed': i_sites_emailed, 
1229                                 'nodes_actedon': i_nodes_actedon, 
1230                                 'allsites':l_allsites}
1231
1232         def print_stats(self, key, stats):
1233                 print "%20s : %d" % (key, stats[key])
1234