more convenience functions to create an api interface as a user or node.
[monitor.git] / monitor / common.py
1
2 import time
3 import struct
4 from monitor import reboot
5 from monitor import util
6 from monitor import database
7 from monitor.wrapper import plc, plccache
8
9 from datetime import datetime, timedelta
10 from monitor.model import Message
11 from monitor.database.info import HistoryNodeRecord
12
13 esc = struct.pack('i', 27)
14 RED     = esc + "[1;31m"
15 GREEN   = esc + "[1;32m"
16 YELLOW  = esc + "[1;33m"
17 BLUE    = esc + "[1;34m"
18 LIGHTBLUE       = esc + "[1;36m"
19 NORMAL  = esc + "[0;39m"
20
21 def red(str):
22         return RED + str + NORMAL
23
24 def yellow(str):
25         return YELLOW + str + NORMAL
26
27 def green(str):
28         return GREEN + str + NORMAL
29
30 def lightblue(str):
31         return LIGHTBLUE + str + NORMAL
32
33 def blue(str):
34         return BLUE + str + NORMAL
35
36 def get_current_state(fbnode):
37         if 'observed_status' in fbnode:
38                 state = fbnode['observed_status']
39         else:
40                 state = "none"
41         l = state.lower()
42         if l == "debug": l = 'dbg '
43         return l
44
45 def color_pcu_state(fbnode):
46
47         if 'plcnode' in fbnode and 'pcu_ids' in fbnode['plcnode'] and len(fbnode['plcnode']['pcu_ids']) > 0 :
48                 values = reboot.get_pcu_values(fbnode['plcnode']['pcu_ids'][0])
49                 if values == None:
50                         return fbnode['pcu']
51         else:
52                 if 'pcu' not in fbnode:
53                         return 'NOPCU'
54                 else:
55                         return fbnode['pcu']
56
57         if 'reboot' in values:
58                 rb = values['reboot']
59                 if rb == 0 or rb == "0":
60                         return fbnode['pcu'] + "OK  "
61                 elif "NetDown" == rb  or "Not_Run" == rb:
62                         return fbnode['pcu'] + "DOWN"
63                 else:
64                         return fbnode['pcu'] + "BAD "
65         else:
66                 return fbnode['pcu'] + "BAD "
67
68 def color_boot_state(l):
69         if    l == "dbg": return yellow("debg")
70         elif  l == "dbg ": return yellow("debg")
71         elif  l == "failboot": return yellow("debg")
72         elif  l == "diag": return lightblue(l)
73         elif  l == "diagnose": return lightblue(l)
74         elif  l == "safeboot": return lightblue(l)
75         elif  l == "disable": return red("dsbl")
76         elif  l == "disabled": return red("dsbl")
77         elif  l == "down": return red(l)
78         elif  l == "boot": return green(l)
79         elif  l == "rins": return blue(l)
80         elif  l == "reinstall": return blue(l)
81         else:
82                 return l
83
84 def diff_time(timestamp, abstime=True):
85         import math
86         now = time.time()
87         if timestamp == None:
88                 return "unknown"
89         if type(timestamp) == type(datetime.now()):
90                 timestamp = time.mktime(timestamp.timetuple())
91         if abstime:
92                 diff = now - timestamp
93         else:
94                 diff = timestamp
95         # return the number of seconds as a difference from current time.
96         t_str = ""
97         if diff < 60: # sec in min.
98                 t = diff / 1
99                 t_str = "%s sec ago" % int(math.ceil(t))
100         elif diff < 60*60: # sec in hour
101                 t = diff / (60)
102                 t_str = "%s min ago" % int(math.ceil(t))
103         elif diff < 60*60*24: # sec in day
104                 t = diff / (60*60)
105                 t_str = "%s hrs ago" % int(math.ceil(t))
106         elif diff < 60*60*24*14: # sec in week
107                 t = diff / (60*60*24)
108                 t_str = "%s days ago" % int(math.ceil(t))
109         elif diff <= 60*60*24*30: # approx sec in month
110                 t = diff / (60*60*24*7)
111                 t_str = "%s wks ago" % int(math.ceil(t))
112         elif diff > 60*60*24*30: # approx sec in month
113                 t = diff / (60*60*24*30)
114                 t_str = "%s mnths ago" % int(t)
115         return t_str
116
117 def getvalue(fb, path):
118     indexes = path.split("/")
119     values = fb
120     for index in indexes:
121         if index in values:
122             values = values[index]
123         else:
124             return None
125     return values
126
127 def nmap_port_status(status):
128         ps = {}
129         l_nmap = status.split()
130         ports = l_nmap[4:]
131
132         continue_probe = False
133         for port in ports:
134                 results = port.split('/')
135                 ps[results[0]] = results[1]
136                 if results[1] == "open":
137                         continue_probe = True
138         return (ps, continue_probe)
139
140
141 def nodegroup_display(node, fbdata, conf=None):
142         node['current'] = get_current_state(fbdata)
143
144         s = fbdata['kernel_version'].split()
145         if len(s) >=3:
146                 node['kernel_version'] = s[2]
147         else:
148                 node['kernel_version'] = fbdata['kernel_version']
149                 
150         if '2.6' not in node['kernel_version']: node['kernel_version'] = ""
151         if conf and not conf.nocolor:
152             node['boot_state']  = color_boot_state(node['boot_state'])
153             node['current']     = color_boot_state(node['current'])
154
155         if type(fbdata['plc_node_stats']['pcu_ids']) == type([]):
156                 node['pcu'] = "PCU"
157         node['lastupdate'] = diff_time(node['last_contact'])
158
159         pf = HistoryNodeRecord.get_by(hostname=node['hostname'])
160         try:
161                 node['lc'] = diff_time(pf.last_changed)
162         except:
163                 node['lc'] = "err"
164
165         ut = fbdata['comon_stats']['uptime']
166         if ut != "null":
167                 ut = diff_time(float(fbdata['comon_stats']['uptime']), False)
168         node['uptime'] = ut
169
170         return "%(hostname)-42s %(boot_state)8s %(current)5s %(pcu)6s %(key)10.10s... %(kernel_version)35.35s %(lastupdate)12s, %(lc)s, %(uptime)s" % node
171
172 def datetime_fromstr(str):
173         if '-' in str:
174                 try:
175                         tup = time.strptime(str, "%Y-%m-%d")
176                 except:
177                         tup = time.strptime(str, "%Y-%m-%d-%H:%M")
178         elif '/' in str:
179                 tup = time.strptime(str, "%m/%d/%Y")
180         else:
181                 tup = time.strptime(str, "%m/%d/%Y")
182         ret = datetime.fromtimestamp(time.mktime(tup))
183         return ret
184
185 def get_nodeset(config):
186         """
187                 Given the config values passed in, return the set of hostnames that it
188                 evaluates to.
189         """
190         api = plc.getAuthAPI()
191         l_nodes = plccache.l_nodes
192
193         if config.nodelist:
194                 f_nodes = util.file.getListFromFile(config.nodelist)
195                 l_nodes = filter(lambda x: x['hostname'] in f_nodes, l_nodes)
196         elif config.node:
197                 f_nodes = [config.node]
198                 l_nodes = filter(lambda x: x['hostname'] in f_nodes, l_nodes)
199         elif config.nodegroup:
200                 ng = api.GetNodeGroups({'name' : config.nodegroup})
201                 l_nodes = api.GetNodes(ng[0]['node_ids'], ['hostname'])
202         elif config.site:
203                 site = api.GetSites(config.site)
204                 l_nodes = api.GetNodes(site[0]['node_ids'], ['hostname'])
205                 
206         l_nodes = [node['hostname'] for node in l_nodes]
207
208         # perform this query after the above options, so that the filter above
209         # does not break.
210         if config.nodeselect:
211                 fbquery = FindbadNodeRecord.get_all_latest()
212                 node_list = [ n.hostname for n in fbquery ]
213                 l_nodes = node_select(config.nodeselect, node_list, None)
214
215         return l_nodes
216
217 def email_exception(content=None):
218     import config
219     from monitor.model import Message
220     import traceback
221     msg=traceback.format_exc()
222     if content:
223         msg = content + "\n" + msg
224     m=Message("exception running monitor", msg, False)
225     m.send([config.cc_email])
226     return
227
228 def changed_lessthan(last_changed, days):
229         if datetime.now() - last_changed <= timedelta(days):
230                 #print "last changed less than %s" % timedelta(days)
231                 return True
232         else:
233                 #print "last changed more than %s" % timedelta(days)
234                 return False
235
236 def changed_greaterthan(last_changed, days):
237         if datetime.now() - last_changed > timedelta(days):
238                 #print "last changed more than %s" % timedelta(days)
239                 return True
240         else:
241                 #print "last changed less than %s" % timedelta(days)
242                 return False
243
244 def found_between(recent_actions, action_type, lower, upper):
245         return found_before(recent_actions, action_type, upper) and found_within(recent_actions, action_type, lower)
246
247 def found_before(recent_actions, action_type, within):
248         for action in recent_actions:
249                 if action_type == action.action_type and \
250                                 action.date_created < (datetime.now() - timedelta(within)):
251                         return True
252         return False
253         
254 def found_within(recent_actions, action_type, within):
255         for action in recent_actions:
256                 #print "%s - %s %s > %s - %s (%s) ==> %s" % (action.loginbase, action.action_type, action.date_created, datetime.now(), timedelta(within), datetime.now()-timedelta(within), action.date_created > (datetime.now() - timedelta(within)) )
257                 if action_type == action.action_type and \
258                                 action.date_created > (datetime.now() - timedelta(within)):
259                                 #datetime.now() - action.date_created < timedelta(within):
260                         # recent action of given type.
261                         #print "%s found_within %s in recent_actions from %s" % (action_type, timedelta(within), action.date_created)
262                         return True
263
264         print "%s NOT found_within %s in recent_actions" % (action_type, timedelta(within) )
265         return False
266