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