-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstats-mon.py
executable file
·1630 lines (1399 loc) · 57.3 KB
/
stats-mon.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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# The MIT License (MIT)
#
# Copyright (c) 2016-2021 Waterside Consulting, inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
"""
stats-mon.py: Collect metrics and log to time-series database
Used to supplement standard SNMP monitoring for metrics not otherwise reported.
Initial support for Fan speeds, Temperatures, and Power consumption of
Ubiquiti EdgeOS-based EdgeMAX platforms. Additional support now includes
netfilter (iptables) rule counters, detailed memory stats, conntrack,
kernel "random" entropy, vmstat, offload stats, per-cpu interrupts
(HW and SW), kernel cache stats, and process stats.
Metrics are collected and consolidated as relevant time-series measurements.
Each poll cycle is further consolidated as a single measurement set for
publication.
Measurement sets are queued for semi-reliable publication to time series
database. If publication fails the measurements remain queued to try again
with the next polling interval. Measurement sets accumulate up to the
maximum configured value, at which point the oldest sets are discarded
to accomodate more recent measurements.
Performance data of this monitoring daemon is also collected and published as
part of the rest of the measurements, providing visibility into monitoring
overhead.
Logging is performed via standard python 'logger' facilities, with a
syslog handler explicitly configured.
"""
__author__ = "WaterByWind"
__copyright__ = "Copyright 2021, Waterside Consulting, inc."
__license__ = "MIT"
__version__ = "1.2.8"
__maintainer__ = "WaterByWind"
__email__ = "[email protected]"
__status__ = "Development"
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# Dependencies
##
#
# Python Modules
# - subprocess32: https://pypi.org/project/subprocess32/
# - python-iptables: https://pypi.org/project/python-iptables/
# - influxdb: https://pypi.org/project/influxdb/
# - requests: https://pypi.org/project/requests/
# - urllib3: https://pypi.org/project/urllib3/
#
import sys
import os
import time
import re
import errno
import logging
import signal
import resource
from datetime import datetime
from logging.handlers import SysLogHandler
from socket import gethostname
# For modules not bundled with EdgeOS, which are in turn listed below
# This specific (ugly) method is needed for now but may change back to relative imports
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
# Sanitize executable search path. 'python-iptables' depends upon '/sbin'
# being in the PATH, so let's just get this out of the way now.
os.environ['PATH'] = "/usr/bin:/bin:/usr/sbin:/sbin"
# python-influxdb seems to be "broken" now and needs the extra explicit imports
import requests
import requests.exceptions
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBClientError
from influxdb.exceptions import InfluxDBServerError
# Try to use improved subprocess32 backport from Python 3
# If not available fall back to original module
if os.name == 'posix' and sys.version_info[0] < 3:
try:
import subprocess32 as subprocess
except ImportError:
import subprocess
else:
import subprocess
# Try to use python-iptables. This is optional, so don't fail if missing
try:
import iptc
except ImportError:
iptc = None
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# TODOs
##
#
# - cmd line options
# - possible as snmpd subagent (AgentX?)
# - additional metrics
# - conntrack? Prob need conntrackd which doesn't exist here
# - services?
# - Additional publish services?
# - Drop privileges? (not run as root)
# - Risk and value here?
#
# Modules for AgentX:
# -- netsnmpagent: https://pypi.python.org/pypi/netsnmpagent
# -- pyagentx: https://pypi.python.org/pypi/pyagentx
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# Configuration
##
# Interval between start of each poll cycle, in seconds; Fraction OK (but why?)
TIME_POLL_INTERVAL = 60.0
# Maximum number of queued measurement sets
# Beware of memory constraints here
MAX_SETS_QUEUED = 1440
# Detach and become daemon?
DEF_DAEMON = True
# Unprivileged user to run as, if existing
DEF_USER = 'statsmon'
# Logging
LOGLEVEL = logging.INFO # Python logging level
LOGFACILITY = SysLogHandler.LOG_LOCAL5 # syslog facility
LOGSOCK = '/dev/log' # syslog socket
# Defaults for becoming daemon
DEF_DIR_WORK = '/' # Default working dir
DEF_UMASK = 0o0000 # Default UMASK
DEF_MAX_FD = 4096 # Default max FD to close()
# Defaults for PID lockfile
LOCKDIR = '/var/run' # Directory for pidfile
LOCKFILE = 'stats-mon.pid' # pidfile name
MAX_LOCK_ATTEMPT = 5 # Attempts to acquire pidfile
# InfluxDB connection parameters
INFLUXDB = {
'HOST' : 'influxdb.localdomain.com',
'PORT' : '8086',
'USER' : 'user',
'PASSWD' : 'password',
'DATABASE': 'edgemax'
}
##
# Configuration Ends here
##
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# "Constant" definitions
##
# Capabilities known
CAP_FANTACH = 'fan'
CAP_FANCTRL = 'fanctrl'
CAP_POWER = 'power'
CAP_TEMP = 'temp'
CAP_IPTABLES = 'iptables'
CAP_MEMINFO = 'meminfo'
CAP_VMSTAT = 'vmstat'
CAP_CAVSTAT = 'caviumstat'
CAP_CONNTRACK = 'conntrack'
CAP_ENTROPY = 'randentropy'
CAP_INTERRUPTS = 'interrupts'
CAP_SOFTIRQS = 'softirqs'
CAP_SELFSTAT = 'monstats'
CAP_SLABINFO = 'slabinfo'
CAP_PIDSTAT = 'pidstats'
# Default capabilities to attempt to use, from known list above
LIST_CAP = [CAP_FANTACH, CAP_FANCTRL, CAP_POWER, CAP_TEMP, CAP_IPTABLES,
CAP_MEMINFO, CAP_VMSTAT, CAP_CAVSTAT, CAP_CONNTRACK, CAP_ENTROPY,
CAP_INTERRUPTS, CAP_SOFTIRQS, CAP_SELFSTAT, CAP_PIDSTAT, CAP_SLABINFO]
# External paths and arguments
BIN_UBNTHAL = '/usr/sbin/ubnt-hal'
CMD_HAL = {
CAP_FANTACH : 'getFanTach',
CAP_FANCTRL : 'getFanCtrl',
CAP_POWER : 'getPowerStatus',
CAP_TEMP : 'getTemp'
}
PROC_PATH = {
CAP_MEMINFO : '/proc/meminfo',
CAP_VMSTAT : '/proc/vmstat',
CAP_CAVSTAT : '/proc/cavium/stats',
CAP_CONNTRACK : '/proc/sys/net/netfilter',
CAP_ENTROPY : '/proc/sys/kernel/random/entropy_avail',
CAP_INTERRUPTS : '/proc/interrupts',
CAP_SOFTIRQS : '/proc/softirqs',
CAP_SELFSTAT : '/proc/self/stat',
CAP_SLABINFO : '/proc/slabinfo',
CAP_PIDSTAT : '/proc/1/stat' # Do not change PID here
}
LIST_FN_CONNTRACK = ['nf_conntrack_max', 'nf_conntrack_count']
# 'exe' is actually 'udap-bridge' child :(
LIST_PROC_MON = ['ubnt-cfgd', 'ubnt-daemon', 'ubnt-util', 'ubnt-udapi-serv',
'snmpd', 'charon', 'udapi-bridge', 'exe']
# Device types known
DEV_EDGEROUTER = 'edgerouter'
# Protocols
PROTO_IPv4 = 4
PROTO_IPv6 = 6
LIST_PROTO_IP = [PROTO_IPv4, PROTO_IPv6]
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# Exception classes
##
class LockError(RuntimeError):
""" Base exception for errors while aquiring a lock """
def __init__(self, msg='(unknown)'):
self.msg = 'Failed to acquire lock: {}'.format(msg)
super(LockError, self).__init__(self.msg)
class AcquireLockError(LockError):
""" Unexpected failure after too many retries """
pass
class ProcessRunningError(LockError):
""" Another instance already found running """
pass
class MissingOSExecutable(RuntimeError):
""" Exception for missing OS executables """
def __init__(self, msg='(unknown)'):
self.msg = 'Missing OS executable: {}'.format(msg)
super(MissingOSExecutable, self).__init__(self.msg)
class NothingToDo(RuntimeError):
""" Exception when no metrics to collect """
def __init__(self, msg='(unknown)'):
self.msg = 'Nothing to do: {}'.format(msg)
super(NothingToDo, self).__init__(self.msg)
class InsufficientPrivilegeError(RuntimeError):
""" Exception for lack of privileges """
def __init__(self, msg='(unknown)'):
self.msg = 'Insufficient privileges: {}'.format(msg)
super(InsufficientPrivilegeError, self).__init__(self.msg)
class InternalError(RuntimeError):
""" Base exception for unexpected internal errors """
def __init__(self, msg='(unknown)'):
self.msg = 'Internal error: {}'.format(msg)
super(InternalError, self).__init__(self.msg)
class NotImplementedError(InternalError):
""" Attempt to use method/function that has been defined but not implemented """
pass
class UnexpectedUseError(InternalError):
""" Unexpected attempt to use/monitor non-existing entity """
pass
class UnexpectedTableError(InternalError):
""" Unexpected iptables table name passed """
pass
class MeasureMismatchError(InternalError):
""" Attempt to add mismatched measurement to series """
pass
class MissingDataSourceError(InternalError):
""" Asserted capability has no data source """
pass
class DaemonError(Exception):
""" Base exception for errors while becoming a daemon """
def __init__(self, msg='(unknown)'):
self.msg = 'Failure becoming a daemon: {}'.format(msg)
super(DaemonError, self).__init__(self.msg)
class DaemonChdirError(DaemonError):
""" Failed chdir() while becoming a daemon """
def __init__(self, tdir='', errno=0, msg='(unknown)'):
self.msg = 'Failed chdir({}): [errno={}] {}'.format(tdir, errno, msg)
super(DaemonChdirError, self).__init__(self.msg)
class DaemonForkError(DaemonError):
""" Failed fork() while becoming a daemon """
def __init__(self, stage='', errno=0, msg='(unknown)'):
self.msg = 'Failed {} fork(): [errno={}] {}'.format(stage, errno, msg)
super(DaemonForkError, self).__init__(self.msg)
class DaemonOpenError(DaemonError):
""" Failed open()/dup2() while becoming a daemon """
def __init__(self, e):
if hasattr(e, 'filename'):
_msg = 'open({})'.format(e.filename)
else:
_msg = 'dup2()'
self.msg = 'Failed {}: [errno={}] {}'.format(_msg, e.errno, e.strerror)
super(DaemonOpenError, self).__init__(self.msg)
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# Publisher Classes
##
# -- perhaps create base class TimeSeriesPublisher with more dbs supported?
#
class InfluxDBPublisher(object):
""" Class for publishing to InfluxDB v1 time-series database """
def __init__(self,
host='localhost',
port=8086,
username='nobody',
password='nobody',
database=None,
ssl=False,
verify_ssl=False,
timeout=None,
retries=3,
use_udp=False,
udp_port=4444,
proxies=None
):
self.connP = {'host': host,
'port': port,
'username': username,
'password': password,
'database': database,
'ssl': ssl,
'verify_ssl': verify_ssl,
'timeout': timeout,
'retries': retries,
'use_udp': use_udp,
'udp_port': udp_port,
'proxies': proxies
}
self.dataList = []
self._pointSet = []
logging.debug('Creating InfluxDB client to server: {}:{}/{}'.format(
self.connP['host'], self.connP['port'], self.connP['database']))
self._client = InfluxDBClient(**self.connP)
def _doWrite(self, jsonList):
logging.debug('Writing {} series to db: {}'.format(
len(jsonList), jsonList))
success = False
try:
self._client.write_points(jsonList)
except requests.exceptions.ConnectionError as e:
logging.error('Connection Error: {}'.format(e))
except InfluxDBClientError as e:
logging.error('InfluxDBClientError: {}'.format(e))
except InfluxDBServerError as e:
logging.error('InfluxDBServerError: {}'.format(e))
except Exception:
e = sys.exc_info()[0]
logging.error('Exception: {}'.format(e))
else:
success = True
return(success)
def queuePoint(self, jsonBody):
self._pointSet.append(jsonBody)
def stageQueue(self):
if len(self._pointSet) > 0:
# If reached/exceeded maximum number of queued measurement
# sets discard oldest entries to accomodate new entries
while len(self.dataList) >= MAX_SETS_QUEUED:
discard = self.dataList.pop(0)
logging.warning('Max count ({}) of queued measurement sets exceeded'.format(MAX_SETS_QUEUED))
logging.warning('Discarding oldest set: {}'.format(discard))
self.dataList.append(self._pointSet)
self._pointSet = []
def publish(self):
self.stageQueue()
while len(self.dataList) > 0:
# Fetch next data set to publish
pset = self.dataList.pop(0)
# Publish single data set
if not self._doWrite(pset):
# Failure: put data back to try again later
self.dataList.insert(0, pset)
logging.warning(
'Deferring publish of {} sets to next poll interval'.format(len(self.dataList)))
break
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
##
# Device classes
##
class BaseDevice(object):
""" Base class for all monitored devices """
def __init__(self):
self._method = {}.fromkeys(LIST_CAP, None)
self._dsClass = {}.fromkeys(LIST_CAP, None)
self._mpClass = {}.fromkeys(LIST_CAP, None)
self._dataSource = {}.fromkeys(LIST_CAP, None)
self._measurements = []
def _regMethod(self, cap, method):
self._method[cap] = method
def _regDSClass(self, cap, classobj):
self._dsClass[cap] = classobj
def _regMPClass(self, cap, classobj):
self._mpClass[cap] = classobj
def getDSClass(self, cap):
return(self._dsClass.get(cap, None))
def getMPClass(self, cap):
return(self._mpClass.get(cap, None))
def _newDSinst(self, cap):
DS = self.getDSClass(cap)
if not DS:
cls = type(self).__name__
func = sys._getframe(1).f_code.co_name
msg = '{}.{}: Unexpected attempt to use undefined data source: \'{}\''.format(
cls, func, cap)
raise UnexpectedUseError(msg)
self._dataSource[cap] = DS(cap)
def _fetchData(self, cap):
if not self.hasCap(cap):
cls = type(self).__name__
func = sys._getframe(1).f_code.co_name
msg = '{}.{}: Unexpected attempt to use non-asserted capability: \'{}\''.format(
cls, func, cap)
raise UnexpectedUseError(msg)
elif not self.hasDataSource(cap):
cls = type(self).__name__
func = sys._getframe(1).f_code.co_name
msg = '{}.{}: Asserted capability has no data source: \'{}\''.format(
cls, func, cap)
raise MissingDataSourceError(msg)
else:
if not self.hasDSinst(cap):
self._newDSinst(cap)
fetchOut = self._dataSource[cap].getstats()
return(fetchOut)
def listCap(self):
return ([k for k, v in self._method.items() if v is not None])
def hasCap(self, key):
return (self._method.get(key, None) is not None)
def hasDataSource(self, key):
return (self._dsClass.get(key, None) is not None)
def hasDSinst(self, key):
return (self._dataSource.get(key, None) is not None)
def read(self, cap):
f = self._method.get(cap, None)
if f is None:
cls = type(self).__name__
func = sys._getframe(1).f_code.co_name
msg = '{}.{}: Unexpected attempt to use undefined read method: \'{}\''.format(
cls, func, cap)
raise UnexpectedUseError(msg)
return(f(cap))
class EdgeRouter(BaseDevice):
""" Class for Ubiquiti EdgeMAX EdgeRouter devices """
def __init__(self):
super(EdgeRouter, self).__init__()
self.devtype = DEV_EDGEROUTER
if not os.path.isfile(BIN_UBNTHAL):
raise MissingOSExecutable(BIN_UBNTHAL)
# If capability is supported, assert availability, define data source and measurement
if self._checkCap(CAP_FANTACH):
self._regMethod(CAP_FANTACH, self._readFanTach)
self._regDSClass(CAP_FANTACH, UBNTHALSource)
self._regMPClass(CAP_FANTACH, FanSpeeds)
if self._checkCap(CAP_FANCTRL):
self._regMethod(CAP_FANCTRL, self._readFanCtrl)
self._regDSClass(CAP_FANCTRL, UBNTHALSource)
self._regMPClass(CAP_FANCTRL, FanControl)
if self._checkCap(CAP_POWER):
self._regMethod(CAP_POWER, self._readPower)
self._regDSClass(CAP_POWER, UBNTHALSource)
self._regMPClass(CAP_POWER, PowerUse)
if self._checkCap(CAP_TEMP):
self._regMethod(CAP_TEMP, self._readTemp)
self._regDSClass(CAP_TEMP, UBNTHALSource)
self._regMPClass(CAP_TEMP, Temperatures)
if self._checkCap(CAP_IPTABLES):
self._regMethod(CAP_IPTABLES, self._readIPtables)
self._regDSClass(CAP_IPTABLES, IPtableSource)
self._regMPClass(CAP_IPTABLES, IPtables)
if self._checkCap(CAP_MEMINFO):
self._regMethod(CAP_MEMINFO, self._readMemInfo)
self._regDSClass(CAP_MEMINFO, ProcFSSource)
self._regMPClass(CAP_MEMINFO, ProcMemInfo)
if self._checkCap(CAP_VMSTAT):
self._regMethod(CAP_VMSTAT, self._readVMStat)
self._regDSClass(CAP_VMSTAT, ProcFSSource)
self._regMPClass(CAP_VMSTAT, ProcVMStat)
if self._checkCap(CAP_CAVSTAT):
self._regMethod(CAP_CAVSTAT, self._readCavStats)
self._regDSClass(CAP_CAVSTAT, ProcFSSource)
self._regMPClass(CAP_CAVSTAT, ProcCavStat)
if self._checkCap(CAP_ENTROPY):
self._regMethod(CAP_ENTROPY, self._readEntropyAvail)
self._regDSClass(CAP_ENTROPY, ProcFSSource)
self._regMPClass(CAP_ENTROPY, ProcEntropyAvail)
if self._checkCap(CAP_CONNTRACK):
self._regMethod(CAP_CONNTRACK, self._readConntrack)
self._regDSClass(CAP_CONNTRACK, ProcFSSource)
self._regMPClass(CAP_CONNTRACK, ProcConntrack)
if self._checkCap(CAP_INTERRUPTS):
self._regMethod(CAP_INTERRUPTS, self._readInterrupts)
self._regDSClass(CAP_INTERRUPTS, ProcFSSource)
self._regMPClass(CAP_INTERRUPTS, ProcInterrupts)
if self._checkCap(CAP_SOFTIRQS):
self._regMethod(CAP_SOFTIRQS, self._readSoftIRQs)
self._regDSClass(CAP_SOFTIRQS, ProcFSSource)
self._regMPClass(CAP_SOFTIRQS, ProcSoftIRQs)
if self._checkCap(CAP_SELFSTAT):
self._regMethod(CAP_SELFSTAT, self._readSelfStats)
self._regDSClass(CAP_SELFSTAT, ProcFSSource)
self._regMPClass(CAP_SELFSTAT, ProcSelfStats)
if self._checkCap(CAP_SLABINFO):
self._regMethod(CAP_SLABINFO, self._readSlabinfo)
self._regDSClass(CAP_SLABINFO, ProcFSSource)
self._regMPClass(CAP_SLABINFO, ProcSlabinfo)
if self._checkCap(CAP_PIDSTAT):
self._regMethod(CAP_PIDSTAT, self._readPIDStats)
self._regDSClass(CAP_PIDSTAT, ProcFSSourceMulti)
self._regMPClass(CAP_PIDSTAT, ProcPIDStats)
def _checkCap(self, cap):
supported = False
if cap == CAP_IPTABLES:
supported = (iptc is not None)
elif cap in PROC_PATH:
supported = os.path.isfile(PROC_PATH[cap])
elif cap in CMD_HAL:
try:
out = subprocess.check_output(
[BIN_UBNTHAL, CMD_HAL[cap]],
stderr=subprocess.STDOUT).splitlines()[-1]
except subprocess.CalledProcessError:
pass
else:
if not out.endswith('not supported on this platform'):
supported = True
else:
cls = type(self).__name__
func = sys._getframe(1).f_code.co_name
msg = '{}.{}: Unexpected attempt to use non-implemented capability: \'{}\''.format(
cls, func, cap)
raise UnexpectedUseError(msg)
if supported:
logging.debug("Has capability '{}'".format(cap))
return(supported)
def _readFanTach(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split(':')
if len(items) < 2:
continue
key = re.sub(r'\s*', r'', items[0]).lower()
val = re.sub(r'\s*([0-9]*)\s*RPM\s*', r'\1', items[1])
if val != '':
mp.addfield(key, int(val))
return([mp])
def _readFanCtrl(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
key = 'fanctrl'
if fetchOut != '':
mp.addfield(key, int(fetchOut))
return([mp])
def _readPower(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split(':')
if len(items) < 2:
continue
key = re.sub(r'System\s*([a-z]+).*', r'\1', items[0])
val = re.sub(r'\s*([0-9.]*)\s*[VAW]\s*', r'\1', items[1])
if val != '':
mp.addfield(key, float(val))
return([mp])
def _readTemp(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split(':')
if len(items) < 2:
continue
key = re.sub(r'\s*', r'', items[0]).lower()
val = re.sub(r'\s*([0-9.]*)\s*C\s*', r'\1', items[1])
if val != '':
mp.addfield(key, float(val))
return([mp])
def _readIPtables(self, cap):
mpList = []
MPClass = self.getMPClass(cap)
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, UnexpectedTableError,
MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
for p in fetchOut.keys():
for t in fetchOut[p].keys():
tStamp = fetchOut[p][t]['tStamp']
for c in fetchOut[p][t]['chains'].keys():
rList = fetchOut[p][t]['chains'][c]
for rule in rList.keys():
mp = MPClass()
mp.setpoint(tStamp)
mp.addtag('proto', 'IPv{}'.format(p))
mp.addtag('table', t)
mp.addtag('chain', c)
# EdgeOS rule comments, trimmed, as rule name
mp.addtag('ruleid', re.sub(r'([0-9]*)\s.*', r'\1', rule))
mp.addfield('pkts', rList[rule]['pkts'])
mp.addfield('bytes', rList[rule]['bytes'])
mpList.append(mp)
return(mpList)
def _readMemInfo(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split(':', 1)
if len(items) < 2:
continue
key = items[0].strip()
dat = items[1].strip()
val = int(re.sub(r'\s*([0-9]*)\s*.*', r'\1', dat))
scale = re.sub(r'\s*[0-9]*\s*([kKmMgG])[bB].*', r'\1', dat)
# At least as of kernel 5.6 this is still always in kB
if scale in 'kK':
val = val << 10
elif scale in 'mM':
val = val << 20
elif scale in 'gG':
val = val << 30
mp.addfield(key, val)
return([mp])
def _readVMStat(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split()
if len(items) != 2:
continue
mp.addfield(items[0], int(items[1]))
return([mp])
def _readCavStats(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
rexp = re.compile(r'ipv|pppoe|vlan')
for line in fetchOut.splitlines():
if '===' in line:
continue
if ':' in line:
items = line.split(':', 2)
if len(items) < 3:
continue
_c = re.sub(r'\s+', r'_', re.sub(r' packets', r'', items[0]))
_p = items[1].split()[0]
_b = items[2].strip()
mp.addfield('{}_packets'.format(_c), int(_p))
mp.addfield('{}_bytes'.format(_c), int(_b))
else:
items = line.split()
if len(items) == 2:
if 'ipv' in items[0]:
mp.addfield(items[0], int(items[1]))
elif len(items) == 5:
if rexp.match(items[0]):
_r = items[0]
mp.addfield('RX_packets_{}'.format(_r), int(items[1]))
mp.addfield('RX_bytes_{}'.format(_r), int(items[2]))
mp.addfield('TX_packets_{}'.format(_r), int(items[3]))
mp.addfield('TX_bytes_{}'.format(_r), int(items[4]))
return([mp])
def _readConntrack(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
for line in fetchOut.splitlines():
items = line.split(':')
if len(items) != 2:
continue
mp.addfield(items[0], int(items[1]))
return([mp])
def _readEntropyAvail(self, cap):
# Note: entropy changes continually. This metric should be used for
# trending only to identify long-term persistent shortfall
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
mp.addfield('entropy_avail', int(fetchOut.splitlines()[0]))
return([mp])
def _readInterrupts(self, cap):
mpList = []
MPClass = self.getMPClass(cap)
tStamp = datetime.utcnow() # Use single timestamp for this entire measurement
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
ic = {}
for line in fetchOut.splitlines():
if ':' in line:
(irq, _r) = line.split(':', 1)
ic[irq.strip()] = _r.split()
else:
cpulist = line.split()
ncpu = len(cpulist)
for i in ic.keys():
_c = ic[i]
li = len(_c) - 1
if li >= ncpu:
# First #cpu fields are interrupt counters per cpu
# Last two fields are controller and device names
mp = MPClass()
mp.setpoint(tStamp)
mp.addtag('irq', i)
mp.addtag('device', "{}/{}".format(_c[li-1], _c[li]))
for x in range(ncpu):
mp.addfield(cpulist[x], int(_c[x]))
mpList.append(mp)
return(mpList)
def _readSoftIRQs(self, cap):
mpList = []
MPClass = self.getMPClass(cap)
tStamp = datetime.utcnow() # Use single timestamp for this entire measurement
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
ic = {}
for line in fetchOut.splitlines():
if ':' in line:
(irq, _r) = line.split(':', 1)
ic[irq.strip()] = _r.split()
else:
cpulist = line.split()
ncpu = len(cpulist)
for i in ic.keys():
_c = ic[i]
mp = MPClass()
mp.setpoint(tStamp)
mp.addtag('irq', i)
for x in range(ncpu):
mp.addfield(cpulist[x], int(_c[x]))
mpList.append(mp)
return(mpList)
def _readPIDStats(self, cap):
mpList = []
MPClass = self.getMPClass(cap)
tStamp = datetime.utcnow() # Use single timestamp for this entire measurement
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
for line in fetchOut:
mp = MPClass()
mp.setpoint(tStamp)
items = line.split()
# From proc(5), fields in order:
# pid comm state ppid pgrp session tty_nr tpgid flags minflt cminflt
# majflt cmajflt utime stime cutime cstime priority nice num_threads
# itrealvalue starttime vsize rss rsslim startcode endcode startstack
# kstkesp kstkeip signal blocked sigignore sigcatch wchan nswap cnswap
# exit_signal processor rt_priority policy delayacct_blkio_ticks
# guest_time cguest_time start_data end_data start_brk arg_start
# arg_end env_start env_end exit_code
mp.addtag('pid', int(items[0]))
mp.addtag('comm', items[1].strip('()'))
mp.addfield('minflt', int(items[9]))
mp.addfield('cminflt', int(items[10]))
mp.addfield('majflt', int(items[11]))
mp.addfield('cmajflt', int(items[12]))
mp.addfield('utime', int(items[13]))
mp.addfield('stime', int(items[14]))
mp.addfield('cutime', int(items[15]))
mp.addfield('cstime', int(items[16]))
mp.addfield('priority', int(items[17]))
mp.addfield('nice', int(items[18]))
mp.addfield('vsize', int(items[22]))
mp.addfield('rss', int(items[23]))
mp.addfield('rt_priority', int(items[39]))
mp.addfield('delayacct_blkio_ticks', int(items[41]))
mpList.append(mp)
return(mpList)
def _readSelfStats(self, cap):
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
mp = self.getMPClass(cap)()
mp.resetpoint()
items = fetchOut.split()
# From proc(5), fields in order:
# pid comm state ppid pgrp session tty_nr tpgid flags minflt cminflt
# majflt cmajflt utime stime cutime cstime priority nice num_threads
# itrealvalue starttime vsize rss rsslim startcode endcode startstack
# kstkesp kstkeip signal blocked sigignore sigcatch wchan nswap cnswap
# exit_signal processor rt_priority policy delayacct_blkio_ticks
# guest_time cguest_time start_data end_data start_brk arg_start
# arg_end env_start env_end exit_code
mp.addtag('pid', int(items[0]))
mp.addtag('comm', items[1].strip('()'))
mp.addfield('minflt', int(items[9]))
mp.addfield('cminflt', int(items[10]))
mp.addfield('majflt', int(items[11]))
mp.addfield('cmajflt', int(items[12]))
mp.addfield('utime', int(items[13]))
mp.addfield('stime', int(items[14]))
mp.addfield('cutime', int(items[15]))
mp.addfield('cstime', int(items[16]))
mp.addfield('priority', int(items[17]))
mp.addfield('nice', int(items[18]))
mp.addfield('vsize', int(items[22]))
mp.addfield('rss', int(items[23]))
mp.addfield('rt_priority', int(items[39]))
mp.addfield('delayacct_blkio_ticks', int(items[41]))
return([mp])
def _readSlabinfo(self, cap):
mpList = []
MPClass = self.getMPClass(cap)
tStamp = datetime.utcnow() # Use single timestamp for this entire measurement
try:
fetchOut = self._fetchData(cap)
except (UnexpectedUseError, MissingDataSourceError, MeasureMismatchError) as e:
logging.warning(e.msg)
else:
lines = fetchOut.splitlines()
# First line has version - we only support 2.1
try:
v = lines.pop(0).split(':')[1].strip()
except IndexError:
v = '(unknown)'
if v == '2.1':
# Second line lists fields (so we can discard)
# name <active_objs> <num_objs> <objsize> <objperslab> <pagesperslab> \
# : tunables <limit> <batchcount> <sharedfactor> \
# : slabdata <active_slabs> <num_slabs> <sharedavail>
line = lines.pop(0)
for line in lines:
items = line.split()
mp = MPClass()
mp.setpoint(tStamp)
mp.addtag('name', items[0])