forked from librenms/librenms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueuemanager.py
641 lines (552 loc) · 23 KB
/
queuemanager.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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
import logging
import threading
import traceback
from queue import Empty
from subprocess import CalledProcessError
import pymysql
import LibreNMS
logger = logging.getLogger(__name__)
class QueueManager:
def __init__(
self, config, lock_manager, type_desc, uses_groups=False, auto_start=True
):
"""
This class manages a queue of jobs and can be used to submit jobs to the queue with post_work()
and process jobs in that queue in worker threads using the work_function
This will attempt to use redis to create a queue, but fall back to an internal queue.
If you are using redis, you can have multiple QueueManagers working on the same queue
You can start or stop the worker threads with start(), stop(), and stop_and_wait()
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: A LibreNMS.Lock instance to help with locks
:param type_desc: description for this queue manager type
:param work_function: function that will be called to perform the task
:param auto_start: automatically start worker threads
"""
self.type = type_desc
self.uses_groups = uses_groups
self.config = config
self.performance = LibreNMS.PerformanceCounter()
self._threads = []
self._queues = {}
self._queue_create_lock = threading.Lock()
self._lm = lock_manager
self._stop_event = threading.Event()
logger.debug("Groups: {}".format(self.config.group))
logger.debug(
"{} QueueManager created: {} workers, {}s frequency".format(
self.type.title(),
self.get_poller_config().workers,
self.get_poller_config().frequency,
)
)
if auto_start:
self.start()
def _service_worker(self, queue_id):
logger.debug("Worker started {}".format(threading.current_thread().getName()))
while not self._stop_event.is_set():
logger.debug(
"Worker {} checking queue {} ({}) for work".format(
threading.current_thread().getName(),
queue_id,
self.get_queue(queue_id).qsize(),
)
)
try:
# cannot break blocking request with redis-py, so timeout :(
device_id = self.get_queue(queue_id).get(True, 10)
if (
device_id is not None
): # None returned by redis after timeout when empty
logger.debug(
"Worker {} ({}) got work {} ".format(
threading.current_thread().getName(), queue_id, device_id
)
)
with LibreNMS.TimeitContext.start() as t:
logger.debug("Queues: {}".format(self._queues))
target_desc = (
"{} ({})".format(device_id if device_id else "", queue_id)
if queue_id
else device_id
)
self.do_work(device_id, queue_id)
runtime = t.delta()
logger.info(
"Completed {} run for {} in {:.2f}s".format(
self.type, target_desc, runtime
)
)
self.performance.add(runtime)
except Empty:
pass # ignore empty queue exception from subprocess.Queue
except CalledProcessError as e:
logger.error(
"{} poller script error! {} returned {}: {}".format(
self.type.title(), e.cmd, e.returncode, e.output
)
)
except Exception as e:
logger.error("{} poller exception! {}".format(self.type.title(), e))
traceback.print_exc()
def post_work(self, payload, queue_id):
"""
Post work to the the queue group.
:param payload: string payload to deliver to the worker
:param queue_id: which queue to post to, 0 is the default
"""
self.get_queue(queue_id).put(payload)
logger.debug(
"Posted work for {} to {}:{} queue size: {}".format(
payload, self.type, queue_id, self.get_queue(queue_id).qsize()
)
)
def start(self):
"""
Start worker threads
"""
workers = self.get_poller_config().workers
groups = (
self.config.group
if hasattr(self.config.group, "__iter__")
else [self.config.group]
)
logger.debug("Starting {} workers for {}".format(workers, self.type))
if self.uses_groups:
for group in groups:
group_workers = max(int(workers / len(groups)), 1)
for i in range(group_workers):
thread_name = "{}_{}-{}".format(self.type.title(), group, i + 1)
self.spawn_worker(thread_name, group)
logger.debug(
"Started {} {} threads for group {}".format(
group_workers, self.type, group
)
)
else:
self.spawn_worker(self.type.title(), 0)
def do_work(self, device_id, group):
pass
def spawn_worker(self, thread_name, group):
pt = threading.Thread(
target=self._service_worker, name=thread_name, args=(group,)
)
pt.daemon = True
self._threads.append(pt)
pt.start()
def restart(self):
"""
Stop the worker threads and wait for them to finish. Then start them again.
"""
self.stop_and_wait()
self.start()
def stop(self):
"""
Stop the worker threads, does not wait for them to finish.
"""
self._stop_event.set()
def stop_and_wait(self):
"""
Stop the worker threads and wait for them to finish.
"""
self.stop() # make sure this has been called so we don't block forever
for t in self._threads:
t.join()
del self._threads[:]
def get_poller_config(self):
"""
Returns the LibreNMS.PollerConfig for this QueueManager
:return: LibreNMS.PollerConfig
"""
return getattr(self.config, self.type)
def get_queue(self, group):
name = self.queue_name(self.type, group)
if name not in self._queues.keys():
with self._queue_create_lock:
if name not in self._queues.keys():
self._queues[name] = self._create_queue(self.type, group)
return self._queues[name]
def _create_queue(self, queue_type, group):
"""
Create a queue (not thread safe)
:param queue_type:
:param group:
:return:
"""
logger.debug("Creating queue {}".format(self.queue_name(queue_type, group)))
try:
return LibreNMS.RedisUniqueQueue(
self.queue_name(queue_type, group),
sentinel_kwargs={
"username": self.config.redis_sentinel_user,
"password": self.config.redis_sentinel_pass,
"socket_timeout": self.config.redis_timeout,
"unix_socket_path": self.config.redis_socket,
},
namespace="librenms.queue",
host=self.config.redis_host,
port=self.config.redis_port,
db=self.config.redis_db,
username=self.config.redis_user,
password=self.config.redis_pass,
unix_socket_path=self.config.redis_socket,
sentinel=self.config.redis_sentinel,
sentinel_service=self.config.redis_sentinel_service,
socket_timeout=self.config.redis_timeout,
)
except ImportError:
if self.config.distributed:
logger.critical(
"ERROR: Redis connection required for distributed polling"
)
logger.critical(
"Please install redis-py, either through your os software repository or from PyPI"
)
exit(2)
except Exception as e:
if self.config.distributed:
logger.critical(
"ERROR: Redis connection required for distributed polling"
)
logger.critical(
"Queue manager could not connect to Redis. {}: {}".format(
type(e).__name__, e
)
)
exit(2)
return LibreNMS.UniqueQueue()
@staticmethod
def queue_name(queue_type, group):
if queue_type and type(group) == int:
return "{}:{}".format(queue_type, group)
else:
raise ValueError(
"Refusing to create improperly scoped queue - parameters were invalid or not set"
)
def record_runtime(self, duration):
self.performance.add(duration)
# ------ Locking Helpers ------
def lock(self, context, context_name="device", allow_relock=False, timeout=0):
return self._lm.lock(
self._gen_lock_name(context, context_name),
self._gen_lock_owner(),
timeout,
allow_relock,
)
def unlock(self, context, context_name="device"):
return self._lm.unlock(
self._gen_lock_name(context, context_name), self._gen_lock_owner()
)
def is_locked(self, context, context_name="device"):
return self._lm.check_lock(self._gen_lock_name(context, context_name))
def _gen_lock_name(self, context, context_name):
return "{}.{}.{}".format(self.type, context_name, context)
def _gen_lock_owner(self):
return "{}-{}".format(self.config.unique_name, threading.current_thread().name)
class TimedQueueManager(QueueManager):
def __init__(
self, config, lock_manager, type_desc, uses_groups=False, auto_start=True
):
"""
A queue manager that periodically dispatches work to the queue
The times are normalized like they started at 0:00
:param config: LibreNMS.ServiceConfig reference to the service config object
:param type_desc: description for this queue manager type
:param uses_groups: If this queue respects assigned groups or there is only one group
:param auto_start: automatically start worker threads
"""
QueueManager.__init__(
self, config, lock_manager, type_desc, uses_groups, auto_start
)
self.timer = LibreNMS.RecurringTimer(
self.get_poller_config().frequency, self.do_dispatch
)
def start_dispatch(self):
"""
Start the dispatch timer, this is not called automatically on init
"""
self.timer.start()
def stop_dispatch(self):
"""
Stop the dispatch timer
"""
self.timer.stop()
def stop(self):
"""
Stop the worker threads and dispatcher thread, does not wait for them to finish.
"""
self.stop_dispatch()
QueueManager.stop(self)
def do_dispatch(self):
pass
class BillingQueueManager(TimedQueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager with two timers dispatching poll billing and calculate billing to the same work queue
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
TimedQueueManager.__init__(
self, config, lock_manager, "billing", False, config.billing.enabled
)
self.calculate_timer = LibreNMS.RecurringTimer(
self.get_poller_config().calculate,
self.dispatch_calculate_billing,
"calculate_billing_timer",
)
def start_dispatch(self):
"""
Start the dispatch timer, this is not called automatically on init
"""
self.calculate_timer.start()
TimedQueueManager.start_dispatch(self)
def stop_dispatch(self):
"""
Stop the dispatch timer
"""
self.calculate_timer.stop()
TimedQueueManager.stop_dispatch(self)
def dispatch_calculate_billing(self):
self.post_work("calculate", 0)
def do_dispatch(self):
self.post_work("poll", 0)
def do_work(self, run_type, group):
if run_type == "poll":
logger.info("Polling billing")
args = ("-d") if self.config.debug else ()
exit_code, output = LibreNMS.call_script("poll-billing.php", args)
else: # run_type == 'calculate'
logger.info("Calculating billing")
args = ("-d") if self.config.debug else ()
exit_code, output = LibreNMS.call_script("billing-calculate.php", args)
if exit_code != 0:
logger.warning(
"Error {} in {} billing:\n{}".format(exit_code, run_type, output)
)
if self.config.log_output:
with open(
"{}/dispatch_billing-{}.log".format(self.config.logdir, run_type), "a"
) as log_file:
log_file.write(output)
class PingQueueManager(TimedQueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager to manage dispatch and workers for Ping
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
TimedQueueManager.__init__(
self, config, lock_manager, "ping", True, config.ping.enabled
)
self._db = LibreNMS.DB(self.config)
def do_dispatch(self):
try:
groups = self._db.query("SELECT DISTINCT (`poller_group`) FROM `devices`")
for group in groups:
self.post_work("", group[0])
except pymysql.err.Error as e:
logger.critical("DB Exception ({})".format(e))
def do_work(self, context, group):
if self.lock(group, "group", timeout=self.config.ping.frequency):
try:
logger.info("Running fast ping")
args = ("-d", "-g", group) if self.config.debug else ("-g", group)
exit_code, output = LibreNMS.call_script("ping.php", args)
if self.config.log_output:
with open(
"{}/dispatch_group_{}_ping.log".format(
self.config.logdir, group
),
"a",
) as log_file:
log_file.write(output)
if exit_code != 0:
logger.warning(
"Running fast ping for {} failed with error code {}: {}".format(
group, exit_code, output
)
)
finally:
self.unlock(group, "group")
class ServicesQueueManager(TimedQueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager to manage dispatch and workers for Services
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
TimedQueueManager.__init__(
self, config, lock_manager, "services", True, config.services.enabled
)
self._db = LibreNMS.DB(self.config)
def do_dispatch(self):
try:
devices = self._db.query(
"SELECT DISTINCT(`device_id`), `poller_group` FROM `services`"
" LEFT JOIN `devices` USING (`device_id`) WHERE `disabled`=0"
)
for device in devices:
self.post_work(device[0], device[1])
except pymysql.err.Error as e:
logger.critical("DB Exception ({})".format(e))
def do_work(self, device_id, group):
if self.lock(device_id, timeout=self.config.services.frequency):
logger.info("Checking services on device {}".format(device_id))
args = ("-d", "-h", device_id) if self.config.debug else ("-h", device_id)
exit_code, output = LibreNMS.call_script("check-services.php", args)
if self.config.log_output:
with open(
"{}/dispatch_device_{}_services.log".format(
self.config.logdir, device_id
),
"a",
) as log_file:
log_file.write(output)
if exit_code == 0:
self.unlock(device_id)
else:
if exit_code == 5:
logger.info(
"Device {} is down, cannot poll service, waiting {}s for retry".format(
device_id, self.config.down_retry
)
)
self.lock(
device_id, allow_relock=True, timeout=self.config.down_retry
)
else:
logger.warning(
"Unknown error while checking services on device {} with exit code {}: {}".format(
device_id, exit_code, output
)
)
class AlertQueueManager(TimedQueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager to manage dispatch and workers for Alerts
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
TimedQueueManager.__init__(
self, config, lock_manager, "alerting", False, config.alerting.enabled
)
self._db = LibreNMS.DB(self.config)
def do_dispatch(self):
self.post_work("alerts", 0)
def do_work(self, device_id, group):
logger.info("Checking alerts")
args = ("-d") if self.config.debug else ()
exit_code, output = LibreNMS.call_script("alerts.php", args)
if self.config.log_output:
with open(
"{}/dispatch_alerts.log".format(self.config.logdir),
"a",
) as log_file:
log_file.write(output)
if exit_code != 0:
if exit_code == 1:
logger.warning("There was an error issuing alerts: {}".format(output))
else:
raise CalledProcessError
class PollerQueueManager(QueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager to manage dispatch and workers for Alerts
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
QueueManager.__init__(
self, config, lock_manager, "poller", True, config.poller.enabled
)
def do_work(self, device_id, group):
if self.lock(device_id, timeout=self.config.poller.frequency):
logger.info("Polling device {}".format(device_id))
args = (
("device:poll", device_id, "-vv")
if self.config.debug
else ("device:poll", device_id, "-q")
)
exit_code, output = LibreNMS.call_script("lnms", args)
if self.config.log_output:
with open(
"{}/dispatch_device_{}_poller.log".format(
self.config.logdir, device_id
),
"a",
) as log_file:
log_file.write(output)
if exit_code == 0:
self.unlock(device_id)
else:
if exit_code == 6:
logger.warning(
"Polling device {} unreachable, waiting {}s for retry".format(
device_id, self.config.down_retry
)
)
# re-lock to set retry timer
self.lock(
device_id, allow_relock=True, timeout=self.config.down_retry
)
else:
logger.error(
"Polling device {} failed with exit code {}: {}".format(
device_id, exit_code, output
)
)
self.unlock(device_id)
else:
logger.debug("Tried to poll {}, but it is locked".format(device_id))
class DiscoveryQueueManager(TimedQueueManager):
def __init__(self, config, lock_manager):
"""
A TimedQueueManager to manage dispatch and workers for Alerts
:param config: LibreNMS.ServiceConfig reference to the service config object
:param lock_manager: the single instance of lock manager
"""
TimedQueueManager.__init__(
self, config, lock_manager, "discovery", True, config.discovery.enabled
)
self._db = LibreNMS.DB(self.config)
def do_dispatch(self):
try:
devices = self._db.query(
"SELECT `device_id`, `poller_group` FROM `devices` WHERE `disabled`=0"
)
for device in devices:
self.post_work(device[0], device[1])
except pymysql.err.Error as e:
logger.critical("DB Exception ({})".format(e))
def do_work(self, device_id, group):
if self.lock(
device_id, timeout=LibreNMS.normalize_wait(self.config.discovery.frequency)
):
logger.info("Discovering device {}".format(device_id))
args = ("-d", "-h", device_id) if self.config.debug else ("-h", device_id)
exit_code, output = LibreNMS.call_script("discovery.php", args)
if self.config.log_output:
with open(
"{}/dispatch_device_{}_discovery.log".format(
self.config.logdir, device_id
),
"a",
) as log_file:
log_file.write(output)
if exit_code == 0:
self.unlock(device_id)
else:
if exit_code == 5:
logger.info(
"Device {} is down, cannot discover, waiting {}s for retry".format(
device_id, self.config.down_retry
)
)
self.lock(
device_id, allow_relock=True, timeout=self.config.down_retry
)
else:
logger.error(
"Discovering device {} failed with exit code {}: {}".format(
device_id, exit_code, output
)
)
self.unlock(device_id)