+ new XMLRPC_SERVER name to boot.planet-lab.org
[monitor.git] / comon.py
1 #
2 # Copyright (c) 2004  The Trustees of Princeton University (Trustees).
3 #
4 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
5 #
6 # $Id: comon.py,v 1.6 2007/06/29 12:42:22 soltesz Exp $
7 #
8 # Get CoMon data, unsorted, in CSV, and create a huge hash.
9 #
10
11
12 import urllib2
13 import httplib
14 import time
15 import Queue 
16 import logging
17 import pickle
18 from threading import *
19 #httplib.HTTPConnection.debuglevel = 1  
20
21 logger = logging.getLogger("monitor")
22
23 # Time between comon refresh
24 COSLEEP=1200
25
26 # CoMon
27 COMONURL = "http://summer.cs.princeton.edu/status/tabulator.cgi?table=table_nodeview"
28
29 # node type:
30 # null == <not in DB?>
31 #        0 == 
32 #        1 == Prod
33 #        2 == alpha
34 #        3 == beta
35
36 # boot state:
37 #       0 == new
38 #       1 == boot
39 #       2 == dbg
40 #       3 == rins
41 #       4 == ins
42
43
44 class Comon(Thread): 
45         """
46         cdb is the comon database (dictionary)
47         all buckets is a queue of all problem nodes. This gets sent to rt to find
48         tickets open for host. 
49         """
50         def __init__(self, cdb, d_allplc_nodes, q_allbuckets):
51                 self.codata = cdb 
52                 self.d_allplc_nodes = d_allplc_nodes
53                 self.updated = time.time()
54                 self.q_allbuckets = q_allbuckets
55                 #self.comon_buckets = {"down" : "resptime%20==%200%20&&%20keyok==null",
56                 #       "ssh": "sshstatus%20%3E%202h",
57                 #       "clock_drift": "drift%20%3E%201m",
58                 #       "dns": "dns1udp%20%3E%2080%20&&%20dns2udp%20%3E%2080",
59                 #       "filerw": "filerw%3E0",
60                 #       "dbg" : "keyok==0"}
61                 self.comon_buckets = {
62                         #"down" : "resptime==0 && keyok==null",
63                         #"ssh": "sshstatus > 2h",
64                         #"clock_drift": "drift > 1m",
65                         #"dns": "dns1udp>80 && dns2udp>80",
66                         #"filerw": "filerw > 0",
67                         #"all" : ""
68                         "dbg" : "keyok==0",
69                         }
70                 Thread.__init__(self)
71
72         def __tohash(self,rawdata):
73                 # First line Comon returns is list of keys with respect to index
74                 keys = rawdata.readline().rstrip().split(", ")
75                 l_host = []
76                 hash = {}
77                 try:
78                         i_ignored = 0
79                         for line in rawdata.readlines():
80                                 l_host = line.rstrip().split(", ")              # split the line on ', '
81                                 hostname = l_host[0]
82                                 if hostname in self.d_allplc_nodes:             # then we'll track it
83                                         hash[hostname] = {}
84                                         for i in range(1,len(keys)):
85                                                 hash[hostname][keys[i]]=l_host[i]
86                                 else:
87                                         i_ignored += 1
88
89                         print "Retrieved %s hosts" % len(hash.keys())
90                         print "Ignoring %d hosts" % i_ignored
91
92                         logger.debug("Retrieved %s hosts" % len(hash.keys()))
93                         logger.debug("Ignoring %d hosts" % i_ignored)
94                 except Exception, err:
95                         logger.debug("No hosts retrieved")      
96                         return {} 
97                 return hash
98
99         # Update individual buckekts.  Hostnames only.
100         def updatebuckets(self):
101                 for (bucket,url) in self.comon_buckets.items():
102                         logger.debug("COMON:  Updating bucket %s" % bucket)
103                         tmp = self.coget(COMONURL + "&format=formatcsv&select='" + url + "'").keys()
104                         setattr(self, bucket, tmp)
105
106         # Update ALL node information
107         def updatedb(self):
108                 # Get time of update
109                 self.updated = time.time()
110                 # Make a Hash, put in self.
111                 self.codata.update(self.coget(COMONURL + "&format=formatcsv"))
112
113         def coget(self,url):
114                 rawdata = None
115                 print "Getting: %s" % url
116                 try:
117                         coserv = urllib2.Request(url)
118                         coserv.add_header('User-Agent',
119                                 'PL_Monitor +http://monitor.planet-lab.org/')
120                         opener = urllib2.build_opener()
121                         # Initial web get from summer.cs in CSV
122                         rawdata = opener.open(coserv)
123                 except urllib2.URLError, (err):
124                         print "Attempting %s" %COMONURL
125                         print "URL error (%s)" % (err)
126                         rawdata = None
127                 return self.__tohash(rawdata)
128
129         # Push nodes that are bad (in *a* bucket) into q(q_allbuckets)
130         def push(self):
131                 #buckets_per_node = []
132                 #for bucket in self.comon.comon_buckets.keys():
133                 #       if (hostname in getattr(self.comon, bucket)):
134                 #               buckets_per_node.append(bucket)
135
136                 #loginbase = self.plcdb_hn2lb[hostname] # plc.siteId(node)
137
138                 #if not loginbase in self.sickdb:
139                 #       self.sickdb[loginbase] = [{hostname: buckets_per_node}]
140                 #else:
141                 #       self.sickdb[loginbase].append({hostname: buckets_per_node})
142
143
144                 print "calling Comon.push()"
145                 for bucket in self.comon_buckets.keys():
146                         #print "bucket: %s" % bucket
147                         for host in getattr(self,bucket):
148                                 diag_node = {}
149                                 diag_node['nodename'] = host
150                                 diag_node['message'] = None
151                                 diag_node['bucket'] = [bucket]
152                                 diag_node['stage'] = ""
153                                 diag_node['args'] = None
154                                 diag_node['info'] = None
155                                 diag_node['time'] = time.time()
156                                 #print "host: %s" % host
157                                 self.q_allbuckets.put(diag_node)
158
159         def run(self):
160                 self.updatedb()
161                 self.updatebuckets()
162                 self.push()
163                 # insert signal that this is the final host
164                 self.q_allbuckets.put("None")
165  
166         def __repr__(self):
167             return self
168
169 def main():
170         logger.setLevel(logging.DEBUG)
171         ch = logging.StreamHandler()
172         ch.setLevel(logging.DEBUG)
173         formatter = logging.Formatter('%(message)s')
174         ch.setFormatter(formatter)
175         logger.addHandler(ch)
176
177
178         t = Queue.Queue()
179         cdb = {}
180         a = Comon(cdb,t)
181         #for i in a.comon_buckets: print "%s : %s" % ( i, a.comon_buckets[i])
182         a.start()
183
184         time.sleep(5)
185         #for i in a.down: print i
186
187         time.sleep(5)
188         #print cdb
189         for host in cdb.keys():
190                 #if cdb[host]['keyok'] == "0":
191                 # null implies that it may not be in PL DB.
192                 if  cdb[host]['bootstate'] != "null" and \
193                         cdb[host]['bootstate'] == "2" and \
194                         cdb[host]['keyok'] == "0":      
195                         print("%-40s \t Bootstate %s nodetype %s kernver %s keyok %s" % ( 
196                                 host, cdb[host]['bootstate'], cdb[host]['nodetype'], 
197                                 cdb[host]['kernver'], cdb[host]['keyok']))
198                         #ssh = soltesz.SSH('root', host)
199                         #try:
200                         #       val = ssh.run("uname -r")
201                         #       print "%s == %s" % (host, val),
202                         #except:
203                         #       pass
204         #       else:
205         #               print("key mismatch at: %s" % host)
206         #print a.codata['michelangelo.ani.univie.ac.at']
207         #time.sleep(3)
208         #a.push()
209         #print a.filerw
210         #print a.coget(COMONURL + "&format=formatcsv&select='" + a.comon_buckets['filerw'])
211
212         #os._exit(0)
213 if __name__ == '__main__':
214         import os
215         try:
216                 main()
217         except KeyboardInterrupt:
218                 print "Killed.  Exitting."
219                 logger.info('Monitor Killed')
220                 os._exit(0)