This commit changes the 'soltesz.py' module into 'moncommands.py' and
[monitor.git] / diagnose.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2004  The Trustees of Princeton University (Trustees).
4
5 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
6 # Stephen Soltesz <soltesz@cs.princeton.edu>
7 #
8 # $Id: diagnose.py,v 1.1 2007/08/08 13:36:46 soltesz Exp $
9
10 import sys
11 from threading import *
12 import time
13 import logging
14 import Queue
15 from sets import Set
16
17 # Global config options
18 from config import config
19 from optparse import OptionParser
20 parser = OptionParser()
21
22 parser.set_defaults(nodelist=None, 
23                                         refresh=False,
24                                         cachert=False, 
25                                         cachenodes=False, 
26                                         blacklist=None, 
27                                         ticketlist=None)
28
29 parser.add_option("", "--nodelist", dest="nodelist", metavar="filename",
30                                         help="Read nodes to act on from specified file")
31 parser.add_option("", "--refresh", action="store_true", dest="refresh",
32                                         help="Refresh the cached values")
33 parser.add_option("", "--cachert", action="store_true", dest="cachert",
34                                         help="Cache the RT database query")
35 parser.add_option("", "--cachenodes", action="store_true", dest="cachenodes",
36                                         help="Cache node lookup from PLC")
37 parser.add_option("", "--ticketlist", dest="ticketlist",
38                                         help="Whitelist all RT tickets in this file")
39 parser.add_option("", "--blacklist", dest="blacklist",
40                                         help="Blacklist all nodes in this file")
41
42 config = config(parser)
43 config.parse_args()
44
45 # daemonize and *pid
46 #from util.process import * 
47
48 # RT tickets
49 import rt
50 # Correlates input with policy to form actions
51 import policy
52 import moncommands
53 import database 
54 import plc
55 import syncplcdb
56
57 # Log to what 
58 LOG="./monitor.log"
59
60 # Time to refresh DB and remove unused entries
61 RTSLEEP=7200 #2hrs
62 # Time between policy enforce/update
63 #POLSLEEP=43200 #12hrs
64 POLSLEEP=10
65
66 # Global list of all running threads.  Any threads added to 
67 # list will be monitored.
68 runningthreads = {}
69 # Seconds between checking threads
70 WATCHSLEEP = 5
71  
72 # Set up Logging
73 logger = logging.getLogger("monitor")
74 logger.setLevel(logging.DEBUG)
75 fh = logging.FileHandler(LOG, mode = 'a')
76 fh.setLevel(logging.DEBUG)
77 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
78 fh.setFormatter(formatter)
79 logger.addHandler(fh)
80
81
82 """
83 Launches threads and adds them to the runningthreads global list.
84 Assigns name for thread, starts.
85 """
86 def startThread(fnct, name):
87                 runningthreads[name] = fnct
88                 runningthreads[name].setName(name)
89                 try:
90                         logger.info("Starting thread " + name)
91                         runningthreads[name].start()
92                 except Exception, err:
93                         logger.error("Thread: " + name + " " + error)
94
95
96 """
97 Watches threads and catches exceptions.  Each launched thread is
98 watched and state is logged.
99 """
100 class ThreadWatcher(Thread):
101         def __init__(self):
102                 Thread.__init__(self)
103
104         def run(self):
105                 while 1:
106                         self.checkThreads()
107                         time.sleep(WATCHSLEEP)
108
109         def checkThreads(self):
110                 # Iterate through treads, compare with last running.
111                 for thread in runningthreads.keys():
112                         # If thread found dead, remove from queue
113                         #print "found %s" % thread
114                         if not runningthreads[thread].isAlive():
115                                 logger.error("***********Thread died: %s**********" %(thread))
116                                 del runningthreads[thread]
117                 return len(runningthreads.keys())
118
119
120 class Dummy(Thread):
121         def __init__(self):
122                 Thread.__init__(self)
123
124         def run(self):
125                 time.sleep(5)
126
127 def dict_from_nodelist(nl):
128         d = {}
129         for host in nl:
130                 h = host['hostname']
131                 d[h] = host
132         return d
133
134
135
136 """
137 Start threads, do some housekeeping, then daemonize.
138 """
139 def main():
140         # Defaults
141         global status, logger
142         global config
143
144         logger.info('Diagnose Started')
145         print 'Diagnose Started'
146
147         ##########  VARIABLES   ########################################
148         # Queue between Merge and RT
149         toRT = Queue.Queue()
150
151         # Queue between RT and Diagnose
152         fromRT = Queue.Queue()
153
154         #########  GET NODES    ########################################
155         logger.info('Get Nodes from PLC')
156         print "getnode from plc: %s %s %s" % (config.debug, config.cachenodes, config.refresh)
157         l_plcnodes = database.if_cached_else_refresh(config.cachenodes, 
158                                                                 config.refresh, "l_plcnodes",
159                                                                 lambda : syncplcdb.create_plcdb() )
160
161         s_plcnodenames = Set([x['hostname'] for x in l_plcnodes])
162
163         # List of nodes from a user-provided file.
164         if config.nodelist:
165                 file = config.nodelist
166                 nodelist = config.getListFromFile(file)
167         
168                 s_usernodes = Set(nodelist)
169                 # SAFE nodes are in PLC and the list 
170                 s_safe_usernodes   = s_plcnodenames & s_usernodes
171                 # UNSAFE nodes are list but not in PLC. i.e. do not monitor.
172                 s_unsafe_usernodes = s_usernodes - s_plcnodenames
173                 if len(s_unsafe_usernodes) > 0 :
174                         for node in s_unsafe_usernodes:
175                                 print "WARNING: User provided: %s but not found in PLC" % node
176
177                 l_nodes = filter(lambda x: x['hostname'] in s_safe_usernodes,l_plcnodes)
178         else:
179                 l_nodes = l_plcnodes
180
181         print "len of l_nodes: %d" % len(l_nodes)
182         # Minus blacklisted ones..
183         l_blacklist = database.if_cached_else(1, "l_blacklist", lambda : [])
184         l_ticket_blacklist = database.if_cached_else(1,"l_ticket_blacklist",lambda : [])
185         l_nodes  = filter(lambda x : not x['hostname'] in l_blacklist, l_nodes)
186
187         logger.info('Get Tickets from RT')
188         #######  RT tickets    #########################################
189         t = moncommands.MyTimer()
190         ad_dbTickets = database.if_cached_else_refresh(config.cachert, config.refresh, "ad_dbTickets", rt.rt_tickets)
191         if ad_dbTickets == "":
192                 print "ad_dbTickets failed..."
193                 sys.exit(1)
194         print "Getting tickets from RT took: %f sec" % t.diff() ; del t
195
196         logger.info('Start Merge/RT/Diagnose threads')
197         ####### Merge
198         # only look at nodes in l_nodes
199         merge = policy.Merge( [node['hostname'] for node in l_nodes], toRT)
200         startThread(merge,"merge")
201         ####### RT
202         rt1   = rt.RT(ad_dbTickets, toRT, fromRT, l_ticket_blacklist)
203         startThread(rt1,"rt1")
204         ####### Diagnose
205         diagnose = policy.Diagnose(fromRT)
206         startThread(diagnose,"diagnose")
207
208
209         tw = ThreadWatcher()
210         while True:
211                 if tw.checkThreads() == 0:
212                         break
213                 print "waiting... %s" % time.time()
214                 time.sleep(WATCHSLEEP)
215
216         logger.info('Diagnose Exitting')
217         sys.exit(0)
218         
219 if __name__ == '__main__':
220         try:
221                 main()
222         except KeyboardInterrupt:
223                 print "Killed.  Exitting."
224                 logger.info('Diagnose Killed')
225                 sys.exit(0)