-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathconfig_parser.py
More file actions
915 lines (816 loc) · 32.9 KB
/
config_parser.py
File metadata and controls
915 lines (816 loc) · 32.9 KB
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
import os
import sys
import tempfile
from datetime import datetime
from pathlib import Path
import yaml
# from yamlinclude import YamlIncludeConstructor
from yaml_include import Constructor
from schema import Schema, Or, And, Use, Optional, SchemaError, Regex
from dhalsim.parser.input_parser import InputParser
class Error(Exception):
"""Base class for exceptions in this module."""
class EmptyConfigError(Error):
"""Raised when the configuration file is empty"""
class MissingValueError(Error):
"""Raised when there is a value missing in a configuration file"""
class InvalidValueError(Error):
"""Raised when there is a invalid value in a configuration file"""
class DuplicateValueError(Error):
"""Raised when there is a duplicate plc value in the plcs section"""
class NoSuchPlc(Error):
"""Raised when an attack targets a PLC that does not exist"""
class NoSuchNode(Error):
"""Raised when an attack targets a node that does not exist"""
class NoSuchTag(Error):
"""Raised when an attack targets a tag the target PLC does not have"""
class NetworkAttackError(Error):
"""Used to raise errors about network attack"""
class TooManyNodes(Error):
"""Raised when there will be too many nodes in the network"""
class SchemaParser:
"""
Class which handles all schema logic.
"""
string_pattern = Regex(r'^[a-zA-Z0-9_]+$',
error="Error in string: '{}', Can only have a-z, A-Z, 0-9, and _")
attack_pattern = Regex(r'^[a-zA-Z0-9_<>+-.]+$',
error="Error in attack name: '{}', "
"Can only have a-z, A-Z, 0-9, and symbols: _ < > + - . (no whitespaces)")
event_pattern = Regex(r'^[a-zA-Z0-9_<>+-.]+$',
error="Error in event name: '{}', "
"Can only have a-z, A-Z, 0-9, and symbols: _ < > + - . (no whitespaces)")
concealment_path = Schema(
str,
Use(Path),
Use(lambda p: p.absolute().parent / p),
Schema(lambda l: Path.is_file, error="'inp_file' could not be found."),
Schema(lambda f: f.suffix == '.csv',
error="Suffix of 'inp_file' should be .inp.")
)
concealment_data = Schema(
Or(
{
'type': And(
str,
Use(str.lower),
'path'
),
'path': concealment_path
},
{
'type': And(
str,
Use(str.lower),
'value'
),
'concealment_value': [{
'tag': And(
str,
string_pattern,
),
Or('value', 'offset', only_one=True,
error="'tags' should have either a 'value' or 'offset' attribute."): Or(float, And(int, Use(float))),
}],
},
{
'type': And(
str,
Use(str.lower),
'payload_replay'
),
'capture_start': And(
int,
Schema(lambda i: i >= 0, error="'capture_start' must be positive."),
),
'capture_end': And(
int,
Schema(lambda i: i >= 0, error="'capture_end' must be positive."),
),
'replay_start': And(
int,
Schema(lambda i: i >= 0, error="'replay_start' must be positive."),
),
},
{
'type': And(
str,
Use(str.lower),
'network_replay'
),
'capture_start': And(
int,
Schema(lambda i: i >= 0, error="'capture_start' must be positive."),
),
'capture_end': And(
int,
Schema(lambda i: i >= 0, error="'capture_end' must be positive."),
),
'replay_start': And(
int,
Schema(lambda i: i >= 0, error="'replay_start' must be positive."),
),
},
)
)
trigger = Schema(
Or(
{
'type': And(
str,
Use(str.lower),
'time'
),
'start': And(
int,
Schema(lambda i: i >= 0, error="'start' must be positive."),
),
'end': And(
int,
Schema(lambda i: i >= 0, error="'end' must be positive."),
),
},
{
'type': And(
str,
Use(str.lower),
Or('below', 'above')
),
'sensor': And(
str,
string_pattern,
),
'value': And(
Or(float, And(int, Use(float))),
),
},
{
'type': And(
str,
Use(str.lower),
'between'
),
'sensor': And(
str,
string_pattern,
),
'lower_value': And(
Or(float, And(int, Use(float))),
),
'upper_value': And(
Or(float, And(int, Use(float))),
),
},
)
)
device_attacks = Schema({
'name': And(
str,
attack_pattern,
),
'trigger': trigger,
'actuator': And(
str,
string_pattern,
),
'command':
Or(
And(
str,
Use(str.lower),
Or('open', 'closed')),
And(
Or(float, And(int, Use(float))))
)
})
network_attacks = Schema(
Or(
{
'type': And(
str,
Use(str.lower),
'naive_mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
Or('value', 'offset', only_one=True,
error="'tags' should have either a 'value' or 'offset' attribute."): Or(float, And(int, Use(float))),
'target': And(
str,
string_pattern
),
Optional('direction', default='source'): And(
str,
Use(str.lower),
Or('source', 'destination'), error="'direction' should be one of the following:"
" 'source' or 'destination'."
)
},
{
'type': And(
str,
Use(str.lower),
'mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'tag': And(
str,
string_pattern,
),
Or('value', 'offset', only_one=True,
error="'tags' should have either a 'value' or 'offset' attribute."): Or(float,
And(int, Use(float))),
},
{
'type': And(
str,
Use(str.lower),
'server_mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'tags': [{
'tag': And(
str,
string_pattern,
),
Or('value', 'offset', only_one=True,
error="'tags' should have either a 'value' or 'offset' attribute."): Or(float, And(int, Use(float))),
}]
},
{
'type': And(
str,
Use(str.lower),
'concealment_mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'tags': [{
'tag': And(
str,
string_pattern,
),
Or('value', 'offset', only_one=True,
error="'tags' should have either a 'value' or 'offset' attribute."): Or(float, And(int, Use(float))),
}],
'concealment_data': concealment_data
},
{
'type': And(
str,
Use(str.lower),
'unconstrained_blackbox_concealment_mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
Optional('persistent', default='True'): And(
str,
Use(str.lower),
Or(True, False), error="'Persistent' should be one of the following: 'True' or 'False'."
),
'trigger': trigger,
},
{
'type': And(
str,
Use(str.lower),
'replay_mitm',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'capture_start': And(
int,
Schema(lambda i: i >= 0, error="'capture_start' must be positive."),
),
'capture_end': And(
int,
Schema(lambda i: i >= 0, error="'capture_start' must be positive."),
),
'replay_start': And(
int,
Schema(lambda i: i >= 0, error="'capture_start' must be positive."),
),
},
{
'type': And(
str,
Use(str.lower),
'simple_dos',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
Optional('direction', default='source'): And(
str,
Use(str.lower),
Or('source', 'destination'), error="'direction' should be one of the following:"
" 'source' or 'destination'."
)
}
)
)
network_events = Schema(
Or(
{
'type': And(
str,
Use(str.lower),
'packet_loss',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'value': And(
Or(float, And(int, Use(float)))
)
},
{
'type': And(
str,
Use(str.lower),
'network_delay',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'value': And(
Or(float, And(int, Use(float)))
)
},
{
'type': And(
str,
Use(str.lower),
'network_delay_loss',
),
'name': And(
str,
string_pattern,
Schema(lambda name: 1 <= len(name) <= 20,
error="Length of name must be between 1 and 20, '{}' has invalid length")
),
'trigger': trigger,
'target': And(
str,
string_pattern
),
'loss_value': And(
Or(float, And(int, Use(float)))
),
'delay_value': And(
Or(float, And(int, Use(float)))
)
}
)
)
@staticmethod
def path_schema(data: dict, config_path: Path) -> dict:
"""
For all the values that need to be a path, this function converts them to absolute paths,
checks if they exists, and checks the suffix if applicable.
:param data: data from the config file
:type data: dict
:param config_path: That to the config file
:type config_path:
:return: the config data, but with existing absolute path objects
:rtype: dict
"""
return Schema(
And(
{
'inp_file': And(
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
Schema(lambda l: Path.is_file, error="'inp_file' could not be found."),
Schema(lambda f: f.suffix == '.inp',
error="Suffix of 'inp_file' should be .inp.")),
Optional('output_path', default=config_path.absolute().parent / 'output'): And(
Use(str, error="'output_path' should be a string."),
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
),
Optional('initial_tank_data'): And(
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
Schema(lambda l: Path.is_file, error="'initial_tank_data' could not be found."),
Schema(lambda f: f.suffix == '.csv',
error="Suffix of initial_tank_data should be .csv")),
Optional('demand_patterns'): And(
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
Schema(lambda l: Path.exists, error="'demand_patterns' path does not exist."),
Or(
Path.is_dir,
Schema(lambda f: f.suffix == '.csv',
error="Suffix of demand_patterns should be .csv"))),
Optional('network_loss_data'): And(
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
Schema(lambda l: Path.is_file, error="'network_loss_data' could not be found."),
Schema(lambda f: f.suffix == '.csv',
error="Suffix of network_loss_data should be .csv")),
Optional('network_delay_data'): And(
Use(Path),
Use(lambda p: config_path.absolute().parent / p),
Schema(lambda l: Path.is_file, error="'network_delay_data' could not be found."),
Schema(lambda f: f.suffix == '.csv',
error="Suffix of network_delay_data should be .csv")),
str: object
}
)
).validate(data)
@staticmethod
def validate_schema(data: dict) -> dict:
"""
Apply a schema to the data. This schema make sure that every reuired parameter is given.
It also fills in default values for missing parameters.
It will test for types of parameters as well.
Besides that, it converts some strings to lower case, like those of :code:'log_level'.
:param data: data from the config file
:type data: dict
:return: A verified version of the data of the config file
:rtype: dict
"""
plc_schema = Schema([{
'name': And(
str,
SchemaParser.string_pattern,
Schema(lambda name: 1 <= len(name) <= 10,
error="Length of name must be between 1 and 10, '{}' has invalid length")
),
Optional('sensors'): [And(
str,
SchemaParser.string_pattern
)],
Optional('actuators'): [And(
str,
SchemaParser.string_pattern
)]
}])
config_schema = Schema({
'plcs': plc_schema,
'inp_file': Path,
Optional('network_topology_type', default='simple'): And(
str,
Use(str.lower),
Or('complex', 'simple')),
'output_path': Path,
Optional('iterations'): And(
int,
Schema(lambda i: i > 0, error="'iterations' must be positive.")),
Optional('mininet_cli', default=False): bool,
Optional('log_level', default='info'): And(
str,
Use(str.lower),
Or('debug', 'info', 'warning', 'error', 'critical', error="'log_level' should be "
"one of the following: "
"'debug', 'info', 'warning', "
"'error' or 'critical'.")),
Optional('demand', default='pdd'): And(
str,
Use(str.lower),
Or('pdd', 'dd'), error="'demand' should be one of the following: 'pdd' or 'dd'."),
Optional('noise_scale', default=0.0): And(
float,
Schema(lambda i: i >= 0, error="'noise_scale' must be positive.")),
Optional('attacks'): {
Optional('device_attacks'): [SchemaParser.device_attacks],
Optional('network_attacks'): [SchemaParser.network_attacks],
},
Optional('events'): {
Optional('network_events'): [SchemaParser.network_events],
},
Optional('batch_simulations'): And(
int,
Schema(lambda i: i > 0, error="'batch_simulations' must be positive.")),
Optional('saving_interval'): And(
int,
Schema(lambda i: i > 0, error="'saving_interval' must be positive.")),
Optional('initial_tank_data'): Path,
Optional('demand_patterns'): Path,
Optional('network_loss_data'): Path,
Optional('network_delay_data'): Path,
Optional('simulator', default='wntr'): And(
str,
Use(str.lower),
Or('wntr', 'epynet')),
})
return config_schema.validate(data)
class ConfigParser:
"""
Class handling the parsing of the input config data.
:param config_path: The path to the config file of the experiment in yaml format
:type config_path: Path
"""
def __init__(self, config_path: Path):
self.batch_index = None
self.yaml_path = None
self.db_path = None
self.config_path = config_path.absolute()
# YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader,
# base_dir=config_path.absolute().parent)
yaml.add_constructor("!include", Constructor(base_dir=config_path.absolute().parent), FullLoader)
try:
self.data = self.apply_schema(self.config_path)
except SchemaError as exc:
sys.exit(exc.code)
try:
self.do_checks(self.data)
except Error as exc:
sys.exit(exc)
self.batch_mode = 'batch_simulations' in self.data
if self.batch_mode:
self.batch_simulations = self.data['batch_simulations']
@staticmethod
def do_checks(data: dict):
"""
Perform various checks on the data provided
:param data: The data to check
"""
ConfigParser.not_too_many_nodes(data)
@staticmethod
def not_too_many_nodes(data: dict):
"""
Check if there are not more then 250 plcs and network attacks.
This would cause trouble with assigning IP and MAC addresses.
:param data: the data to check on
:raise TooManyNodes: When there are more then 250 nodes in the network
"""
raise_message = "There are too many nodes in the network. Only 250 nodes are supported."
if 'plcs' in data:
n_plcs = len(data["plcs"])
if n_plcs > 250:
raise TooManyNodes(raise_message)
if 'attacks' in data and 'network_attacks' in data['attacks'] and \
n_plcs + len(data['attacks']['network_attacks']) > 250:
raise TooManyNodes(raise_message)
elif 'attacks' in data and 'network_attacks' in data['attacks'] and \
len(data['attacks']['network_attacks']) > 250:
raise TooManyNodes(raise_message)
@staticmethod
def apply_schema(config_path: Path) -> dict:
"""
Load the yaml data from the config file, and apply the schema.
:param config_path: The to the config file
:type config_path: Path
:return: A verified version of the data of the config file
:rtype: dict
"""
data = ConfigParser.load_yaml(config_path)
data = SchemaParser.path_schema(data, config_path)
return SchemaParser.validate_schema(data)
@staticmethod
def load_yaml(path: Path) -> dict:
"""
Uses :code:'pyyaml' and :code'pyyaml-include' to read in a yaml file.
This means you can use '!include' to include yaml files in other yaml files.
:param path: path to the yaml file to be loaded.
:type path: Path
:return: a dict representing the yaml file
:rtype: dict
"""
try:
with path.open(mode='r') as file:
data = yaml.load(file, Loader=yaml.FullLoader)
return data
except FileNotFoundError as exc:
sys.exit(f"File not found: {exc.filename}")
@property
def output_path(self):
"""
Property for the path to the output folder.
''output'' by default.
:return: absolute path to the output folder
:rtype: Path
"""
path = self.data['output_path']
if self.batch_mode:
path /= 'batch_' + str(self.batch_index)
return path
@property
def demand_patterns(self):
"""
Function that returns path to demand pattern csv
:return: absolute path to the demand pattern csv
:rtype: Path
"""
path = self.data.get('demand_patterns')
# If running in batch mode, then have to use batch index in name
if self.batch_mode:
path /= str(self.batch_index) + '.csv'
if not path.is_file():
raise FileNotFoundError(str(path) + " is not a file.")
return path
def generate_device_attacks(self, yaml_data):
"""
This function will add device attacks to the appropriate PLCs in the intermediate yaml
:param yaml_data: The YAML data without the device attacks
"""
if 'attacks' in self.data and 'device_attacks' in self.data['attacks']:
for device_attack in self.data['attacks']['device_attacks']:
for plc in yaml_data['plcs']:
if device_attack['actuator'] in plc['actuators']:
if 'attacks' not in plc.keys():
plc['attacks'] = []
plc['attacks'].append(device_attack)
break
return yaml_data
def generate_network_attacks(self):
"""
This function will add network attacks to the appropriate PLCs in the intermediate yaml
:param network_attacks: The YAML data of the network attacks
"""
if 'attacks' in self.data and 'network_attacks' in self.data['attacks']:
network_attacks = self.data['attacks']["network_attacks"]
for network_attack in network_attacks:
# Check existence and validity of target PLC
# This is the only valid target of this attack
if network_attack['type'] == 'unconstrained_blackbox_concealment_mitm':
target = 'scada'
else:
target = network_attack['target']
# Network attacks to SCADA do not need a target plc
if target.lower() == 'scada':
continue
target_plc = None
for plc in self.data.get("plcs"):
if plc['name'] == target:
target_plc = plc
break
if not target_plc:
raise NoSuchPlc("PLC {plc} does not exists".format(plc=target))
if network_attack['type'] == 'server_mitm':
# Check existence of tags on target PLC
tags = []
for tag in network_attack['tags']:
tags.append(tag['tag'])
if not set(tags).issubset(set(target_plc['actuators'] + target_plc['sensors'])):
raise NoSuchTag(
f"PLC {target_plc['name']} does not have all the tags specified.")
#todo: Checks for concealment_mitm
return network_attacks
return []
def generate_network_events(self):
"""
This function will add network events in the intermediate yaml
"""
if 'events' in self.data and 'network_events' in self.data['events']:
network_events = self.data['events']['network_events']
for network_event in network_events:
# Check the existence and validity of target node
target = network_event['target']
if target == 'scada':
continue
target_node = None
for node in self.data.get('plcs'):
if node['name'] == target:
target_node = target
break
if not target_node:
raise NoSuchNode("Node {node} does not exists".format(node=target))
return network_events
return []
def generate_temporary_dirs(self):
"""Generates the temporary directory and yaml/db paths"""
# Create temp directory and intermediate yaml files in /tmp/
temp_directory = tempfile.mkdtemp(prefix='dhalsim_')
# Change read permissions in tempdir
os.chmod(temp_directory, 0o775)
self.yaml_path = Path(temp_directory + '/intermediate.yaml')
self.db_path = temp_directory + '/dhalsim.sqlite'
def generate_intermediate_yaml(self):
"""Writes the intermediate.yaml file to include all options specified in the config, the plc's and their
data, and all valves/pumps/tanks etc.
:return: the path to the yaml file
:rtype: Path
"""
self.generate_temporary_dirs()
yaml_data = {}
yaml_data['config_path'] = str(self.config_path)
# Begin with PLC data specified in plcs section
yaml_data['plcs'] = self.data['plcs']
# Add path and database information
yaml_data['inp_file'] = str(self.data['inp_file'])
yaml_data['output_path'] = str(self.output_path)
yaml_data['db_path'] = self.db_path
yaml_data['network_topology_type'] = self.data['network_topology_type']
# Simulator to be used, it can be EPANET WNTR or EPANET epynet
yaml_data['simulator'] = self.data['simulator']
# Add batch mode parameters
if self.batch_mode:
yaml_data['batch_index'] = self.batch_index
yaml_data['batch_simulations'] = self.data['batch_simulations']
# Initial physical values
# If the user has not configured initial_tank_data, yaml_data will not have this key
if 'initial_tank_data' in self.data:
yaml_data['initial_tank_data'] = str(self.data['initial_tank_data'])
if 'demand_patterns' in self.data:
yaml_data['demand_patterns_data'] = str(self.demand_patterns)
# Add network loss parameters
if 'network_loss_data' in self.data:
yaml_data['network_loss_data'] = str(self.data['network_loss_data'])
# Add network delay parameters
if 'network_delay_data' in self.data:
yaml_data['network_delay_data'] = str(self.data['network_delay_data'])
# Mininet cli parameter
yaml_data['mininet_cli'] = self.data['mininet_cli']
# Write intermittent saving interval to intermediate yaml
if 'saving_interval' in self.data:
yaml_data['saving_interval'] = self.data['saving_interval']
# Write gaussian noise scale value to intermediate yaml
if 'noise_scale' in self.data:
yaml_data['noise_scale'] = self.data['noise_scale']
else:
yaml_data['noise_scale'] = 0
# Demand
yaml_data['demand'] = self.data['demand']
# Note: if iterations not present then default value will be written in InputParser
if 'iterations' in self.data:
yaml_data['iterations'] = self.data['iterations']
# Log level
yaml_data['log_level'] = self.data['log_level']
yaml_data['start_time'] = datetime.now()
# Write values from INP file into yaml file (controls, tanks/valves/initial values, etc.)
# toDo: test this - preparing DHALSIM to be used with other simulators
if self.data['simulator'] == 'wntr' or self.data['simulator'] == 'epynet':
yaml_data = InputParser(yaml_data).write()
# Parse the device attacks from the config file
yaml_data = self.generate_device_attacks(yaml_data)
yaml_data["network_attacks"] = self.generate_network_attacks()
# Parse network events from the config file
yaml_data["network_events"] = self.generate_network_events()
# Write data to yaml file
with self.yaml_path.open(mode='w') as intermediate_yaml:
yaml.safe_dump(yaml_data, intermediate_yaml)
return self.yaml_path