moved nodecommon.py into monitor module
[monitor.git] / monitor / common.py
1
2 import time
3 import struct
4 from pcucontrol import reboot
5
6 from monitor import util
7 from monitor import database
8 from monitor.wrapper import plc, plccache
9
10 from datetime import datetime 
11 from monitor.model import PersistFlags
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                         #return fbnode['pcu'] + "OK  "
62                         #return green(fbnode['pcu'])
63                 elif "NetDown" == rb  or "Not_Run" == rb:
64                         return fbnode['pcu'] + "DOWN"
65                         #return yellow(fbnode['pcu'])
66                 else:
67                         return fbnode['pcu'] + "BAD "
68                         #return red(fbnode['pcu'])
69         else:
70                 #return red(fbnode['pcu'])
71                 return fbnode['pcu'] + "BAD "
72
73 def color_boot_state(l):
74         if    l == "dbg": return yellow("debg")
75         elif  l == "dbg ": return yellow("debg")
76         elif  l == "diag": return lightblue(l)
77         elif  l == "disable": return red("dsbl")
78         elif  l == "down": return red(l)
79         elif  l == "boot": return green(l)
80         elif  l == "rins": 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 abstime:
90                 diff = now - timestamp
91         else:
92                 diff = timestamp
93         # return the number of seconds as a difference from current time.
94         t_str = ""
95         if diff < 60: # sec in min.
96                 t = diff / 1
97                 t_str = "%s sec ago" % int(math.ceil(t))
98         elif diff < 60*60: # sec in hour
99                 t = diff / (60)
100                 t_str = "%s min ago" % int(math.ceil(t))
101         elif diff < 60*60*24: # sec in day
102                 t = diff / (60*60)
103                 t_str = "%s hrs ago" % int(math.ceil(t))
104         elif diff < 60*60*24*14: # sec in week
105                 t = diff / (60*60*24)
106                 t_str = "%s days ago" % int(math.ceil(t))
107         elif diff <= 60*60*24*30: # approx sec in month
108                 t = diff / (60*60*24*7)
109                 t_str = "%s wks ago" % int(math.ceil(t))
110         elif diff > 60*60*24*30: # approx sec in month
111                 t = diff / (60*60*24*30)
112                 t_str = "%s mnths ago" % int(t)
113         return t_str
114
115 def getvalue(fb, path):
116     indexes = path.split("/")
117     values = fb
118     for index in indexes:
119         if index in values:
120             values = values[index]
121         else:
122             return None
123     return values
124
125 def nmap_port_status(status):
126         ps = {}
127         l_nmap = status.split()
128         ports = l_nmap[4:]
129
130         continue_probe = False
131         for port in ports:
132                 results = port.split('/')
133                 ps[results[0]] = results[1]
134                 if results[1] == "open":
135                         continue_probe = True
136         return (ps, continue_probe)
137
138
139 def nodegroup_display(node, fbdata, conf=None):
140         node['current'] = get_current_state(fbdata)
141
142         s = fbdata['kernel_version'].split()
143         if len(s) >=3:
144                 node['kernel_version'] = s[2]
145         else:
146                 node['kernel_version'] = fbdata['kernel_version']
147                 
148         if '2.6' not in node['kernel_version']: node['kernel_version'] = ""
149         if conf and not conf.nocolor:
150             node['boot_state']  = color_boot_state(node['boot_state'])
151             node['current']     = color_boot_state(node['current'])
152
153         if type(fbdata['plc_node_stats']['pcu_ids']) == type([]):
154                 node['pcu'] = "PCU"
155         node['lastupdate'] = diff_time(node['last_contact'])
156
157         pf = PersistFlags(node['hostname'], 1, db='node_persistflags')
158         try:
159                 node['lc'] = diff_time(pf.last_changed)
160         except:
161                 node['lc'] = "err"
162
163         ut = fbdata['comon_stats']['uptime']
164         if ut != "null":
165                 ut = diff_time(float(fbdata['comon_stats']['uptime']), False)
166         node['uptime'] = ut
167
168         return "%(hostname)-42s %(boot_state)8s %(current)5s %(pcu)6s %(key)10.10s... %(kernel_version)35.35s %(lastupdate)12s, %(lc)s, %(uptime)s" % node
169
170 def datetime_fromstr(str):
171         if '-' in str:
172                 try:
173                         tup = time.strptime(str, "%Y-%m-%d")
174                 except:
175                         tup = time.strptime(str, "%Y-%m-%d-%H:%M")
176         elif '/' in str:
177                 tup = time.strptime(str, "%m/%d/%Y")
178         else:
179                 tup = time.strptime(str, "%m/%d/%Y")
180         ret = datetime.fromtimestamp(time.mktime(tup))
181         return ret
182
183 def get_nodeset(config):
184         """
185                 Given the config values passed in, return the set of hostnames that it
186                 evaluates to.
187         """
188         api = plc.getAuthAPI()
189         l_nodes = plccache.l_nodes
190
191         if config.nodelist:
192                 f_nodes = util.file.getListFromFile(config.nodelist)
193                 l_nodes = filter(lambda x: x['hostname'] in f_nodes, l_nodes)
194         elif config.node:
195                 f_nodes = [config.node]
196                 l_nodes = filter(lambda x: x['hostname'] in f_nodes, l_nodes)
197         elif config.nodegroup:
198                 ng = api.GetNodeGroups({'name' : config.nodegroup})
199                 l_nodes = api.GetNodes(ng[0]['node_ids'], ['hostname'])
200         elif config.site:
201                 site = api.GetSites(config.site)
202                 l_nodes = api.GetNodes(site[0]['node_ids'], ['hostname'])
203                 
204         l_nodes = [node['hostname'] for node in l_nodes]
205
206         # perform this query after the above options, so that the filter above
207         # does not break.
208         if config.nodeselect:
209                 fbquery = FindbadNodeRecord.get_all_latest()
210                 node_list = [ n.hostname for n in fbquery ]
211                 l_nodes = node_select(config.nodeselect, node_list, None)
212
213         return l_nodes
214