-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualize_network.py
1598 lines (1302 loc) · 62.6 KB
/
visualize_network.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
import boto3
import xml.etree.cElementTree as ET
import math
import argparse
import os
import errno
#update this if deploying to lambda
LAMBDA_INVOCATION = False
# command line arguments
parser = argparse.ArgumentParser(description='VPC Network Visualizer')
# positional, required args
parser.add_argument('profile', help='aws profile')
parser.add_argument('region', help='aws region')
parser.add_argument('vpc', help='vpc id')
# value-based args
parser.add_argument('--outdir', dest='directory', help='output save directory', default="")
parser.add_argument('--stroke', dest='stroke', help='line stroke width', default=3, type=int)
parser.add_argument('--text', dest='line_height', help='text line height', default=20, type=int)
parser.add_argument('--subcols', dest='sub_cols', help='subnet alignment columns', default=3, type=int)
parser.add_argument('--peercols', dest='peer_cols', help='peer VPC alignment columns', default=1, type=int)
parser.add_argument('--fontl', dest='font_large', help='large font size', default=16, type=int)
# true/false args
parser.add_argument('--all', '-a', dest='all_resources', action='store_true', help='show non associated resources')
parser.add_argument('--linelabels', '-l', dest='labels', action='store_true', help='add connection labels')
parser.add_argument('--rtconnections', '-c', dest='rt_connections', action='store_true', help='add route table connections')
class DefaultLambdaNamespace:
"""Class that returns argparse-like default argument dict"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def get_configuration(lambda_invocation):
"""return arguments and authentication kwargs for given run configuration"""
kwargs = {}
if lambda_invocation:
return (DefaultLambdaNamespace(all_resources=False,
directory='',
font_large=16,
labels=False,
line_height=20,
peer_cols=1,
profile='NONE',
region='NONE',
rt_connections=False,
stroke=3,
sub_cols=3,
vpc='NONE'), kwargs)
else:
args = parser.parse_args()
kwargs['profile_name'] = args.profile
kwargs['region_name'] = args.region
return (args, kwargs)
# parse cmd line args
(args, kwargs) = get_configuration(LAMBDA_INVOCATION)
SESSION = boto3.Session(**kwargs)
# draw.io specific resource shapes
ROUTE53_SHAPE = "mxgraph.aws3.route_53"
ROUTE_TABLE_SHAPE = "mxgraph.aws3.route_table"
INTERNET_GATEWAY_SHAPE = "mxgraph.aws3.internet_gateway"
ENI_SHAPE = "mxgraph.aws3.elastic_network_interface"
PEERING_SHAPE = "mxgraph.aws3.vpc_peering"
NAT_GATEWAY_SHAPE = "mxgraph.aws3.vpc_nat_gateway"
NACL_SHAPE = "mxgraph.aws3.network_access_controllist"
VPC_SHAPE = "mxgraph.aws3.virtual_private_cloud"
SUBNET_SHAPE = "mxgraph.aws3.permissions"
FLOW_LOGS_SHAPE = "mxgraph.aws3.flow_logs"
ENDPTS_SHAPE = "mxgraph.aws3.endpoints"
VPN_SHAPE = "mxgraph.aws3.vpn_gateway"
VPN_CONN_SHAPE = "mxgraph.aws3.vpn_connection"
GENERIC_SERVER_SHAPE = "mxgraph.aws3.traditional_server"
DIRECT_CONNECT_SHAPE = "mxgraph.aws3.direct_connect"
AWS_CLOUD_SHAPE = "mxgraph.aws3.cloud"
# colors
BLACK = "#000000"
GREEN = "#00ff00"
BLUE = "#0000ff"
RED = "#ff0000"
# aws icon specific colors
ICON_ORANGE = "#F58536"
AWS_BORDER_ORANGE = "#F59D56"
ICON_GOLD = "#D9A741"
# draw.io diagram dimensions
DIAGRAM_WIDTH = 4000
DIAGRAM_HEIGHT = 4000
# global padding dimension
PADDING = 60
# resource spacing
RESOURCE_DISTRIBUTION = PADDING * 3
# subnet minimum dimensions (if not associated with nat)
SUBNET_MIN_W = 340
SUBNET_MIN_H = 80
# vpc minimum dimensions (used to show peered vpcs)
VPC_MIN_W = 200
VPC_MIN_H = 120
# used for stacking peered vpc containers next to main diagram
VPC_PEER_COLS = args.peer_cols
# subnets are aligned according to associated nacl
SUBNET_ALIGNMENT_COLS = args.sub_cols
# space for route table listings and acl listings
VPC_GUTTER_DIM = 700
# add association labels to connections
CONNECTION_LABELS = args.labels
# diagram list column width
DIAGRAM_COL_WIDTH_SMALL = 70
DIAGRAM_COL_WIDTH_NORMAL = 120
DIAGRAM_COL_WIDTH_OVERSIZED = 210
# diagram line spacing
DIAGRAM_LINE_HEIGHT = args.line_height
# diagram list header spacing
DIAGRAM_HEADER_SPACING = 50
# small resource text offset for container
SMALL_RESOURCE_TEXT_OFFSET = 20
#connection weight
STROKE_WIDTH = args.stroke
# connections rounded: 0 for false, 1 for true
CONNECTIONS_ROUNDED = 1
# line bundle spacing
LINE_BUNDLE_SPACING = 10
# font sizes
FONT_SIZE_NORMAL = 12
FONT_SIZE_LARGE = args.font_large
# placeholders for connection organization
X_DIRECTION = 1
Y_DIRECTION = 0
# add route table connections to external resources (crowds diagram)
ADD_ROUTE_TABLE_CONNECTIONS = args.rt_connections
# only add route tables or nacls if they are associated with a subnet
OMIT_NON_ASSOCIATED_RESOURCES = not args.all_resources
# when determining a resource's human-friendly name, try this if 'Name' not present
SECOND_NAME_FIELD = 'aws:cloudformation:logical-id'
# used as a placeholder for adding horizontal lines to lists
HORIZONTAL_LINE = "horiz_line"
# used as an organization placeholder
NO_AZ = 'no_az'
# custom connection entries
CONNECTION_ENTRY_NONE = ""
CONNECTION_ENTRY_RIGHT = "entryX=1;entryY=0.5;"
CONNECTION_ENTRY_LEFT = "entryX=0;entryY=0.5;"
def create_xml_doc():
return ET.Element("mxGraphModel",
dx="950",
dy="464",
grid="1",
gridSize="10",
guides="1",
tooltips="1",
connect="1",
arrows="1",
fold="1",
page="1",
pageScale="1",
pageWidth="{}".format(DIAGRAM_WIDTH),
pageHeight="{}".format(DIAGRAM_HEIGHT),
background="#ffffff",
math="0",
shadow="0")
def get_account_number():
return SESSION.client('sts').get_caller_identity().get('Account')
def make_save_location(dir):
if dir:
try:
os.makedirs(dir)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(dir):
pass
else:
raise
return os.path.join(dir, '')
def if_in(resource, *keys):
#check for keys in map and return the value of the first one found
for k in keys:
if k in resource:
return resource[k]
return ""
def insert_text(xml_root, text, x, y, dx=15, dy=10, font_color=BLACK, font_size=FONT_SIZE_NORMAL):
# add a text element
newElement = ET.SubElement(xml_root, "mxCell",
id="text-{}_{}".format(text, y),
value="<font style='font-size: {}px'; color='{}'>{}</font>".format(font_size, font_color, text),
vertex="1",
style="text;html=1;labelBackgroundColor=#ffffff",
parent="1")
ET.SubElement(newElement, "mxGeometry",
x="{}".format(x + dx),
y="{}".format(y + dy),
width="50",
height="30").set('as','geometry')
def name_from_tags(resource):
if 'Tags' in resource:
for t in resource['Tags']:
if t['Key'] == 'Name':
return t['Value']
for t_other in resource['Tags']:
if t_other['Key'] == SECOND_NAME_FIELD:
return t_other['Value']
return ""
else:
return ""
def insert_line(xml_root, x1, y1, x2, y2):
newElement = ET.SubElement(xml_root, "mxCell",
id="line_{},{}_{},{}".format(x1, y1, x2, y2),
value="",
edge="1",
style="shape=link;html=1;shadow=0;startArrow=diamondThin;startFill=1;endArrow=async;endFill=1;jettySize=auto;orthogonalLoop=1;strokeColor=#000000;strokeWidth=1;",
parent="1")
geometry = ET.SubElement(newElement, "mxGeometry",
relative="1",
width="50",
height="50")
geometry.set('as','geometry')
ET.SubElement(geometry, "mxPoint",
x="{}".format(x1),
y="{}".format(y1)).set('as','sourcePoint')
ET.SubElement(geometry, "mxPoint",
x="{}".format(x2),
y="{}".format(y2)).set('as','targetPoint')
class RouteGroup:
def __init__(self, start_x_bundle, start_y_bundle, starting_direction, bundle_spacing=LINE_BUNDLE_SPACING, additional_break=-1):
"""RouteGroup takes a x coordinate to start stacking connections and a y coordinate to start stacking connections,
either of these may be omitted by passing -1. A RouteGroup object generates routes of (x,y) pairs and maintains the
grouping by incrementing these stacking coordinates by the provided bundle spacing"""
self.bundle_spacing = bundle_spacing
self.current_x = start_x_bundle
self.current_y = start_y_bundle
self.starting_direction = starting_direction
self.additional_break = additional_break
if starting_direction != X_DIRECTION and starting_direction != Y_DIRECTION:
# complex route will return as [] and not be used when rendering connections
print("WARNING: bad starting direction {} for route group generator. \n(Use X_DIRECTION or Y_DIRECTION)".format(starting_direction))
def get_next_route(self, origin_x, origin_y):
complex_route = []
if self.starting_direction == X_DIRECTION:
complex_route.append((self.current_x, origin_y))
if self.current_y != -1:
complex_route.append((self.current_x, self.current_y))
if self.additional_break != -1:
complex_route.append((self.additional_break, self.current_y))
elif self.starting_direction == Y_DIRECTION:
complex_route.append((origin_x, self.current_y))
if self.current_x != -1:
complex_route.append((self.current_x, self.current_y))
if self.additional_break != -1:
complex_route.append((self.current_x, self.additional_break))
if self.current_x != -1:
self.current_x += self.bundle_spacing
if self.current_y != -1:
self.current_y -= self.bundle_spacing
if self.additional_break != -1:
self.additional_break -= self.bundle_spacing
return complex_route
class DiagramContainer:
"""Generic diagram container"""
def __init__(self, name, id, loc_x, loc_y, width, height, shape):
self.name = name
self.id = id
self.loc_x = loc_x
self.loc_y = loc_y
self.width = width
self.height = height
self.shape = shape
self.container_id = "{}_container".format(self.id)
def get_container_id(self):
return self.container_id
def render_xml_connection(self, xml_root, other_id, text="", color=BLACK, stroke_width=STROKE_WIDTH, complex_route=[], connection_entry=CONNECTION_ENTRY_NONE):
if CONNECTION_LABELS:
label = text
else:
label = ""
newElement = ET.SubElement(xml_root, "mxCell",
id="connect{}to{}".format(self.id, other_id),
style="edgeStyle=orthogonalEdgeStyle;rounded={};endArrow=async;strokeColor={};fillColor={};html=1;{}jettySize=auto;orthogonalLoop=1;strokeWidth={};".format(CONNECTIONS_ROUNDED,
color, color, connection_entry, stroke_width),
edge="1",
value=label,
parent="1",
source="{}".format(self.container_id),
target="{}".format(other_id))
geometry = ET.SubElement(newElement, "mxGeometry", relative="1")
geometry.set('as','geometry')
if complex_route:
array = ET.SubElement(geometry, "Array")
array.set('as','points')
for (x,y) in complex_route:
ET.SubElement(array, "mxPoint", x="{}".format(x), y="{}".format(y))
def render_xml(self, xml_root, icon_width=30, icon_height=36, icon_dx=20, icon_dy=-20, icon_color=ICON_ORANGE, arc_size=10):
newElement_container = ET.SubElement(xml_root, "mxCell",
id=self.container_id,
value="",
style="rounded=1;arcSize={};dashed=0;strokeColor=#000000;fillColor=none;gradientColor=none;strokeWidth=2;".format(arc_size),
vertex="1",
parent="1")
ET.SubElement(newElement_container, "mxGeometry",
x="{}".format(self.loc_x),
y="{}".format(self.loc_y),
width="{}".format(self.width),
height="{}".format(self.height)).set('as','geometry')
newElement = ET.SubElement(xml_root, "mxCell",
id=self.id,
value="",
style="dashed=0;html=1;shape={};fillColor={};gradientColor=none;dashed=0;".format(self.shape, icon_color),
vertex="1",
parent="1")
ET.SubElement(newElement, "mxGeometry",
x="{}".format(self.loc_x + icon_dx),
y="{}".format(self.loc_y + icon_dy),
width="{}".format(icon_width),
height="{}".format(icon_height)).set('as','geometry')
class DiagramObject:
"""Generic diagram object"""
def __init__(self, name, id, loc_x, loc_y, shape, parent="1"):
self.name = name
self.id = id
self.loc_x = loc_x
self.loc_y = loc_y
self.shape_id = shape
self.parent = parent
def render_xml(self, xml_root, width=50, height=50, icon_color=ICON_ORANGE):
newElement = ET.SubElement(xml_root, "mxCell",
id=self.id,
value="",
style="outlineConnect=0;dashed=0;verticalLabelPosition=bottom;verticalAlign=top;align=center;html=1;shape={};fillColor={};gradientColor=none;".format(self.shape_id, icon_color),
vertex="1",
parent="{}".format(self.parent))
ET.SubElement(newElement, "mxGeometry",
x="{}".format(self.loc_x),
y="{}".format(self.loc_y),
width="{}".format(width),
height="{}".format(height)).set('as','geometry')
def get_id(self):
return self.id
def render_xml_connection(self, xml_root, other_id, text="", color=BLACK, stroke_width=STROKE_WIDTH, complex_route=[], connection_entry=CONNECTION_ENTRY_NONE):
if CONNECTION_LABELS:
label = text
else:
label = ""
newElement = ET.SubElement(xml_root, "mxCell",
id="connect{}to{}".format(self.id, other_id),
style="edgeStyle=orthogonalEdgeStyle;rounded={};endArrow=async;strokeColor={};fillColor={};html=1;{}jettySize=auto;orthogonalLoop=1;strokeWidth={};".format(CONNECTIONS_ROUNDED,
color, color, connection_entry, stroke_width),
edge="1",
value=label,
parent="1",
source="{}".format(self.id),
target="{}".format(other_id))
geometry = ET.SubElement(newElement, "mxGeometry", relative="1")
geometry.set('as','geometry')
if complex_route:
array = ET.SubElement(geometry, "Array")
array.set('as','points')
for (x,y) in complex_route:
ET.SubElement(array, "mxPoint", x="{}".format(x), y="{}".format(y))
class DiagramList:
def __init__(self, title, id, list, fields, col_widths):
self.title = title
self.id = id
self.list = list
self.fields = fields
self.lane_header_height = DIAGRAM_LINE_HEIGHT
self.line_height = DIAGRAM_LINE_HEIGHT
self.col_widths = col_widths
self.header_spacing = DIAGRAM_HEADER_SPACING
def create_lane(self, xml_root, x, width, height, section_title):
"""Create a column in the table"""
lane_title = "{}_{}".format(self.title, section_title)
newElement = ET.SubElement(xml_root, "mxCell",
id=lane_title,
value=section_title,
style="swimlane;html=1;startSize=20;",
vertex="1",
parent="{}".format(self.id))
ET.SubElement(newElement, "mxGeometry",
x="{}".format(x),
y="{}".format(self.lane_header_height),
width="{}".format(width),
height="{}".format(height)).set('as','geometry')
return lane_title
def add_entry(self, xml_root, lane, value, y_offset, width):
"""add an entry to a table"""
newElement = ET.SubElement(xml_root, "mxCell",
id="{}_{}_{}".format(lane, value, y_offset),
value="{}".format(value),
style="text;strokeColor=none;fillColor=none;align=left;verticalAlign=top;spacingLeft=4;spacingRight=4;overflow=hidden;rotatable=0;points=[[0,0.5],[1,0.5]];portConstraint=eastwest;",
vertex="1",
parent="{}".format(lane))
ET.SubElement(newElement, "mxGeometry",
x="5",
y="{}".format(y_offset),
width="{}".format(width - 10),
height="26").set('as','geometry')
def render_xml_connection(self, xml_root, other_id, text="", color=BLACK, stroke_width=STROKE_WIDTH, complex_route=[]):
if CONNECTION_LABELS:
label = text
else:
label = ""
newElement = ET.SubElement(xml_root, "mxCell",
id="connect{}to{}".format(self.id, other_id),
style="edgeStyle=orthogonalEdgeStyle;rounded={};endArrow=async;strokeColor={};fillColor={};html=1;jettySize=auto;orthogonalLoop=1;strokeWidth={};".format(CONNECTIONS_ROUNDED,
color, color, stroke_width),
edge="1",
value=label,
parent="1",
source="{}".format(self.id),
target="{}".format(other_id))
geometry = ET.SubElement(newElement, "mxGeometry", relative="1")
geometry.set('as','geometry')
if complex_route:
array = ET.SubElement(geometry, "Array")
array.set('as','points')
for (x,y) in complex_route:
ET.SubElement(array, "mxPoint", x="{}".format(x), y="{}".format(y))
def render_xml(self, xml_root, x, y):
width = 0
for col_width in self.col_widths:
width += col_width
height = self.header_spacing + (self.line_height * len(self.list))
newElement = ET.SubElement(xml_root, "mxCell",
id="{}".format(self.id),
value="{}".format(self.title),
style="swimlane;html=1;childLayout=stackLayout;resizeParent=1;resizeParentMax=0;startSize=20;",
vertex="1",
parent="1")
ET.SubElement(newElement, "mxGeometry",
x="{}".format(x),
y="{}".format(y),
width="{}".format(width),
height="{}".format(height)).set('as','geometry')
lanes = []
lane_x = 0
for f in range(len(self.fields)):
lanes.append(self.create_lane(xml_root, lane_x, self.col_widths[f], height - self.lane_header_height, self.fields[f]))
lane_x += self.col_widths[f]
y_offset = self.line_height
for entry in self.list:
# check for horizontal line placeholder
if entry == HORIZONTAL_LINE:
horiz_line_y = y + y_offset + int(self.header_spacing / 2) + 5
insert_line(xml_root, x, horiz_line_y,
x + width, horiz_line_y)
else:
for i in range(len(entry)):
self.add_entry(xml_root, lanes[i], entry[i], y_offset, self.col_widths[i])
y_offset += self.line_height
return height
class DirectConnectResource:
def __init__(self, id, name):
self.id = id
self.name = name
self.associations = []
def add_association(self, assoc):
self.associations.append(assoc)
def render_xml(self, xml_root, x, y, padding=PADDING):
dc_object = DiagramObject(self.id, self.id, x, y, DIRECT_CONNECT_SHAPE)
dc_object.render_xml(xml_root, height=60)
insert_text(xml_root, "{}".format(self.name), x, y, dx=50, dy=0)
insert_text(xml_root, "{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=50, dy=0)
# add connections to registered associations
for assoc in self.associations:
dc_object.render_xml_connection(xml_root, "{}".format(assoc), color=RED)
class NAclResource:
def __init__(self, id, name):
self.id = id
self.col_suggestion = 0
self.rules_ingress = []
self.rules_egress = []
self.name = name
self.x = 0
def get_id(self):
return self.id
def add_rule(self, rule_number, protocol, egress, cidr_block, rule_action):
if egress:
self.rules_egress.append((int(rule_number), protocol, egress, cidr_block, rule_action))
else:
self.rules_ingress.append((int(rule_number), protocol, egress, cidr_block, rule_action))
def add_col_suggestion(self, suggestion):
self.col_suggestion = suggestion
def get_col_suggestion(self):
return self.col_suggestion
def get_x(self):
return self.x
def render_xml(self, xml_root, x, y, route_generator, padding=PADDING):
self.x = x
nacl_object = DiagramObject(self.id, self.id, x, y, NACL_SHAPE)
nacl_object.render_xml(xml_root)
insert_text(xml_root, "{}".format(self.id), x, y, dx=-30, dy=50)
sorted_rules_egress = sorted(self.rules_egress, key=lambda rule: rule[0])
sorted_rules_ingress = sorted(self.rules_ingress, key=lambda rule: rule[0])
#add horizontal line separator
sorted_rules_egress.append(HORIZONTAL_LINE)
sorted_rules_egress.extend(sorted_rules_ingress)
fields = ["Rule Number", "Protocol", "Egress", "Cidr Block", "Rule Action"]
widths = [DIAGRAM_COL_WIDTH_NORMAL, DIAGRAM_COL_WIDTH_SMALL, DIAGRAM_COL_WIDTH_SMALL,
DIAGRAM_COL_WIDTH_OVERSIZED, DIAGRAM_COL_WIDTH_SMALL]
if len(sorted_rules_egress) > 0:
label = "{} | {}".format(self.name, self.id)
if self.name == "":
label = self.id
DiagramList("{}".format(label),
"{}_list".format(self.id),
sorted_rules_egress,
fields,
widths).render_xml(xml_root, int((x - VPC_GUTTER_DIM) * 3.5) - int(1.5 * VPC_GUTTER_DIM), padding)
nacl_object.render_xml_connection(xml_root, "{}_list".format(self.id), color=RED,
complex_route=route_generator.get_next_route(x + 30, y))
class NgResource:
def __init__(self, id, subnet_id, name):
self.id = id
self.subnet_id = subnet_id
self.name = name
self.igw = None
def get_id(self):
return self.id
def get_subnet_id(self):
return self.subnet_id
def register_igw(self, igw_id):
self.igw = igw_id
def render_xml(self, xml_root, x, y, padding=PADDING):
ng_object = DiagramObject(self.id, self.id, x, y, NAT_GATEWAY_SHAPE)
ng_object.render_xml(xml_root)
insert_text(xml_root,"{}".format(self.name), x, y, dx=50, dy=0)
insert_text(xml_root,"{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=50, dy=0)
if self.igw != None:
ng_object.render_xml_connection(xml_root, self.igw, color=BLUE, complex_route=[(x + (4 * PADDING), y + PADDING)])
class FlowLogsResource:
def __init__(self, id, name):
self.id = id
self.name = name
def get_id(self):
return self.id
def render_xml(self, xml_root, x, y, padding=PADDING):
fl_object = DiagramObject(self.id, self.id, x, y, FLOW_LOGS_SHAPE)
fl_object.render_xml(xml_root, width=30, height=30)
insert_text(xml_root, "{}".format(self.name), x, y, dx=-10, dy=5)
insert_text(xml_root, "{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=-10, dy=5)
class VpcEndpointResource:
def __init__(self, service_name, type):
self.ids = []
self.service_name = service_name
self.type = type
self.rt_associations = []
def add_vpce_id(self, new_id):
#for repeated vpce ids for resource endpoints
self.ids.append(new_id)
def get_servicename(self):
return self.service_name
def register_rt_association(self, rt_id):
self.rt_associations.append(rt_id)
def render_xml(self, xml_root, x, y, route_generator, padding=PADDING):
vpc_e_object = DiagramObject(self.service_name, self.service_name, x, y, ENDPTS_SHAPE)
vpc_e_object.render_xml(xml_root)
insert_text(xml_root,"{} {}".format(self.service_name, self.type), x, y, dx=50, dy=0)
# add text for added vpce's
id_y = y + DIAGRAM_LINE_HEIGHT
for id in self.ids:
insert_text(xml_root,"{}".format(id), x, id_y, dx=50, dy=0)
id_y += DIAGRAM_LINE_HEIGHT
# add associations
for assoc in self.rt_associations:
vpc_e_object.render_xml_connection(xml_root,"{}".format(assoc), color=BLUE,
complex_route=route_generator.get_next_route(x, y + 30))
class VpnGatewayResource:
def __init__(self, id, name, vpn):
self.id = id
self.name = name
self.vpn = vpn
def get_id(self):
return self.id
def render_xml(self, xml_root, x, y, padding=PADDING):
vpngw_object = DiagramObject(self.id, self.id, x, y, VPN_SHAPE)
vpngw_object.render_xml(xml_root)
if self.vpn != "":
#add vpn resource
vpn_object = DiagramObject(self.vpn, self.vpn, x + (3 * padding), y, VPN_CONN_SHAPE)
vpn_object.render_xml(xml_root)
vpn_object.render_xml_connection(xml_root,self.id)
insert_text(xml_root,"{}".format(self.vpn), x + (3 * padding), y, dx=80, dy=20)
insert_text(xml_root,"{}".format(self.name), x, y, dx=50, dy=0)
insert_text(xml_root,"{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=50, dy=0)
class SubnetResource:
def __init__(self, id, cidr, az, name):
self.id = id
self.cidr = cidr
self.az = az
self.ng_list = []
self.col_suggestion = 0
self.associations = []
self.name = name
def get_dimensions(self):
h = SUBNET_MIN_H
ng_height_requirement = len(self.ng_list) * RESOURCE_DISTRIBUTION - PADDING
if ng_height_requirement > h:
h = ng_height_requirement
return (SUBNET_MIN_W, h)
def register_ng(self, ng_resource):
self.ng_list.append(ng_resource)
def register_nacl_association(self, assoc_data):
self.associations.append(assoc_data)
def get_col_suggestion(self):
if len(self.associations) > 0:
return self.associations[0][3].get_col_suggestion()
else:
return 0
def get_id(self):
return self.id
def get_az(self):
return self.az
def get_name(self):
return self.name
def render_xml(self, xml_root, x, y, route_generator, padding=PADDING):
(subnet_w, subnet_h) = self.get_dimensions()
subnet_container = DiagramContainer(self.id, self.id,
x, y,
subnet_w, subnet_h, SUBNET_SHAPE)
subnet_container.render_xml(xml_root,icon_color=ICON_GOLD)
insert_text(xml_root,"{}, CIDR: {}".format(self.id, self.cidr), x, y)
insert_text(xml_root,"{}".format(self.name), x, y + DIAGRAM_LINE_HEIGHT)
for a in self.associations:
subnet_container.render_xml_connection(xml_root,"{}".format(a[1]), text=a[2], color=GREEN,
complex_route=route_generator.get_next_route(x, y + 30),
connection_entry=CONNECTION_ENTRY_RIGHT)
ng_x = x + subnet_w - int(padding / 2)
ng_y = y + int(subnet_h / 2)
for ng in self.ng_list:
ng.render_xml(xml_root,ng_x, ng_y)
ng_y += RESOURCE_DISTRIBUTION
class IgwResource:
def __init__(self, id, vpc_id, name):
self.id = id
self.vpc_id = "{}_container".format(vpc_id)
self.name = name
def get_id(self):
return self.id
def render_xml(self, xml_root, x, y, padding=PADDING, shape=INTERNET_GATEWAY_SHAPE):
igw_object = DiagramObject(self.id, self.id, x, y, shape)
igw_object.render_xml(xml_root)
insert_text(xml_root,"{}".format(self.name), x, y, dx=50, dy=0)
insert_text(xml_root,"{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=50, dy=0)
class NetworkInterfaceResource:
def __init__(self, id, subnet_id, type):
"""CURRENTLY UNUSED IN THE SCRIPT"""
self.id = id
self.subnet_id = "{}_container".format(subnet_id)
self.type = type
def get_id(self):
return self.id
def render_xml(self, xml_root, x, y, width, height, padding=PADDING):
igw_object = DiagramObject(self.id, self.id, x, y, ENI_SHAPE)
igw_object.render_xml(xml_root)
igw_object.render_xml_connection(xml_root,self.subnet_id, text=self.type, COLOR=BLUE)
insert_text(xml_root,"{}".format(self.id), x, y, dx=0, dy=50)
class RouteTableResource:
def __init__(self, id, name):
self.id = id
self.associations = []
self.routes = []
self.name = name
self.az_connections = []
def get_id(self):
return self.id
def cmp_cidr(self, cidr_one_list, cidr_two_list):
if not cidr_one_list or not cidr_two_list:
#both values are the same
return 0
try:
#try to parse as an integer
val_one = int(cidr_one_list[0])
except:
return -1
try:
#try to parse as an integer
val_two = int(cidr_two_list[0])
except:
return 1
if val_one < val_two:
return -1
elif val_one > val_two:
return 1
else:
#recursively compare the next bytes of each cidr block
return self.cmp_cidr(cidr_one_list[1:], cidr_two_list[1:])
def sort_routes(self):
#sort cidr blocks
cidr_sorted = sorted(self.routes, cmp=lambda cidr_one,cidr_two:
self.cmp_cidr(cidr_one.split("."), cidr_two.split(".")),
key=lambda cidr: cidr[0])
#add local gw to front of list
for r in range(len(cidr_sorted)):
if cidr_sorted[r][2] == 'local':
cidr_sorted.insert(0, cidr_sorted.pop(r))
return cidr_sorted
def register_rt_association(self, subnet_id, rt_assoc_id, az):
self.associations.append((subnet_id, rt_assoc_id))
self.az_connections.append(az)
def get_suggested_az(self):
if not self.az_connections:
return NO_AZ
else:
return max(set(self.az_connections), key=self.az_connections.count)
def simplify_origin(self, origin):
if origin == 'EnableVgwRoutePropagation':
return 'Propagated'
elif origin == 'CreateRoute':
return 'Create Route'
elif origin == 'CreateRouteTable':
return 'Create Table'
else:
return origin
def add_route(self, dest_cidr, state, gw_id, origin):
self.routes.append((dest_cidr, state, gw_id, self.simplify_origin(origin)))
def render_xml(self, xml_root, x, y, list_y, route_generator, list_route_generator, rt_diagram_route_generator, padding=PADDING):
route_table_diagram = DiagramObject(self.id, self.id, x, y, ROUTE_TABLE_SHAPE)
route_table_diagram.render_xml(xml_root)
insert_text(xml_root, self.id, x, y, dx=0, dy=50)
for assoc in self.associations:
route_table_diagram.render_xml_connection(xml_root, "{}_container".format(assoc[0]), text=assoc[1],
complex_route=route_generator.get_next_route(x + 50, y + 40))
if len(self.routes) > 0:
#list fields and lane widths
fields = ["Destination CIDR", "State", "Gateway ID", "Origin"]
widths = [DIAGRAM_COL_WIDTH_OVERSIZED, DIAGRAM_COL_WIDTH_SMALL, DIAGRAM_COL_WIDTH_NORMAL, DIAGRAM_COL_WIDTH_NORMAL]
label = "{} | {}".format(self.name, self.id)
if self.name == "":
label = self.id
sorted_routes = self.sort_routes()
rt_list = DiagramList("{}".format(label),
"{}_list".format(self.id), sorted_routes, fields, widths)
resource_height = rt_list.render_xml(xml_root, 0, list_y - RESOURCE_DISTRIBUTION)
if ADD_ROUTE_TABLE_CONNECTIONS:
routes_connected = []
route_y = y + padding
for route in self.routes:
if route[2] not in routes_connected:
rt_list.render_xml_connection(xml_root, route[2], complex_route=rt_diagram_route_generator.get_next_route(x, route_y))
routes_connected.append(route[2])
route_y += LINE_BUNDLE_SPACING
route_table_diagram.render_xml_connection(xml_root, "{}_list".format(self.id), color=RED,
complex_route=list_route_generator.get_next_route(x, y + 10),
connection_entry=CONNECTION_ENTRY_RIGHT)
return resource_height
class AZResource:
def __init__(self, id):
self.id = id
self.subnets = []
self.width_override = (False, 0)
def register_subnet(self, subnet_resource):
self.subnets.append(subnet_resource)
def get_id(self):
return self.id
def override_width(self, width):
self.width_override = (True, width)
def empty(self):
return len(self.subnets) == 0
def get_total_subnets(self):
return len(self.subnets)
def get_dimensions(self):
w = 0
h = PADDING
for subnet in self.subnets:
(new_w, new_h) = subnet.get_dimensions()
w = new_w
h += new_h + PADDING
if self.width_override[0]:
w = self.width_override[1]
else:
w = w + (2 * PADDING)
return (w, h)
def render_xml(self, xml_root, x, y, nacl_route_generator, padding=PADDING):
#render az outline
(width, height) = self.get_dimensions()
#add a box with a dashed outline
newElement = ET.SubElement(xml_root, "mxCell",
id=self.id,
style="rounded=1;arcSize=10;dashed=1;strokeColor={};fillColor=none;gradientColor=none;dashPattern=8 4;strokeWidth=2;".format(AWS_BORDER_ORANGE),
vertex="1",
value="",
parent="1")
ET.SubElement(newElement, "mxGeometry",
x="{}".format(x),
y="{}".format(y),
width="{}".format(width),
height="{}".format(height)).set('as','geometry')
insert_text(xml_root, self.id, x + int(width / 2) - 40, y + height - 40, font_color=AWS_BORDER_ORANGE)
subnet_x = x + padding
subnet_y = y + padding
sorted_subnets = sorted(self.subnets, key=lambda subnet_obj: subnet_obj.get_name())
for subnet in sorted_subnets:
col_suggestion = subnet.get_col_suggestion()
(sub_w, sub_h) = subnet.get_dimensions()
offset = col_suggestion * ((width - sub_w - padding) / SUBNET_ALIGNMENT_COLS)
subnet.render_xml(xml_root, subnet_x + offset, subnet_y, nacl_route_generator)
subnet_y = subnet_y + padding + sub_h
class PeeringResource:
def __init__(self, id, accepting_vpc, requesting_vpc, name, connection_ref):
self.id = id
self.accepting_vpc = accepting_vpc
self.requesting_vpc = requesting_vpc
self.name = name
self.connection = connection_ref
def register_diagram_vpc(self, diagram_vpc_id):
self.diagram_vpc_id = diagram_vpc_id
def get_id(self):
return self.id
def render_xml(self, xml_root, x, y, route_generator, padding=PADDING):
peering_object = DiagramObject(self.id, self.id, x, y, PEERING_SHAPE)
peering_object.render_xml(xml_root)
peering_object.render_xml_connection(xml_root, self.connection, complex_route=route_generator.get_next_route(x + 50, y + 40))
insert_text(xml_root, "{}".format(self.name), x, y, dx=50, dy=-10)
insert_text(xml_root, "{}".format(self.id), x, y + DIAGRAM_LINE_HEIGHT, dx=50, dy=-10)
class VpcResource:
def __init__(self, id, name, cidr):
self.id = id
self.az_list = []
self.nacl_list = []
self.rt_list = []
self.name = name
self.cidr = cidr
self.dns_server_list = []