forked from eschava/psmqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.py
603 lines (488 loc) · 22.1 KB
/
handlers.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import re
import json
import fnmatch
import psutil # pip install psutil
class CommandHandler:
def __init__(self, name):
self.name = name
def handle(self, params):
raise Exception("Not implemented")
class ValueCommandHandler(CommandHandler):
def __init__(self, method_name):
CommandHandler.__init__(self, method_name)
self.method = getattr(psutil, method_name)
def handle(self, params):
if params != '':
raise Exception("Parameter '" + params + "' in '" + self.name + "' is not supported")
return self.get_value()
def get_value(self):
return self.method()
class IndexCommandHandler(CommandHandler):
def __init__(self, method_name):
CommandHandler.__init__(self, method_name)
self.method = getattr(psutil, method_name)
def handle(self, param):
arr = self.get_value()
if param == '*' or param == '*;':
return string_from_list_optionally(arr, param.endswith(';'))
elif param == 'count':
return len(arr)
elif param.isdigit():
return arr[int(param)]
else:
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
def get_value(self):
return self.method()
class TupleCommandHandler(CommandHandler):
def __init__(self, method_name):
CommandHandler.__init__(self, method_name)
self.method = getattr(psutil, method_name)
def handle(self, params):
tup = self.get_value()
if params == '*':
return tup._asdict()
if params == '*;':
return string_from_dict(tup._asdict())
elif params in tup._fields:
return getattr(tup, params)
elif params == '':
raise Exception("Parameter in '" + self.name + "' should be selected")
else:
raise Exception("Parameter '" + params + "' in '" + self.name + "' is not supported")
def get_value(self):
return self.method()
class IndexTupleCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
param, index_str = split(params)
all_params = param == '*' or param == '*;'
index = -1
if param.isdigit():
all_params = True
index = int(param)
elif index_str.isdigit():
index = int(index_str)
elif index_str != '*' and index_str != '*;':
raise Exception("Element '" + index_str + "' in '" + params + "' is not supported")
if index < 0 and all_params:
raise Exception("Cannot list all elements and parameters at the same '" + params + "' request")
result = self.get_value()
if index < 0:
return list_from_array_of_namedtupes(result, param, params, index_str.endswith(';'))
else: # index selected
try:
result = result[index]
if all_params:
return string_from_dict_optionally(result._asdict(), param.endswith(';'))
elif param in result._fields:
return getattr(result, param)
else:
raise Exception("Parameter '" + param + "' in '" + params + "' is not supported")
except IndexError:
raise Exception("Element #" + str(index) + " is not present")
# noinspection PyMethodMayBeStatic
def get_value(self):
raise Exception("Not implemented")
class IndexOrTotalCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
total = True
join = False
count = False
index = -1
if params == '*':
total = False
elif params == '*;':
total = False
join = True
elif params == 'count':
total = False
count = True
elif params.isdigit():
total = False
index = int(params)
elif params != '':
raise Exception("Parameter '" + params + "' in '" + self.name + "' is not supported")
try:
result = self.get_value(total)
if count:
return len(result)
elif index >= 0:
return result[index]
else:
return string_from_list_optionally(result, join)
except IndexError:
raise Exception("Element #" + str(index) + " is not present")
# noinspection PyMethodMayBeStatic
def get_value(self, total):
raise Exception("Not implemented")
class IndexOrTotalTupleCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
param, index_str = split(params)
all_params = param == '*' or param == '*;'
params_join = param.endswith(';')
total = True
index_join = False
index = -1
if index_str == '*':
total = False
elif index_str == '*;':
total = False
index_join = True
elif index_str.isdigit():
total = False
index = int(index_str)
elif index_str != '':
raise Exception("Element '" + index_str + "' in '" + params + "' is not supported")
if not total and index < 0 and all_params:
raise Exception("Cannot list all elements and parameters at the same '" + params + "' request")
result = self.get_value(total)
if index < 0:
if all_params: # not total
return string_from_dict_optionally(result._asdict(), params_join)
else:
if not total:
return list_from_array_of_namedtupes(result, param, params, index_join)
elif param in result._fields:
return getattr(result, param)
else:
raise Exception("Element '" + param + "' in '" + params + "' is not supported")
else: # index selected
try:
result = result[index]
if all_params:
return string_from_dict_optionally(result._asdict(), params_join)
elif param in result._fields:
return getattr(result, param)
else:
raise Exception("Parameter '" + param + "' in '" + params + "' is not supported")
except IndexError:
raise Exception("Element #" + str(index) + " is not present")
# noinspection PyMethodMayBeStatic
def get_value(self, total):
raise Exception("Not implemented")
class NameOrTotalTupleCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
param, name = split(params)
all_params = param == '*' or param == '*;'
params_join = param.endswith(';')
total = True
index_join = False
if name == '*':
total = False
name = None
elif name == '*;':
total = False
index_join = True
name = None
elif name != '':
total = False
if not total and name is None and all_params:
raise Exception("Cannot list all elements and parameters at the same '" + params + "' request")
result = self.get_value(total)
if name is None or name == '':
if all_params: # not total
return string_from_dict_optionally(result._asdict(), params_join)
else:
if not total:
return dict_from_dict_of_namedtupes(result, param, params, index_join)
elif param in result._fields:
return getattr(result, param)
else:
raise Exception("Element '" + param + "' in '" + params + "' is not supported")
else: # name selected
result = result[name]
if all_params:
return string_from_dict_optionally(result._asdict(), params_join)
elif param in result._fields:
return getattr(result, param)
else:
raise Exception("Parameter '" + param + "' in '" + params + "' is not supported")
# noinspection PyMethodMayBeStatic
def get_value(self, total):
raise Exception("Not implemented")
class DiskUsageCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
param, disk = split(params)
if disk == '':
raise Exception("Disk ' in '" + self.name + "' should be specified")
disk = disk.replace('|', '/') # replace slashes with vertical slashes to do not conflict with MQTT topic name
tup = self.get_value(disk)
if param == '*' or param == '*;':
return string_from_dict_optionally(tup._asdict(), param.endswith(';'))
elif param in tup._fields:
return getattr(tup, param)
else:
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
# noinspection PyMethodMayBeStatic
def get_value(self, disk):
return psutil.disk_usage(disk)
class SensorsTemperaturesCommandHandler(CommandHandler):
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
tup = self.get_value()
source, param = split(params)
if source == '*' or source == '*;':
tup = {k: map(lambda i: i.current, v) for k, v in tup.items()}
return string_from_dict_optionally(tup, source.endswith(';'))
elif source in tup:
llist = tup[source]
label, param = split(param)
if label == '' and param == '':
return map(lambda i: i.current, llist)
elif label == '*' or label == '*;':
llist = map(lambda i: i._asdict(), llist)
return string_from_dict_optionally(llist, label.endswith(';'))
else:
temps = llist[int(label)] if label.isdigit() else next((x for x in llist if x.label == label), None)
if temps is None:
raise Exception("Device '" + label + "' in '" + self.name + "' is not supported")
if param == '':
return temps.current
elif param == '*' or param == '*;':
return string_from_dict_optionally(temps._asdict(), param.endswith(';'))
else:
return temps._asdict()[param]
else:
raise Exception("Sensor '" + source + "' in '" + self.name + "' is not supported")
# noinspection PyMethodMayBeStatic
def get_value(self):
return psutil.sensors_temperatures()
class ProcessesCommandHandler(CommandHandler):
top_cpu_regexp = re.compile("^top_cpu(\[\d+\])*$")
top_memory_regexp = re.compile("^top_memory(\[\d+\])*$")
top_number_regexp = re.compile("^top_[a-z_]+\[(\d+)\]$")
pid_file_regexp = re.compile("^pid\[(.*)\]$")
name_pattern_regexp = re.compile("^name\[(.*)\]$")
def __init__(self, name):
CommandHandler.__init__(self, name)
def handle(self, params):
process, param = split(params)
if process == '*' or process == '*;':
if param == '*':
raise Exception("Parameter name in '" + self.name + "' should be specified")
result = dict()
for p in psutil.process_iter():
value = self.get_process_value(p, param, params)
result[p.pid] = value
return string_from_dict_optionally(result, process.endswith(';'))
elif process.isdigit():
pid = int(process)
elif self.top_cpu_regexp.match(process):
pid = self.find_process(process, lambda p: p.cpu_percent(), True)
elif self.top_memory_regexp.match(process):
pid = self.find_process(process, lambda p: p.memory_percent(), True)
elif self.pid_file_regexp.match(process):
pid = self.get_pid_from_file(self.pid_file_regexp.match(process).group(1).replace('|', '/'))
elif self.name_pattern_regexp.match(process):
pid = self.get_find_process(self.name_pattern_regexp.match(process).group(1))
else:
raise Exception("Process in '" + params + "' should be selected")
if pid < 0:
raise Exception("Process " + process + " not found")
process = psutil.Process(pid)
return self.get_process_value(process, param, params)
def find_process(self, request, cmp_func, reverse):
procs = []
for p in psutil.process_iter():
p._sort_value = cmp_func(p)
procs.append(p)
procs = sorted(procs, key=lambda p: p._sort_value, reverse=reverse)
m = self.top_number_regexp.match(request)
index = 0 if m is None else int(m.group(1))
return procs[index].pid
@staticmethod
def get_pid_from_file(filename):
with open(filename) as f:
return int(f.read())
@staticmethod
def get_find_process(pattern):
for p in psutil.process_iter():
if fnmatch.fnmatch(p.name(), pattern):
return p.pid
raise Exception("Process matching '" + pattern + "' not found")
@staticmethod
def get_process_value(process, params, all_params):
prop, param = split(params)
if prop in process_handlers:
return process_handlers[prop].handle(param, process)
else:
raise Exception("Parameter '" + prop + "' in '" + all_params + "' is not supported")
class ProcessCommandHandler:
def __init__(self, name):
self.name = name
def handle(self, param, process):
raise Exception("Not implemented")
class ProcessPropertiesCommandHandler(ProcessCommandHandler):
def __init__(self, name, join, subproperties):
ProcessCommandHandler.__init__(self, name)
self.join = join
self.subproperties = subproperties
def handle(self, param, process):
if param != '':
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
return self.get_value(process)
def get_value(self, process):
result = dict()
for k in process_handlers:
handler = process_handlers[k]
if hasattr(handler, "method") and handler.method is not None: # property is defined for current OS
try:
if isinstance(handler, ProcessMethodCommandHandler):
v = handler.handle('', process)
self.add_to_dict(result, k, v, self.join)
elif self.subproperties:
if isinstance(handler, ProcessMethodIndexCommandHandler) or isinstance(handler, ProcessMethodTupleCommandHandler):
v = handler.handle('*', process)
self.add_to_dict(result, k, v, self.join)
except psutil.AccessDenied: # just skip with property
pass
return string_from_dict_optionally(result, self.join)
@staticmethod
def add_to_dict(d, key, val, join):
if join:
d[key] = val
return
if isinstance(val, dict):
for k in val:
d[key + "/" + k] = val[k]
elif isinstance(val, list):
for i, v in enumerate(val):
d[key + "/" + str(i)] = v
else:
d[key] = val
class ProcessMethodCommandHandler(ProcessCommandHandler):
def __init__(self, name):
ProcessCommandHandler.__init__(self, name)
try:
self.method = getattr(psutil.Process, self.name)
except AttributeError:
self.method = None # method not defined
def handle(self, param, process):
if param != '':
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
return self.get_value(process)
def get_value(self, process):
return self.method(process)
class ProcessMethodIndexCommandHandler(ProcessCommandHandler):
def __init__(self, name):
ProcessCommandHandler.__init__(self, name)
try:
self.method = getattr(psutil.Process, self.name)
except AttributeError:
self.method = None # method not defined
def handle(self, param, process):
arr = self.method(process)
if param == '*' or param == '*;':
return string_from_list_optionally(arr, param.endswith(';'))
elif param == 'count':
return len(arr)
elif param.isdigit():
return arr[int(param)]
else:
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
class ProcessMethodTupleCommandHandler(ProcessCommandHandler):
def __init__(self, name):
ProcessCommandHandler.__init__(self, name)
try:
self.method = getattr(psutil.Process, self.name)
except AttributeError:
self.method = None # method not defined
def handle(self, param, process):
tup = self.method(process)
if param == '*' or param == '*;':
return string_from_dict_optionally(tup._asdict(), param.endswith(';'))
elif param in tup._fields:
return getattr(tup, param)
else:
raise Exception("Parameter '" + param + "' in '" + self.name + "' is not supported")
handlers = {
'cpu_times': TupleCommandHandler('cpu_times'),
'cpu_percent': type("CpuPercentCommandHandler", (IndexOrTotalCommandHandler, object),
{"get_value": lambda self, total: psutil.cpu_percent(percpu=not total)})('cpu_percent'),
'cpu_times_percent': type("CpuTimesPercentCommandHandler", (IndexOrTotalTupleCommandHandler, object),
{"get_value": lambda self, total: psutil.cpu_times_percent(percpu=not total)})('cpu_times_percent'),
'cpu_stats': TupleCommandHandler('cpu_stats'),
'virtual_memory': TupleCommandHandler('virtual_memory'),
'swap_memory': TupleCommandHandler('swap_memory'),
'disk_partitions': type("DiskPartitionsCommandHandler", (IndexTupleCommandHandler, object),
{"get_value": lambda self: psutil.disk_partitions()})('disk_partitions'),
'disk_usage': DiskUsageCommandHandler('disk_usage'),
'disk_io_counters': type("DiskIOCountersCommandHandler", (IndexOrTotalTupleCommandHandler, object),
{"get_value": lambda self, total: psutil.disk_io_counters(perdisk=not total)})('disk_io_counters'),
'net_io_counters': type("NetIOCountersCommandHandler", (NameOrTotalTupleCommandHandler, object),
{"get_value": lambda self, total: psutil.net_io_counters(pernic=not total)})('net_io_counters'),
'processes': ProcessesCommandHandler('processes'),
'users': type("UsersCommandHandler", (IndexTupleCommandHandler, object),
{"get_value": lambda self: psutil.users()})('users'),
'boot_time': type("BootTimeCommandHandler", (ValueCommandHandler, object), {})('boot_time'),
'pids': type("PidsCommandHandler", (IndexCommandHandler, object), {})('pids'),
'sensors_temperatures': SensorsTemperaturesCommandHandler('sensors_temperatures'),
}
process_handlers = {
'*': ProcessPropertiesCommandHandler('*', False, False),
'**': ProcessPropertiesCommandHandler('**', False, True),
'*;': ProcessPropertiesCommandHandler('*;', True, False),
'**;': ProcessPropertiesCommandHandler('**;', True, True),
'pid': type("ProcessPidCommandHandler", (ProcessMethodCommandHandler, object),
{"get_value": lambda self, process: process.pid})('pid'),
'ppid': ProcessMethodCommandHandler('ppid'),
'name': ProcessMethodCommandHandler('name'),
'exe': ProcessMethodCommandHandler('exe'),
'cwd': ProcessMethodCommandHandler('cwd'),
'cmdline': ProcessMethodIndexCommandHandler('cmdline'),
'status': ProcessMethodCommandHandler('status'),
'username': ProcessMethodCommandHandler('username'),
'create_time': ProcessMethodCommandHandler('create_time'),
'terminal': ProcessMethodCommandHandler('terminal'),
'uids': ProcessMethodTupleCommandHandler('uids'),
'gids': ProcessMethodTupleCommandHandler('gids'),
'cpu_times': ProcessMethodTupleCommandHandler('cpu_times'),
'cpu_percent': ProcessMethodCommandHandler('cpu_percent'),
'cpu_affinity': ProcessMethodIndexCommandHandler('cpu_affinity'),
'memory_percent': ProcessMethodCommandHandler('memory_percent'),
'memory_info': ProcessMethodTupleCommandHandler('memory_info'),
'memory_full_info': ProcessMethodTupleCommandHandler('memory_full_info'),
'io_counters': ProcessMethodTupleCommandHandler('io_counters'),
'num_threads': ProcessMethodCommandHandler('num_threads'),
'num_fds': ProcessMethodCommandHandler('num_fds'),
'num_ctx_switches': ProcessMethodTupleCommandHandler('num_ctx_switches'),
'nice': ProcessMethodCommandHandler('nice'),
}
def list_from_array_of_namedtupes(array_of_namedtupes, key, func, join=False):
result = list()
for tup in array_of_namedtupes:
if key in tup._fields:
result.append(getattr(tup, key))
else:
raise Exception("Element '" + key + "' in '" + func + "' is not supported")
return string_from_list_optionally(result, join)
def dict_from_dict_of_namedtupes(dict_of_namedtupes, key, func, join=False):
result = dict()
for name in dict_of_namedtupes:
tup = dict_of_namedtupes[name]
if key in tup._fields:
result[name] = getattr(tup, key)
else:
raise Exception("Element '" + key + "' in '" + func + "' is not supported")
return string_from_dict_optionally(result, join)
def string_from_dict(d):
return json.dumps(d)
def string_from_dict_optionally(d, join):
return string_from_dict(d) if join else d
def string_from_list_optionally(l, join):
return json.dumps(l) if join else l
def split(s):
parts = s.split("/", 1)
return parts if len(parts) == 2 else [parts[0], '']
if __name__ == '__main__':
pass