+ diagnose.py: added --refresh option so that cached values can be refresh, and either
[monitor.git] / findbad.py
1 #!/usr/bin/python
2
3 import os
4 import sys
5 import string
6 import time
7
8 from config import config
9 from optparse import OptionParser
10 parser = OptionParser()
11 parser.set_defaults(filename="", increment=False, dbname="findbadnodes", cachenodes=False)
12 parser.add_option("-f", "--nodes", dest="filename", metavar="FILE", 
13                                         help="Provide the input file for the node list")
14 parser.add_option("", "--cachenodes", action="store_true",
15                                         help="Cache node lookup from PLC")
16 parser.add_option("", "--dbname", dest="dbname", metavar="FILE", 
17                                         help="Specify the name of the database to which the information is saved")
18 parser.add_option("-i", "--increment", action="store_true", dest="increment", 
19                                         help="Increment round number to force refresh or retry")
20 config = config(parser)
21 config.parse_args()
22
23 # QUERY all nodes.
24 COMON_COTOPURL= "http://summer.cs.princeton.edu/status/tabulator.cgi?" + \
25                                         "table=table_nodeview&" + \
26                                     "dumpcols='name,resptime,sshstatus,uptime,lastcotop'&" + \
27                                     "formatcsv"
28                                     #"formatcsv&" + \
29                                         #"select='lastcotop!=0'"
30
31 import threading
32 plc_lock = threading.Lock()
33 round = 1
34 externalState = {'round': round, 'nodes': {}}
35 count = 0
36
37
38 import soltesz
39 import plc
40 import comon
41 import threadpool
42 import syncplcdb
43
44 def collectPingAndSSH(nodename, cohash):
45         ### RUN PING ######################
46         ping = soltesz.CMD()
47         (oval,eval) = ping.run_noexcept("ping -c 1 -q %s | grep rtt" % nodename)
48
49         values = {}
50
51         if oval == "":
52                 # An error occurred
53                 values['ping'] = "NOPING"
54         else:
55                 values['ping'] = "PING"
56
57         ### RUN SSH ######################
58         b_getbootcd_id = True
59         ssh = soltesz.SSH('root', nodename)
60         oval = ""
61         eval = ""
62         (oval, eval) = ssh.run_noexcept('echo `uname -a ; ls /tmp/bm.log`')
63         val = oval
64         if "2.6.17" in oval or "2.6.20" in oval:
65                 values['ssh'] = 'SSH'
66                 if "bm.log" in oval:
67                         values['category'] = 'ALPHA'
68                         values['state'] = 'DEBUG'
69                 else:
70                         values['category'] = 'ALPHA'
71                         values['state'] = 'BOOT'
72         elif "2.6.12" in oval or "2.6.10" in oval:
73                 values['ssh'] = 'SSH'
74                 values['category'] = 'PROD'
75                 if "bm.log" in oval:
76                         values['state'] = 'DEBUG'
77                 else:
78                         values['state'] = 'BOOT'
79         elif "2.4" in oval:
80                 b_getbootcd_id = False
81                 values['ssh'] = 'SSH'
82                 values['category'] = 'OLDBOOTCD'
83                 values['state'] = 'DEBUG'
84         elif oval != "":
85                 values['ssh'] = 'SSH'
86                 values['category'] = 'UNKNOWN'
87                 if "bm.log" in oval:
88                         values['state'] = 'DEBUG'
89                 else:
90                         values['state'] = 'BOOT'
91         else:
92                 # An error occurred.
93                 b_getbootcd_id = False
94                 values['ssh'] = 'NOSSH'
95                 values['category'] = 'ERROR'
96                 values['state'] = 'DOWN'
97                 val = eval.strip()
98
99         values['kernel'] = val
100
101         if b_getbootcd_id:
102                 # try to get BootCD for all nodes that are not 2.4 nor inaccessible
103                 (oval, eval) = ssh.run_noexcept('cat /mnt/cdrom/bootme/ID')
104                 val = oval
105                 if "BootCD" in val:
106                         values['bootcd'] = val
107                         if "v2" in val:
108                                 values['category'] = 'OLDBOOTCD'
109                 else:
110                         values['bootcd'] = ""
111         else:
112                 values['bootcd'] = ""
113
114         # TODO: get bm.log for debug nodes.
115         # 'zcat /tmp/bm.log'
116                 
117         if nodename in cohash: 
118                 values['comonstats'] = cohash[nodename]
119         else:
120                 values['comonstats'] = {'resptime':  '-1', 
121                                                                 'uptime':    '-1',
122                                                                 'sshstatus': '-1', 
123                                                                 'lastcotop': '-1'}
124         # include output value
125         ### GET PLC NODE ######################
126         b_except = False
127         plc_lock.acquire()
128
129         try:
130                 d_node = plc.getNodes({'hostname': nodename}, ['pcu_ids', 'site_id', 'last_contact'])
131         except:
132                 b_except = True
133                 import traceback
134                 traceback.print_exc()
135
136         plc_lock.release()
137         if b_except: return (None, None)
138
139         site_id = -1
140         if d_node and len(d_node) > 0:
141                 pcu = d_node[0]['pcu_ids']
142                 if len(pcu) > 0:
143                         values['pcu'] = "PCU"
144                 else:
145                         values['pcu'] = "NOPCU"
146                 site_id = d_node[0]['site_id']
147                 last_contact = d_node[0]['last_contact']
148                 values['plcnode'] = {'status' : 'SUCCESS', 
149                                                         'pcu_ids': pcu, 
150                                                         'site_id': site_id,
151                                                         'last_contact': last_contact}
152         else:
153                 values['pcu']     = "UNKNOWN"
154                 values['plcnode'] = {'status' : "GN_FAILED"}
155                 
156
157         ### GET PLC SITE ######################
158         b_except = False
159         plc_lock.acquire()
160
161         try:
162                 d_site = plc.getSites({'site_id': site_id}, 
163                                                         ['max_slices', 'slice_ids', 'node_ids', 'login_base'])
164         except:
165                 b_except = True
166                 import traceback
167                 traceback.print_exc()
168
169         plc_lock.release()
170         if b_except: return (None, None)
171
172         if d_site and len(d_site) > 0:
173                 max_slices = d_site[0]['max_slices']
174                 num_slices = len(d_site[0]['slice_ids'])
175                 num_nodes = len(d_site[0]['node_ids'])
176                 loginbase = d_site[0]['login_base']
177                 values['plcsite'] = {'num_nodes' : num_nodes, 
178                                                         'max_slices' : max_slices, 
179                                                         'num_slices' : num_slices,
180                                                         'login_base' : loginbase,
181                                                         'status'     : 'SUCCESS'}
182         else:
183                 values['plcsite'] = {'status' : "GS_FAILED"}
184
185         return (nodename, values)
186
187 def recordPingAndSSH(request, result):
188         global externalState
189         global count
190         (nodename, values) = result
191
192         if values is not None:
193                 global_round = externalState['round']
194                 externalState['nodes'][nodename]['values'] = values
195                 externalState['nodes'][nodename]['round'] = global_round
196
197                 count += 1
198                 print "%d %s %s" % (count, nodename, externalState['nodes'][nodename]['values'])
199                 soltesz.dbDump(config.dbname, externalState)
200
201 # this will be called when an exception occurs within a thread
202 def handle_exception(request, result):
203         print "Exception occured in request %s" % request.requestID
204         for i in result:
205                 print "Result: %s" % i
206
207
208 def checkAndRecordState(l_nodes, cohash):
209         global externalState
210         global count
211         global_round = externalState['round']
212
213         tp = threadpool.ThreadPool(20)
214
215         # CREATE all the work requests
216         for nodename in l_nodes:
217                 if nodename not in externalState['nodes']:
218                         externalState['nodes'][nodename] = {'round': 0, 'values': []}
219
220                 node_round   = externalState['nodes'][nodename]['round']
221                 if node_round < global_round:
222                         # recreate node stats when refreshed
223                         #print "%s" % nodename
224                         req = threadpool.WorkRequest(collectPingAndSSH, [nodename, cohash], {}, 
225                                                                                  None, recordPingAndSSH, handle_exception)
226                         tp.putRequest(req)
227                 else:
228                         # We just skip it, since it's "up to date"
229                         count += 1
230                         print "%d %s %s" % (count, nodename, externalState['nodes'][nodename]['values'])
231                         pass
232
233         # WAIT while all the work requests are processed.
234         while 1:
235                 try:
236                         time.sleep(1)
237                         tp.poll()
238                 except KeyboardInterrupt:
239                         print "Interrupted!"
240                         break
241                 except threadpool.NoResultsPending:
242                         print "All results collected."
243                         break
244
245
246
247 def main():
248         global externalState
249
250         externalState = soltesz.if_cached_else(1, config.dbname, lambda : externalState) 
251
252         if config.increment:
253                 # update global round number to force refreshes across all nodes
254                 externalState['round'] += 1
255
256         cotop = comon.Comon()
257         # lastcotop measures whether cotop is actually running.  this is a better
258         # metric than sshstatus, or other values from CoMon
259         cotop_url = COMON_COTOPURL
260
261         # history information for all nodes
262         cohash = cotop.coget(cotop_url)
263
264         if config.filename == "":
265                 l_nodes = syncplcdb.create_plcdb()
266                 l_nodes = [node['hostname'] for node in l_nodes]
267                 #l_nodes = cohash.keys()
268         else:
269                 l_nodes = config.getListFromFile(config.filename)
270
271         checkAndRecordState(l_nodes, cohash)
272
273         return 0
274
275
276 if __name__ == '__main__':
277         try:
278                 main()
279         except Exception, err:
280                 print "Exception: %s" % err
281                 print "Saving data... exitting."
282                 soltesz.dbDump(config.dbname, externalState)
283                 sys.exit(0)