/
ttp.py
3146 lines (2832 loc) · 122 KB
/
ttp.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
# -*- coding: utf-8 -*-
import re
import os
import logging
from xml.etree import cElementTree as ET
from multiprocessing import Process, cpu_count, JoinableQueue, Queue
from sys import version_info
from sys import getsizeof
from collections import OrderedDict
# Initiate global variables
python_major_version = version_info.major
log = logging.getLogger(__name__)
_ttp_ = {
"macro": {},
"python_major_version": python_major_version,
"global_vars": {},
"template_obj": {},
}
"""
==============================================================================
TTP LAZY IMPORT SYSTEM
==============================================================================
"""
class CachedModule:
"""Class that contains name of the function and path to module/file
that contains that function, on first call to this class, function
will be imported into _ttp_ dictionary, subsequent calls we call
function directly
"""
def __init__(self, import_path, parent_dir, function_name, functions):
self.import_path = import_path
self.parent_dir = parent_dir
self.function_name = function_name
self.parent_module_functions = functions
def load(self):
# import cached function and insert it into _ttp_ dictionary
abs_import = "ttp."
if __name__ == "__main__" or __name__ == "__mp_main__":
abs_import = ""
path = "{abs}{imp}".format(abs=abs_import, imp=self.import_path)
module = __import__(path, fromlist=[None])
setattr(module, "_ttp_", _ttp_)
try:
_name_map_ = getattr(module, "_name_map_")
except AttributeError:
_name_map_ = {}
for func_name in self.parent_module_functions:
name = _name_map_.get(func_name, func_name)
_ttp_[self.parent_dir][name] = getattr(module, func_name)
def __call__(self, *args, **kwargs):
# this method invoked on CachedModule class call, triggering function import
log.info(
"calling CachedModule: module '{}', function '{}'".format(
self.import_path, self.function_name
)
)
self.load()
# call original function
return _ttp_[self.parent_dir][self.function_name](*args, **kwargs)
def lazy_import_functions():
"""function to collect a list of all files/directories within ttp module,
parse .py files using ast and extract information about all functions
to cache them within _ttp_ dictionary
"""
log.info("ttp.lazy_import_functions: starting functions lazy import")
import ast
# get exclusion suffix
if python_major_version == 2:
exclude = "_py3.py"
elif python_major_version == 3:
exclude = "_py2.py"
module_files = []
exclude_modules = ["ttp.py"]
# create a list of all ttp module files
for item in os.walk(os.path.dirname(__file__)):
root, dirs, files = item
module_files += [
open("{}/{}".format(root, f), "r")
for f in files
if (
f.endswith(".py")
and not f.startswith("_")
and not f.endswith(exclude)
and not f in exclude_modules
)
]
log.info("ttp.lazy_import_functions: files loaded, starting ast parsing")
# get all functions from modules and cache them in _ttp_
for module_file in module_files:
node = ast.parse(module_file.read())
assignments = [n for n in node.body if isinstance(n, ast.Assign)]
functions = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
functions = [f for f in functions if (not f.startswith("_"))]
# get _name_map_
_name_map_ = {}
for assignment in assignments:
# stop if _name_map_ already found
if _name_map_:
break
for target in assignment.targets:
if target.id == "_name_map_":
_name_map_.update(
{
key.s: assignment.value.values[index].s
for index, key in enumerate(assignment.value.keys)
}
)
# fill in _ttp_ dictionary with CachedModule class
parent_path, filename = os.path.split(module_file.name)
_, parent_dir = os.path.split(parent_path)
for func_name in functions:
name = _name_map_.get(func_name, func_name)
path = "{}.{}".format(parent_dir, filename.replace(".py", ""))
_ttp_.setdefault(parent_dir, {})[name] = CachedModule(
path, parent_dir, name, functions
)
module_file.close()
log.info("ttp.lazy_import_functions: finished functions lazy import")
"""
==============================================================================
MAIN TTP CLASS
==============================================================================
"""
class ttp:
""" Template Text Parser main class to load data, templates, lookups, variables
and dispatch data to parser object to parse in single or multiple processes,
construct final results and run outputs.
**Parameters**
* ``data`` file object or OS path to text file or directory with text files with data to parse
* ``template`` file object or OS path to text file with template
* ``base_path`` (str) base OS path prefix to load data from for template's inputs
* ``log_level`` (str) level of logging "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
* ``log_file`` (str) path where to save log file
* ``vars`` dictionary of variables to make available to ttp parser
Example::
from ttp import ttp
parser = ttp(data="/os/path/to/data/dir/", template="/os/path/to/template.txt")
parser.parse()
result = parser.result(format="json")
print(result[0])
"""
def __init__(
self,
data="",
template="",
log_level="WARNING",
log_file=None,
base_path="",
vars={},
):
self.__data_size = 0
self.__datums_count = 0
self._templates = []
self.base_path = base_path
self.multiproc_threshold = 5242880 # in bytes, equal to 5MBytes
self.vars = vars # dictionary of variables to add to each template vars
self.lookups = {}
# setup logging
logging_config(log_level, log_file)
# lazy import all functions
lazy_import_functions()
# add reference to TTP object in _ttp_ dunder
_ttp_["ttp_object"] = self
# check if template given, if so - load it
if template != "":
self.add_template(template=template)
# check if data given, if so - load it:
if data != "":
self.add_input(data=data)
def add_input(
self,
data,
input_name="Default_Input",
template_name="_root_template_",
groups=["all"],
):
"""Method to load additional data to be parsed. Data associated with certain
input of ``input_name`` and template of ``template_name``.
.. warning:: ``add_input`` should be called only after templates added
**Parameters**
* ``data`` file object or OS path to text file or directory with text files with data to parse
* ``input_name`` (str) name of the input to put data in, default is *Default_Input*
* ``groups`` (list) list of group names to use to parse this input data
* ``template_name`` (str) name of the template to add input for
"""
if not self._templates:
log.warning("ttp.add_input: no TTP templates to associate input data with, load template(s) first.")
# form a list of ((type, url|text,), input_name, groups,) tuples
data_items = _ttp_["utils"]["load_files"](path=data, read=False)
if data_items:
[
template.update_input(
data=data_items, input_name=input_name, groups=groups
)
for template in self._templates
if template.name == template_name
]
def set_input(
self,
data,
input_name="Default_Input",
template_name="_root_template_",
groups=["all"],
):
"""Method to replace existing templates inputs data with new set of data. This
method is alias to ``clear_input`` and ``add_input`` methods.
.. warning:: ``set_input`` should be called only after templates added
**Parameters**
* ``data`` file object or OS path to text file or directory with text files with data to parse
* ``input_name`` (str) name of the input to put data in, default is *Default_Input*
* ``groups`` (list) list of group names to use to parse this input data
* ``template_name`` (str) name of the template to set input for
"""
if not self._templates:
log.warning("ttp.set_input: no TTP templates to associate input data with, load template(s) first.")
self.clear_input(template_name=template_name)
self.add_input(
data=data, input_name=input_name, groups=groups, template_name=template_name
)
def clear_input(self, template_name=None):
"""Method to delete all input data for all or some templates, can be used prior to adding new
set of data to parse with same templates, instead of re-initializing ttp object.
**Parameters**
* ``template_name`` (str) name of the template to clear input for, clears for all templates
by default
"""
self.__data_size = 0
self.__datums_count = 0
for template in self._templates:
if template_name is None:
template.inputs = {}
elif template.name == template_name:
template.inputs = {}
def _calculate_overall_data_size(self):
"""Method to calculate overall data size and count
"""
self.__data_size = 0
self.__datums_count = 0
for template in self._templates:
# get overall data size and count
for input_name, input_obj in template.inputs.items():
self.__datums_count += len(input_obj.data)
# get data size
for i in input_obj.data:
if i[0] == "file_name":
self.__data_size += os.path.getsize(i[1])
elif i[0] == "text_data":
self.__data_size += getsizeof(i[1])
def add_template(self, template, template_name="_root_template_", filter=[]):
"""Method to load TTP templates into the parser.
**Parameters**
* ``template`` file object or OS path to text file with template
* ``template_name`` (str) name of the template
* ``filter`` (list) list of templates' names to load,
``filter`` attribute allow to filter the list of template names that
should be loaded. Checks done against child templates as well. For
templates specified in filter list, groups/macro/inputs/etc. will not
be loaded and no results produced.
"""
log.debug("ttp.add_template - loading template '{}'".format(template_name))
# get a list of [(type, text,)] tuples or empty list []
items = _ttp_["utils"]["load_files"](path=template, read=True)
for i in items:
template_obj = _template_class(
template_text=i[1],
base_path=self.base_path,
ttp_vars=self.vars,
name=template_name,
filter=filter,
)
# if not template_obj.templates - no 'template' tags in template
self._templates += (
template_obj.templates if template_obj.templates else [template_obj]
)
def add_lookup(self, name, text_data="", include=None, load="python", key=None):
"""Method to add lookup table data to all templates loaded so far. Lookup is a
text representation of structure that can be loaded into python dictionary using one
of the available loaders - python, csv, ini, yaml, json.
**Parameters**
* ``name`` (str) name to assign this lookup table for referencing
* ``text_data`` (str) text to load lookup table/dictionary from
* ``include`` (str) absolute or relative /os/path/to/lookup/table/file.txt
* ``load`` (str) name of TTP loader to use to load table data
* ``key`` (str) specify key column for csv loader to construct dictionary
``include`` can accept relative OS path - relative to the directory where TTP will be
invoked either using CLI tool or as a module
"""
lookup_data = _ttp_["utils"]["load_struct"](
text_data=text_data, include=include, load=load, key=key
)
self.lookups.update({name: lookup_data})
[template.add_lookup({name: lookup_data}) for template in self._templates]
def add_vars(self, vars):
"""Method to add variables to ttp and its templates to reference during parsing
**Parameters**
* ``vars`` dictionary of variables to make available to ttp parser
"""
if isinstance(vars, dict):
self.vars.update(vars)
[template.add_vars(vars) for template in self._templates]
def parse(self, one=False, multi=False):
"""Method to parse data with templates.
**Parameters**
* ``one`` (boolean) if set to True will run parsing in single process
* ``multi`` (boolean) if set to True will run parsing in multiprocess
By default one and multi set to False and TTP will run parsing following below rules:
1. if one or multi set to True run in one or multi process
2. if overall data size is less then 5Mbyte, use single process
3. if overall data size is more then 5Mbytes, use multiprocess
In addition to 3 TTP will check if number of input data items more then 1, if so
multiple processes will be used and one process otherwise.
"""
# add self.__data to templates and get file count and size:
self._calculate_overall_data_size()
log.info(
"ttp.parse: loaded datums - {}, overall size - {} bytes".format(
self.__datums_count, self.__data_size
)
)
if one is True and multi is True:
log.critical("ttp.parse - choose one or multiprocess parsing")
raise SystemExit()
elif one is True:
self.__parse_in_one_process()
elif multi is True:
self.__parse_in_multiprocess()
elif self.__data_size > self.multiproc_threshold and self.__datums_count >= 2:
self.__parse_in_multiprocess()
else:
self.__parse_in_one_process()
# run outputters defined in templates:
[template.run_outputs() for template in self._templates]
def __parse_in_multiprocess(self):
"""Method to parse data in bulk by parsing each data item
against each template and saving results in results list.
"""
log.info("ttp.parse: parse using multiple processes")
num_processes = cpu_count()
for template in self._templates:
num_jobs = 0
tasks = JoinableQueue()
results_queue = Queue()
workers = [
_worker(
tasks,
results_queue,
lookups=template.lookups,
vars=template.vars,
groups=template.groups,
macro_text=template.macro_text,
)
for i in range(num_processes)
]
[w.start() for w in workers]
for input_name, input_obj in template.inputs.items():
for datum in input_obj.data:
task_dict = {
"data": datum,
"groups_indexes": input_obj.groups_indexes,
"input_functions": input_obj.functions,
}
tasks.put(task_dict)
num_jobs += 1
[tasks.put(None) for i in range(num_processes)]
# wait for all tasks to complete
tasks.join()
for i in range(num_jobs):
result = results_queue.get()
template.form_results(result)
def __parse_in_one_process(self):
"""Method to parse data in single process, each data item parsed
against each template and results saved in results list
"""
log.info("ttp.parse: parse using single process")
for template in self._templates:
_ttp_["macro"] = template.macro
_ttp_["template_obj"] = template
parserObj = _parser_class(
lookups=template.lookups, vars=template.vars, groups=template.groups
)
if template.results_method.lower() == "per_input":
for input_name, input_obj in template.inputs.items():
for datum in input_obj.data:
parserObj.set_data(
datum, main_results={}, input_functions=input_obj.functions
)
parserObj.parse(groups_indexes=input_obj.groups_indexes)
result = parserObj.main_results
template.form_results(result)
elif template.results_method.lower() == "per_template":
results_data = {}
for input_name, input_obj in template.inputs.items():
for datum in input_obj.data:
parserObj.set_data(
datum,
main_results=results_data,
input_functions=input_obj.functions,
)
parserObj.parse(groups_indexes=input_obj.groups_indexes)
results_data = parserObj.main_results
template.form_results(results_data)
def result(self, templates=[], structure="list", **kwargs):
"""Method to get parsing results, supports basic filtering based on
templates' names, results can be formatted and returned to specified
returner.
**Parameters**
* ``templates`` (list or str) names of the templates to return results for
* ``structure`` (str) structure type, valid values - ``list``, ``dictionary`` or ``flat_list``
**kwargs** - can contain any attributes supported by output tags, for instance:
* ``format`` (str) output formatter name - yaml, json, raw, pprint, csv, table, tabulate
* ``functions`` (str) reference output functions to run results through
**Example**::
from ttp import ttp
parser = ttp(data="/os/path/to/data/dir/", template="/os/path/to/template.txt")
parser.parse()
json_result = parser.result(format="json")[0]
yaml_result = parser.result(format="yaml")[0]
print(json_result)
print(yaml_result)
**Returns**
By default template results set to *per_input* and structure set to *list*, returns list such as::
[
[ template_1_input_1_results,
template_1_input_2_results,
...
template_1_input_N_results ],
[ template_2_input_1_results,
template_2_input_2_results,
...
]
If template results set to *per_template* and structure set to *list*, returns list such as::
[
[ template_1_input_1_2...N_joined_results ],
[ template_2_input_1_2...N_joined_results ]
]
If template results set to *per_input* and structure set to *dictionary*, returns dictionary such as::
{
template_1_name: [
input_1_results,
input_2_results,
...
input_N_results
],
template_2_name: [
input_1_results,
input_2_results
],
...
}
If template results set to *per_template* and structure set to *dictionary*,
returns dictionary such as::
{
template_1_name: input_1_2...N_joined_results,
template_2_name: input_1_2...N_joined_results
}
If structure set to *flat_list*, results will be combined across
all templates in a list of dictionaries. For instance, with structure
set to *list* result might look like this::
[[[{'interface': 'Lo0', 'ip': '192.168.0.1', 'mask': '32'},
{'interface': 'Lo1', 'ip': '1.1.1.1', 'mask': '32'}],
[{'interface': 'Lo2', 'ip': '2.2.2.2', 'mask': '32'},
{'interface': 'Lo3', 'ip': '3.3.3.3', 'mask': '32'}]]]
But with structure set to *flat_list* it will be flattened to this::
[{'interface': 'Lo0', 'ip': '192.168.0.1', 'mask': '32'},
{'interface': 'Lo1', 'ip': '1.1.1.1', 'mask': '32'},
{'interface': 'Lo2', 'ip': '2.2.2.2', 'mask': '32'},
{'interface': 'Lo3', 'ip': '3.3.3.3', 'mask': '32'}]
"""
# filter templates to run outputs for:
templates = [templates] if isinstance(templates, str) else templates
templates_obj = self._templates
if templates:
templates_obj = [
template for template in self._templates if template.name in templates
]
# checkif kwargs privided, create outputter if so
if kwargs:
kwargs.setdefault("returner", "self")
outputter = _outputter_class(**kwargs)
# form results structure
if structure.lower() == "list":
if kwargs:
return [
outputter.run(template.results, macro=template.macro)
for template in templates_obj
]
else:
return [template.results for template in templates_obj]
elif structure.lower() == "dictionary":
if kwargs:
return {
template.name: outputter.run(template.results, macro=template.macro)
for template in templates_obj
if template.name
}
else:
return {
template.name: template.results
for template in templates_obj
if template.name
}
elif structure.lower() == "flat_list":
ret = []
for template in templates_obj:
rslt = (
outputter.run(template.results, macro=template.macro)
if kwargs
else template.results
)
if isinstance(rslt, list):
for item in rslt:
if isinstance(item, list):
ret += item
else:
ret.append(item)
else:
ret.append(rslt)
return ret
def get_input_load(self):
"""Method to retrieve input tag text load. Using input ``load`` attribute,
text data can be loaded into python structure using one of the supported
loaders, for instance if text data structured using YAML, YAML
loader can be used to produce python native structure, that structure will
be returned by this method.
Primary use case is to specify parameters within TTP input that can be
used by other applications/scrips.
**Returns**
Dictionary of {"template_name": {"input_name": "input load data"}} across all templates,
where input_name set to input name attribute value, by default it is "Default_Input",
and template_name set to name of the template, by default it is "_root_template_"
.. warning:: inputs load can override one another if combination of template_name
and input_name is not unique.
"""
ret = {}
for template_obj in self._templates:
ret[template_obj.name] = {}
for input_name, input_obj in template_obj.inputs.items():
ret[template_obj.name][input_name] = input_obj.parameters
return ret
def clear_result(self, templates=[]):
"""Method to clear parsing results for templates.
**Parameters**
* ``templates`` (list or str) - name of template(s) to clear results for,
if not provided will clear results for all templates.
"""
# filter templates objects to clear results for
templates = [templates] if isinstance(templates, str) else templates
# clear results
if templates:
[
t_obj.results.clear()
for t_obj in self._templates
if t_obj.name in templates
]
else:
[t_obj.results.clear() for t_obj in self._templates]
"""
==============================================================================
TTP PARSER MULTIPROCESSING WORKER
==============================================================================
"""
class _worker(Process):
"""Class used in multiprocessing to parse data
"""
def __init__(self, task_queue, results_queue, lookups, vars, groups, macro_text):
Process.__init__(self)
self.task_queue = task_queue
self.results_queue = results_queue
self.macro_text = macro_text
self.parserObj = _parser_class(lookups, vars, groups)
def load_functions(self):
lazy_import_functions()
# load macro from text
funcs = {}
# extract macro with all the __builtins__ provided
for macro_text in self.macro_text:
try:
funcs = _ttp_["utils"]["load_python_exec"](
macro_text, builtins=__builtins__
)
_ttp_["macro"].update(funcs)
except SyntaxError as e:
log.error(
"multiprocess_worker.load_functions: syntax error, failed to load macro: \n{},\nError: {}".format(
macro_text, e
)
)
def run(self):
self.load_functions()
# run tasks
while True:
next_task = self.task_queue.get()
# check for dead pill to stop process
if next_task is None:
self.task_queue.task_done()
break
# set parser object parameters
self.parserObj.set_data(
next_task["data"],
main_results={},
input_functions=next_task["input_functions"],
)
# parse and get results
self.parserObj.parse(groups_indexes=next_task["groups_indexes"])
result = self.parserObj.main_results
# put results in the queue and finish task
self.task_queue.task_done()
self.results_queue.put(result)
return
"""
==============================================================================
TTP TEMPLATE CLASS
==============================================================================
"""
class _template_class:
"""Template class to hold template data
"""
def __init__(
self,
template_text,
base_path="",
ttp_vars={},
name="_root_template_",
filter=[],
):
self.PATHCHAR = "." # character to separate path items, like ntp.clock.time, '.' is pathChar here
self.vars = { # dictionary to store template variables
"_vars_to_results_": {}, # to indicate variables and patch where they should be saved in results
# _vars_to_results_ is a dict of {pathN:[var_key1, var_keyN]} data
"_var_functions_": {}, # dictionary to keep variables with functions such as getters
}
self.ttp_vars = ttp_vars # need to save it to pass to child templates
self.vars.update(ttp_vars)
self.outputs = [] # list that contains global outputs
self.groups_outputs = [] # list that contains groups specific outputs
self.groups = []
self.inputs = OrderedDict()
self.lookups = {}
self.templates = []
self.base_path = base_path
self.results = []
self.name = name
self.macro = {} # dictionary of macro name to function mapping
self.results_method = "per_input" # how to join results
self.macro_text = (
[]
) # list to contain macro functions text to transfer into other processes
self.filter = filter # list that contains names of child templates to extract
self.doc = "" # string to contain template doc/description
# load template from string:
self.load_template_xml(template_text)
# update inputs with the groups it has to be run against:
self.update_inputs_with_groups()
# update groups with output references:
self.update_groups_with_outputs()
# separate vars with functions from vars
self.get_var_functions()
if log.isEnabledFor(logging.DEBUG):
self.debug()
[template_obj.debug for template_obj in self.templates]
[input.debug() for input in self.inputs.values()]
[group.debug() for group in self.groups]
[output_obj.debug() for output_obj in self.outputs]
def debug(self):
from pprint import pformat
text = "Template Object {}, Template name '{}' content:\n{}".format(
self, self.name, pformat(vars(self), indent=4)
)
log.debug(text)
def add_lookup(self, data):
"""Method to load lookup data
"""
self.lookups.update(data)
[template.add_lookup(data) for template in self.templates]
def add_vars(self, data):
"""Method to update vars with given data
"""
if isinstance(data, dict):
self.vars.update(data)
[template.add_vars(data) for template in self.templates]
def run_outputs(self):
"""Method to run template outputs with template results
"""
for output in self.outputs:
self.results = output.run(self.results, macro=self.macro)
def form_results(self, result):
"""Method to add results to self.results
"""
# handle _anonymous_ groups results
if "_anonymous_" in result:
if self.results_method == "per_template":
if isinstance(result["_anonymous_"], dict):
self.results = [result.pop("_anonymous_")]
self.results = result.pop("_anonymous_")
else:
self.results.append(result.pop("_anonymous_"))
# handle remaining results
if result:
if isinstance(result, list):
self.results += result
elif self.results_method == "per_template" and isinstance(result, dict):
self.results = result
else:
self.results.append(result)
def get_var_functions(self):
"""optimization method to move variable functions
in separate dictionary
"""
# form _var_functions_ dictionary
for var_name, var_value in self.vars.items():
if not isinstance(var_value, str):
continue
if var_value in _ttp_["variable"]:
self.vars["_var_functions_"][var_name] = var_value
# remove _var_functions_ from self.vars
[self.vars.pop(var_name) for var_name in self.vars["_var_functions_"].keys()]
def update_input(
self, element=None, data=None, input_name="Default_Input", groups=["all"]
):
"""
Method to set data for template input
Args:
data (list): list of (data_name, data_path,) tuples
input_name (str): name of the input
groups (list): list of groups to use for that input
"""
input = _input_class(
element=element,
input_name=input_name,
template_obj=self,
groups=groups,
data=data,
)
if input.name in self.inputs:
self.inputs[input.name].load_data(data=input.data)
self.inputs[input.name].groups_indexes += input.groups_indexes
self.inputs[input.name].groups_indexes = list(
set(self.inputs[input.name].groups_indexes)
)
del input
else:
self.inputs[input.name] = input
def update_inputs_with_groups(self):
"""
Method to update self.inputs group_inputs with group indexes
"""
for G in self.groups:
for input_name in G.inputs:
# add new input
if input_name not in self.inputs:
url = self.base_path + input_name
data_items = _ttp_["utils"]["load_files"](path=url, read=False)
# skip 'text_data' from data as if by the time this method runs
# no input with such name found it means that group input is os path
# string and text_data will be returned by self.utils.load_files
# only if no such path exists, hence text_data does not make sense here
data = [i for i in data_items if "text_data" not in i[0]]
self.update_input(data=data, input_name=input_name)
def update_groups_with_outputs(self):
"""Method to replace output names in group with
output index from self.groups_outputs, also move
output from self.outputs to group specific
self.groups_outputs
"""
for G in self.groups:
for output_index, grp_output in enumerate(G.outputs):
group_output_found = False
# search through global outputs:
for glob_index, glob_output in enumerate(self.outputs):
if glob_output.name == grp_output:
self.groups_outputs.append(self.outputs.pop(glob_index))
G.outputs[output_index] = self.groups_outputs[-1]
group_output_found = True
# go to next output if this output found:
if group_output_found:
continue
# try to find output in group specific outputs:
for index, output in enumerate(self.groups_outputs):
if output.name == grp_output:
G.outputs[output_index] = output
group_output_found = True
# print error message if no output found:
if not group_output_found:
G.outputs.pop(output_index)
log.error(
"template.update_groups_with_outputs: group '{}' - output '{}' not found.".format(
G.name, grp_output
)
)
def get_template_attributes(self, element):
def extract_name(O):
self.name = O
def extract_base_path(O):
self.base_path = O
def extract_results_method(O):
self.results_method = O
def extract_pathchar(O):
self.PATHCHAR = str(O)
opt_funcs = {
"name": extract_name,
"base_path": extract_base_path,
"results": extract_results_method,
"pathchar": extract_pathchar,
}
[
opt_funcs[name](options)
for name, options in element.attrib.items()
if name in opt_funcs
]
def load_template_xml(self, template_text):
def parse_vars(element):
# method to parse vars data
vars = _ttp_["utils"]["load_struct"](element.text, **element.attrib)
if vars:
self.vars.update(vars)
# check if var has name attribute:
if "name" in element.attrib:
path = element.attrib["name"]
[
self.vars["_vars_to_results_"].setdefault(path, []).append(key)
for key in vars.keys()
]
def parse_output(element):
self.outputs.append(_outputter_class(element, template_obj=self))
def parse_group(element, grp_index):
self.groups.append(
_group_class(
element,
top=True,
pathchar=self.PATHCHAR,
vars=self.vars,
grp_index=grp_index,
)
)
def parse_lookup(element):
try:
name = element.attrib["name"]
except KeyError:
log.warning(
"Lookup 'name' attribute not found but required, skipping it"
)
return
lookup_data = _ttp_["utils"]["load_struct"](element.text, **element.attrib)
if lookup_data is None:
return
if element.attrib.get("database", "").lower() == "geoip2":
lookup_data = _ttp_["lookup"]["geoip2_db_loader"](lookup_data)
self.lookups[name] = lookup_data
def parse_template(element, template_index):
# skip child templates that are not in requested children list
if self.filter:
if not element.attrib.get("name", None) in self.filter:
return
self.templates.append(
_template_class(
template_text=ET.tostring(element, encoding="UTF-8"),
base_path=self.base_path,
ttp_vars=self.ttp_vars,
name=str(template_index),
)
)
def parse_macro(element):
funcs = {}
# extract macro with all the __builtins__ provided
try:
funcs = _ttp_["utils"]["load_python_exec"](
element.text, builtins=__builtins__
)
self.macro.update(funcs)
# save macro text to be able to restore macro functions within another process
self.macro_text.append(element.text)
except SyntaxError as e:
log.error(
"template.parse_macro: syntax error, failed to load macro: \n{},\nError: {}".format(
element.text, e
)
)