Initial Checkin.
[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: $
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 from threading import *
18 #httplib.HTTPConnection.debuglevel = 1  
19
20 logger = logging.getLogger("monitor")
21
22 # Time between comon refresh
23 COSLEEP=1200
24
25 # CoMon
26 COMONURL = "http://summer.cs.princeton.edu/status/tabulator.cgi?table=table_nodeview"
27
28
29 class Comon(Thread): 
30         """
31         """
32         def __init__(self, cdb, allbuckets):
33                 self.codata = cdb 
34                 self.updated = time.time()
35                 self.allbuckets = allbuckets
36                 self.comonbkts = {"ssh": "sshstatus%20%3E%202h",
37                         "clock_drift": "drift%20%3E%201m",
38                         "dns": "dns1udp%20%3E%2080%20&&%20dns2udp%20%3E%2080",
39                         "disk": "resptime%20%3E%200%20&&%20gbfree%20%3C%205",
40                         "filerw": "filerw%3E0"}
41                 Thread.__init__(self)
42
43         def __tohash(self,rawdata):
44                 # First line Comon returns is list of keys with respect to index
45                 keys = rawdata.readline().rstrip().split(", ")
46                 host = []
47                 hash = {}
48                 try:
49                         for line in rawdata.readlines():
50                                 host = line.rstrip().split(", ")
51                                 tmp = {}
52                                 for i in range(1,len(keys)):
53                                         tmp[keys[i]]=host[i]
54                                 hash[host[0]]=tmp
55                         logger.debug("Retrieved %s hosts" % len(hash.keys()))
56                 except Exception, err:
57                         logger.debug("No hosts retrieved")      
58                         return {} 
59                 return hash
60
61         # Update individual buckekts.  Hostnames only.
62         def updatebkts(self):
63                 for (bkt,url) in self.comonbkts.items():
64                         tmp = self.coget(COMONURL + "&format=formatcsv&select='" + url + "'").keys()
65                         setattr(self, bkt, tmp)
66
67         # Update ALL node information
68         def updatedb(self):
69                 # Get time of update
70                 self.updated = time.time()
71                 # Make a Hash, put in self.
72                 self.codata = self.coget(COMONURL + "&format=formatcsv")
73
74         def coget(self,url):
75                 rawdata = None
76                 try:
77                         logger.debug("Trying - " + url)
78                         coserv = urllib2.Request(url)
79                         coserv.add_header('User-Agent',
80                                 'PL_Monitor +http://monitor.planet-lab.org/')
81                         opener = urllib2.build_opener()
82                         # Initial web get from summer.cs in CSV
83                         rawdata = opener.open(coserv)
84                 except urllib2.URLError, (err):
85                         print "Attempting %s" %COMONURL
86                         print "URL error (%s)" % (err)
87                         rawdata = None
88                 return self.__tohash(rawdata)
89
90         # Push nodes that are bad (in *a* bucket) into q(allbuckets)
91         def push(self):
92                 for bucket in self.comonbkts.keys():
93                         for host in getattr(self,bucket):
94                                 self.allbuckets.put(host)
95
96         def run(self):
97                 while 1:
98                         self.updatedb()
99                         self.updatebkts()
100                         self.push()
101                         time.sleep(COSLEEP)
102  
103         def __repr__(self):
104             return self
105
106 def main():
107         logger.setLevel(logging.DEBUG)
108         ch = logging.StreamHandler()
109         ch.setLevel(logging.DEBUG)
110         formatter = logging.Formatter('%(message)s')
111         ch.setFormatter(formatter)
112         logger.addHandler(ch)
113
114
115         t = Queue.Queue()
116         cdb = {}
117         a = Comon(cdb,t)
118         a.start()
119         time.sleep(3)
120         print a.ssh
121         #time.sleep(3)
122         #a.push()
123         #print a.filerw
124         print a.coget(COMONURL + "&format=formatcsv&select='" + a.comonbkts['filerw'])
125
126         os._exit(0)
127 if __name__ == '__main__':
128         import os
129         try:
130                 main()
131         except KeyboardInterrupt:
132                 print "Killed.  Exitting."
133                 logger.info('Monitor Killed')
134                 os._exit(0)