-
Notifications
You must be signed in to change notification settings - Fork 0
/
probenodes.py
executable file
·196 lines (165 loc) · 6.22 KB
/
probenodes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python3
from __future__ import absolute_import, division, print_function, unicode_literals
import sys, os
import numpy as np
from functools import partial
from multiprocessing import Pool # TODO: parallelize the looping probe
try:
import spur
except ImportError:
print('Import Error: please install spur package : pip3 install --user spur')
exit(2)
try:
from tabulate import tabulate
except ImportError:
print('Import Error: please install tabulate package : pip3 install --user tabulate')
exit(2)
conf = dict(
username = 'adulac',
private_key = os.path.join(os.path.expanduser('~'), '.ssh/id_rsa'),
#hosts = ['racer', 'tiger', 'victory', 'fuzzy', 'zombie', 'hertog'],
hosts = ['racer', 'tiger', 'victory', 'fuzzy', 'zombie', 'hertog', 'corona', 'macks'],
)
_md_ext = [ 'headerid', 'sane_lists', 'smart_strong', 'extra', 'footnotes',
'smarty', 'codehilite', 'wikilinks', 'fenced_code', 'admonition',
'nl2br', 'abbr', 'toc', 'attr_list', 'def_list', 'tables', 'meta',
]
class ProbeNodes(object):
default_script = './bin/amaburn1.sh'
def __init__(self, conf):
self.conf = conf
for k, v in conf.items():
setattr(self, k, v)
def task_setup(self, task):
if task == 'cpu':
self.headers = ['users/#cores'] + self.hosts
self.op_load = lambda x : x / 100
elif task == 'mem':
self.headers = ['users/%memory'] + self.hosts
self.op_load = lambda x : x
else:
raise ValueError('What task ? %s' % (task))
self.script = [self.default_script, task]
self.task = task
return
# How to keep the connection open ?
def probe_hosts(self, task):
self.task_setup(task)
results = {}
self.shells = {}
for host in self.hosts:
if host == 'zombie':
# ssh/.config is ignored !!!
_host = 'zombie-dust'
else:
_host = host
try:
shell = spur.SshShell(hostname=_host,
username=self.username,
private_key_file=self.private_key,
missing_host_key=spur.ssh.MissingHostKey.auto_add,
shell_type=spur.ssh.ShellTypes.minimal)
with shell:
mesg = shell.run(self.script).output
self.shells[host] = shell
except spur.ssh.ConnectionError as error:
print("host `%s' error: %s" % (host,str( error.original_traceback)[-100:].replace('\n','')))
mesg = 'null'
finally:
results[host] = {'output':mesg}
return results
def format_probes(self, r, sort=True):
hosts = self.hosts
headers = self.headers
task = self.task
try:
self.users = [u.split()[0] for u in list(filter(None, r[hosts[0]]['output'].decode('utf8').split('\n')))]
except Exception as e:
print(e)
print(r[hosts[0]]['output'])
raise (e)
# __remove extras information__
self.users = self.users[:-1]
table = np.zeros((len(self.users), len(hosts)))
_ont = ['user',self.task]
for _col, _h in enumerate(r.items()):
h, res = _h
mesg = res['output']
col = hosts.index(h)
if isinstance(mesg, bytes):
mesg = mesg.decode('utf8')
users = mesg.split('\n')
users = list(filter(None, users))
load_avg = users.pop(-1) # -> self.resulst
headers[col+1] = headers[col+1] + '(%s)'%(load_avg)
for _row, elt in enumerate(users):
u = elt.split()
uname = u[0]
try:
row = self.users.index(uname)
except ValueError:
print('uname error : %s, passing...' % (uname))
continue
try:
load = self.op_load(float(u[_ont.index(task)]))
except:
load = 0
table[row, col] = load
if sort is True:
sort_load = table.sum(1).argsort()[::-1]
table = table[sort_load]
self.users = np.asarray(self.users)[sort_load]
table = np.column_stack((self.users, table))
return table
# don't work
def probe(self):
results = {}
for host, shell in self.shells.items():
results[host] = shell.run(self.script).output
table = self.format_probes(results)
return self.show(table)
def dump(self, task=None, file=sys.stdout, wrap=None):
task = task or self.task
table = self.format_probes(self.probe_hosts(task))
table = tabulate(table, headers=self.headers)
if wrap:
table = wrap(table)
if isinstance(file , str):
with open(file, 'w') as _f:
_f.write(table+'\n')
else:
print(table, file=sys.stdout)
return table
def loop(self, ts=None):
from markdown import markdown
markdown_extra = partial(lambda p, x: markdown(x, p), [ 'markdown.extensions.%s'%(ext) for ext in _md_ext])
tasks = ['cpu', 'mem']
while True:
for t in tasks:
t =self.dump(task=t, file='pb_%s'%t)
#self.dump(task=t, file='pb_%s'%t, wrap=markdown_extra)
print(t)
@staticmethod
def html():
t1 = open('pb_cpu', 'r').read()
t2 = open('pb_mem', 'r').read()
scr = '''<script type="text/javascript">
setTimeout(function () { location.reload(true); }, %s);
</script>''' % (2000)
t = 'HTTP/1.1 200 OK\n\n'
m = '''<!DOCTYPE html><html><body>
<pre>%s \n %s \n %s</pre>
</body></html>''' % (t1, t2, scr)
html = t+m
print(html, file=sys.stdout)
if __name__ == '__main__':
if len(sys.argv) > 1:
conf['task'] = sys.argv[1]
if conf.get('task') == 'html':
ProbeNodes.html()
exit()
pb = ProbeNodes(conf)
if conf.get('task'):
t = pb.dump(conf['task'])
else:
pb.loop()