This repository has been archived by the owner on Nov 23, 2021. It is now read-only.
/
variables.py
792 lines (610 loc) · 22.1 KB
/
variables.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
"""Module for classes that format variables."""
# Standard imports
from time import time
import socket
import re
# pattoo imports
from pattoo_shared import data
from pattoo_shared import files
from pattoo_shared import network
from pattoo_shared.constants import (
DATA_INT, DATA_FLOAT, DATA_COUNT64, DATA_COUNT, DATA_STRING, DATA_NONE,
DATAPOINT_KEYS, AGENT_METADATA_KEYS)
class Metadata():
"""Metadata related to a DataPoint."""
def __init__(self, key, value):
"""Initialize the class.
Args:
key: Metadata key
value: Metadata value
Returns:
None
"""
# Initialize variables
self.key = key
self.value = value
self.update_checksum = True
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
# Create a printable variation of the value
result = ('<{0} key={1}, value={2}>'.format(
self.__class__.__name__, repr(self.key), repr(self.value))
)
return result
class ConverterMetadata(Metadata):
"""Metadata related to a Converter DataPoint."""
def __init__(self, key, value, update_checksum=True):
"""Initialize the class.
Args:
key: Metadata key
value: Metadata value
update_checksum: When True, the Datapoint object will update its
checksum using the metadata values of objects created with this
class. The DataPoint checksums are used to create new database
entries. Not all metadata changes should trigger the creation
of a new datapoint for charting. The updating of an operating
system kernel version as metadata may not necessarily mean a
completely new data source.
Returns:
None
Variables:
self.key: Metadata key
self.value: Metadata value
self.valid: True if valid
"""
# Inherit object
Metadata.__init__(self, key, value)
# Initialize variables
self.update_checksum = bool(update_checksum)
(self.key, self.value, self.valid) = _key_value_valid(
key, value, metadata=True, override=True)
# Reset valid
self.valid = False not in [
key in AGENT_METADATA_KEYS,
self.valid
]
class DataPointMetadata(Metadata):
"""Metadata related to a Regular DataPoint."""
def __init__(self, key, value, update_checksum=True):
"""Initialize the class.
Args:
key: Metadata key
value: Metadata value
update_checksum: When True, the Datapoint object will update its
checksum using the metadata values of objects created with this
class. The DataPoint checksums are used to create new database
entries. Not all metadata changes should trigger the creation
of a new datapoint for charting. The updating of an operating
system kernel version as metadata may not necessarily mean a
completely new data source.
Returns:
None
Variables:
self.key: Metadata key
self.value: Metadata value
self.valid: True if valid
"""
# Inherit object
Metadata.__init__(self, key, value)
self.update_checksum = bool(update_checksum)
# Initialize variables
(self.key, self.value, self.valid) = _key_value_valid(
key, value, metadata=True)
class DataPoint():
"""Variable representation for data retreived from a target.
Stores individual datapoints polled by pattoo agents
"""
def __init__(self, key, value, data_type=DATA_INT, timestamp=None):
"""Initialize the class.
Args:
key: Key related to data value
value: Data value
data_type: This MUST be one of the types listed in constants.py
timestamp: Integer EPOCH timestamp in milliseconds
Returns:
None
Variables:
self.timestamp: Integer of epoch milliseconds
self.valid: True if the object has a valid data_type
self.checksum: Hash of self.key, self.data_type and metadata to
ensure uniqueness when assigned to a target.
"""
# Initialize variables
(self.key, self.value, self.valid) = _key_value_valid(
key, value, metadata=False)
self.data_type = data_type
self.metadata = {}
self._metakeys = []
# Round timestamp to the nearest millisecond.
if data.is_numeric(timestamp) is False:
self.timestamp = int(round(time(), 3) * 1000)
else:
self.timestamp = int(timestamp)
# False validity if value is not of the right type
self.valid = False not in [
data_type in [
DATA_INT,
DATA_FLOAT,
DATA_COUNT64,
DATA_COUNT,
DATA_STRING,
DATA_NONE
],
data_type is not False,
data_type is not True,
data_type is not None,
self.valid is True
]
# Validity check: Make sure numeric data_types have numeric values
if False not in [
data_type in [
DATA_INT,
DATA_FLOAT,
DATA_COUNT64,
DATA_COUNT
],
self.valid is True,
data.is_numeric(value) is False]:
self.valid = False
# Convert floatable strings to float, and integers to ints
if False not in [
self.valid is True,
data.is_numeric(value) is True,
isinstance(value, str) is True]:
if data_type in [DATA_FLOAT, DATA_COUNT64, DATA_COUNT]:
self.value = float(value)
elif data_type in [DATA_INT]:
self.value = int(float(value))
# Convert strings to string
if data_type in [DATA_STRING]:
self.value = str(value)
# Create checksum
self.checksum = data.hashstring(
'{}{}'.format(self.key, self.data_type))
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
# Create a printable variation of the value
printable_value = _strip_non_printable(self.key)
result = ('''\
<{} key={}, value={}, data_type={}, timestamp={}, valid={}>\
'''.format(self.__class__.__name__,
repr(printable_value), repr(self.value),
repr(self.data_type), repr(self.timestamp),
repr(self.valid))
)
return result
def add(self, items):
"""Add DataPointMetadata to the internal self.metadata list.
Args:
items: A DataPointMetadata object list
Returns:
None
"""
# Ensure there is a list of objects
if isinstance(items, list) is False:
items = [items]
# Only append approved data types
for item in items:
if isinstance(item, Metadata) is True:
# Ignore invalid values
if item.valid is False or item.key in DATAPOINT_KEYS:
continue
# Process
if item.key not in self._metakeys:
self.metadata[item.key] = item.value
self._metakeys.append(item.key)
if bool(item.update_checksum) is True:
self.checksum = data.hashstring('''\
{}{}{}'''.format(self.checksum, item.key, item.value))
class PostingDataPoints():
"""Object defining DataPoint objects to post to the pattoo server."""
def __init__(self, agent_id, polling_interval, datapoints):
"""Initialize the class.
Args:
agent_id: Unique ID of agent posting data
polling_interval: Periodic interval over which the data was polled.
datapoints: List of DataPoint objects
Returns:
None
"""
# Initialize key variables
self.pattoo_agent_id = agent_id
self.pattoo_agent_polling_interval = polling_interval
self.pattoo_datapoints = datapoints
self.pattoo_timestamp = int(time() * 1000)
# Validation tests
self.valid = False not in [
isinstance(self.pattoo_agent_id, str),
isinstance(self.pattoo_agent_polling_interval, int),
isinstance(self.pattoo_datapoints, dict),
self.pattoo_agent_polling_interval is not False,
self.pattoo_agent_polling_interval is not True,
]
if self.valid is True:
self.valid = False not in [
self.valid,
'datapoint_pairs' in datapoints.keys(),
'key_value_pairs' in datapoints.keys()
]
if self.valid is True:
self.valid = False not in [
self.valid,
isinstance(datapoints['datapoint_pairs'], list),
isinstance(datapoints['key_value_pairs'], dict)
]
class TargetDataPoints():
"""Object defining a list of DataPoint objects.
Stores DataPoints polled from a specific ip_target.
"""
def __init__(self, target):
"""Initialize the class.
Args:
target: Target polled to get the DataPoint objects
Returns:
None
Variables:
self.data: List of DataPoints retrieved from the target
self.valid: True if the object is populated with DataPoints
"""
# Initialize key variables
self.data = []
self.target = target
self.valid = False
self._checksums = []
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
# Create a printable variation of the value
result = (
'<{0} target={1}, valid={2}, data={3}'
''.format(
self.__class__.__name__,
repr(self.target), repr(self.valid), repr(self.data)
)
)
return result
def add(self, items):
"""Append DataPoint to the internal self.data list.
Args:
items: A DataPoint object list
Returns:
None
"""
# Ensure there is a list of objects
if isinstance(items, list) is False:
items = [items]
# Only add DataPoint objects that are not duplicated
for item in items:
if isinstance(item, DataPoint) is True:
if item.checksum not in self._checksums:
self.data.append(item)
self._checksums.append(item.checksum)
# Set object as being.valid
self.valid = False not in [bool(self.data), bool(self.target)]
class AgentPolledData():
"""Object defining data received from / sent by Agent.
Only AgentPolledData objects can be submitted to the pattoo server through
phttp.Post()
"""
def __init__(self, agent_program, polling_interval):
"""Initialize the class.
Args:
agent_program: Name of agent program collecting the data
polling_interval: Polling interval
Returns:
None
Variables:
self.data: List of TargetDataPoints objects created by polling
self.valid: True if the object contains TargetDataPoints objects
"""
# Initialize key variables
self.agent_program = agent_program
self.agent_hostname = socket.getfqdn()
self.agent_timestamp = int(time() * 1000)
self.data = []
self.valid = False
self.agent_polling_interval = polling_interval * 1000
# Get the agent_id
from .configuration import Config
config = Config()
self.agent_id = files.get_agent_id(agent_program, config)
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
# Return
result = ('''\
<{0} agent_id={1} agent_program={2}, agent_hostname={3}, timestamp={4} \
polling_interval={5}, valid={6}>\
'''.format(self.__class__.__name__, repr(self.agent_id),
repr(self.agent_program), repr(self.agent_hostname),
repr(self.agent_timestamp), repr(self.agent_polling_interval),
repr(self.valid)))
return result
def add(self, items):
"""Append TargetDataPoints to the internal self.data list.
Args:
items: A TargetDataPoints object list
Returns:
None
"""
# Do nothing if not a list
if isinstance(items, list) is False:
items = [items]
# Only append approved data types
for item in items:
# Only append approved data types
if isinstance(item, TargetDataPoints) is True:
# Ignore invalid values
if item.valid is False:
continue
# Process
self.data.append(item)
# Set object as being.valid
self.valid = False not in [
bool(self.agent_id),
bool(self.agent_program),
bool(self.agent_hostname),
bool(self.agent_polling_interval),
bool(self.data)]
class AgentAPIVariable():
"""Variable representation for data required by the AgentAPI."""
def __init__(self, ip_bind_port=20201, ip_listen_address='0.0.0.0'):
"""Initialize the class.
Args:
ip_bind_port: ip_bind_port
listen_address: TCP/IP address on which the API is listening.
Returns:
None
"""
# Initialize variables
self.ip_bind_port = ip_bind_port
self.ip_listen_address = ip_listen_address
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
result = ('''\
<{0} ip_bind_port={1}, ip_listen_address={2}>\
'''.format(self.__class__.__name__,
repr(self.ip_bind_port),
repr(self.ip_listen_address)
)
)
return result
class PollingPoint():
"""Object used to track data to be polled."""
def __init__(self, address=None, multiplier=1):
"""Initialize the class.
Args:
address: Address to poll
multiplier: Multiplier to use when polled
Returns:
None
"""
# Initialize variables
self.address = address
if data.is_numeric(multiplier) is True:
self.multiplier = multiplier
else:
self.multiplier = 1
self.valid = address is not None
# Create checksum
seed = '{}{}'.format(address, multiplier)
self.checksum = data.hashstring(seed)
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
result = ('''\
<{0} address={1}, multiplier={2}>\
'''.format(self.__class__.__name__,
repr(self.address),
repr(self.multiplier)
))
return result
class TargetPollingPoints():
"""Object defining a list of PollingPoint objects.
Stores PollingPoints polled from a specific ip_target.
"""
def __init__(self, target):
"""Initialize the class.
Args:
target: Target polled to get the PollingPoint objects
Returns:
None
Variables:
self.data: List of PollingPoints retrieved from the target
self.target: Name of target from which the data was received
self.valid: True if the object is populated with PollingPoints
"""
# Initialize key variables
self.data = []
self.target = target
self.valid = False
self._checksums = []
def __repr__(self):
"""Return a representation of the attributes of the class.
Args:
None
Returns:
result: String representation.
"""
# Create a printable variation of the value
result = (
'<{0} target={1}, valid={2}, data={3}>'
''.format(
self.__class__.__name__,
repr(self.target), repr(self.valid), repr(self.data)
)
)
return result
def add(self, items):
"""Append PollingPoint to the internal self.data list.
Args:
items: A PollingPoint object list
Returns:
None
"""
# Ensure there is a list of objects
if isinstance(items, list) is False:
items = [items]
# Only add PollingPoint objects that are not duplicated
for item in items:
if isinstance(item, PollingPoint) is True:
# Ignore invalid values
if item.valid is False:
continue
# Add data to the list
if item.checksum not in self._checksums:
self.data.append(item)
# Set object as being.valid
self.valid = False not in [bool(self.data), bool(self.target)]
class IPTargetPollingPoints(TargetPollingPoints):
"""Object defining a list of PollingPoint objects.
Stores PollingPoints polled from a specific ip_target.
"""
def __init__(self, target):
"""Initialize the class.
Args:
target: Target polled to get the PollingPoint objects
Returns:
None
Variables:
self.data: List of PollingPoints retrieved from the target
self.target: Name of target from which the data was received
self.valid: True if the object is populated with PollingPoints
"""
# Inherit object
TargetPollingPoints.__init__(self, target)
def add(self, items):
"""Append PollingPoint to the internal self.data list.
Args:
items: A PollingPoint object list
Returns:
None
"""
# Ensure there is a list of objects
if isinstance(items, list) is False:
items = [items]
# Only add PollingPoint objects that are not duplicated
for item in items:
if isinstance(item, PollingPoint) is True:
# Ignore invalid values
if item.valid is False:
continue
# Add data to the list
if item.checksum not in self._checksums:
self.data.append(item)
# Set object as being.valid
self.valid = False not in [
bool(self.data), bool(network.get_ipaddress(self.target))]
def _strip_non_printable(value):
"""Strip non printable characters.
Removes any non-printable characters and adds an indicator to the string
when binary characters are found.
Args:
value: the value that you wish to strip
Returns:
printable_value: Printable string
"""
# Initialize key variables
printable_value = ''
if isinstance(value, str) is False:
printable_value = value
else:
# Filter all non-printable characters
# (note that we must use join to account for the fact that Python 3
# returns a generator)
printable_value = ''.join(
[x for x in value if x.isprintable() is True])
if printable_value != value:
if bool(printable_value) is True:
printable_value = '{} '.format(printable_value)
printable_value = '{}(contains binary)'.format(printable_value)
# Return
return printable_value
def _key_value_valid(key, value, metadata=False, override=False):
"""Create a standardized version of key, value.
Args:
key: Key
value: Value
metadata: If True, convert value to string and strip. Used for
metadata key-value pairs.
override: Allow the 'pattoo' string in the key. Used when posting
DataPoint objects to the pattoo server.
Returns:
result: Tuple of (key, value, valid)
"""
# Set variables
valid = False not in [
isinstance(key, (str, int, float)) is True,
key is not True,
key is not False,
key is not None,
isinstance(value, (str, int, float)) is True,
value is not True,
value is not False,
value is not None,
]
# Assign key, value
if valid is True:
key = str(key).lower().strip()
# Reevaluate valid
valid = False not in [
valid,
key != '']
# 'pattoo' normally cannot be in the key.
if override is False:
valid = False not in [
valid,
'pattoo' not in key.lower()]
# Assign values
if valid is True:
if bool(metadata) is True:
value = str(value).strip()
else:
key = None
value = None
# Return
result = (key, value, valid)
return result
def _strip_pattoo(key):
"""Remove the string 'pattoo' from key.
1) Remove the string 'pattoo' from key
2) Replace dashes ('-') with underscores ('_')
3) Remove leading underscores
4) Strip leading and trailing white space
5) Make the key lowercase
Args:
key: Key to process
Returns:
result: Key without string.
"""
# Return
result = str(key).lower().strip().replace('pattoo', '').replace('-', '_')
result = re.sub(r'^(_)+(.*?)$', '\\2', result)
return result