-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenesisSynthesiser.py
2347 lines (1905 loc) · 80.5 KB
/
GenesisSynthesiser.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
from z3 import *
from Topology import Topology
from PolicyDatabase import PolicyDatabase
#from NetworkPredicate import *
import time
import random
#import metis
import networkx as nx
#from SliceGraphSolver import SliceGraphSolver
from Tactic import *
import re
from subprocess import *
from collections import deque
from collections import defaultdict
class GenesisSynthesiser(object) :
def __init__(self, topo, pdb, DC=True, TopoSlicing=False, pclist=None, useTactic=False, tactic="", noOptimizations=False, BridgeSlicing=True, weakIsolation=False, repairMode=False, controlPlane=False, ospfOnly=False) :
self.topology = topo
# Network Forwarding Function
#self.Fwd = Function('Fwd', IntSort(), IntSort(), IntSort(), BoolSort())
# self.Reach = Function('Reach', IntSort(), IntSort(), IntSort(), BoolSort())
# Packet Classes to be synthesized.
self.stackfwdvars = dict()
self.stackreachvars = dict()
#self.delta = Function('delta', IntSort(), IntSort(), IntSort())
self.pc = Int('pc') # Generic variable for packet classes
self.z3Solver = Solver()
self.z3Solver.set(unsat_core=True)
self.z3Solver.set(':smt.phase_selection', 5)
self.z3Solver.set(':smt.random_seed', random.randint(1, 1000))
#self.z3Solver = Optimize()
# #self.z3Solver.set("sat.phase", "always-false")
self.fwdmodel = None
self.count = 20
# Policy Database.
self.pdb = pdb
# DC Synthesis Variables
self.DCPaths = dict() # Stores the solutions obtained during the DC synthesis procedure.
self.DCLinkCapacityConstraints = []
# Store the different retry attempts for link capacity recovery to ensure we dont repeat solutions.
self.DCLinkRecoveryAttempts = dict()
self.DCTrackedPaths = dict()
self.DCUnsatLinkCores = []
# DC Synthesis Constants.
self.CUT_THRESHOLD = 50
self.BASE_GRAPH_SIZE_THRESHOLD = 10
self.CURR_GRAPH_SIZE_THRESHOLD = 10
self.MIN_GRAPH_THRESHOLD = 3
# Different Solution Recovery Variables.
self.DIFF_SOL_RETRY_COUNT = 10
self.ResetOldSolutionsFlag = False
# Link Capacity Recovery Variables
self.LINK_RECOVERY_COUNT = 4
# DC Synthesis Flags
self.noOptimizationsFlag = noOptimizations
self.DCSynthesisFlag = DC
self.recoveryFlag = False
self.topologySlicingFlag = TopoSlicing
self.bridgeSlicingFlag = BridgeSlicing
self.synthesisSuccessFlag = True
self.weakIsolationFlag = weakIsolation
# SAT Encoding Flags
self.UseQuantifiersflag = True
self.UseTopoSAT = True
self.addGlobalTopoFlag = False
# Profiling Information.
self.z3constraintTime = 0 # Time taken to create the constraints.
self.z3addTime = 0 # Time taken to add the constraints.
self.z3numberofadds = 0 # Count of adds.
self.z3solveTime = 0 # Time taken to solve the constraints.
self.metisTime = 0 # Time taken to partition the graphs.
self.z3SolveCount = 0 # Count of z3 solve instances.
# Tactic variables
self.useTacticFlag = useTactic
self.tactic = tactic
self.tactics = dict()
# Constraint Stores
self.backwardReachPropagationConstraints = dict()
# BFS Global Variable.
self.bfsLists = dict()
for i in range(1, self.topology.getMaxPathLength() + 1) :
self.bfsLists[i] = []
# TE Variables
self.maxUtilizationVar = Real('maxUtilVar')
self.totalUtilizationVar = Real('totUtilVar')
# Repair Mode
self.repairMode = repairMode
# Generate Control Plane
self.controlPlaneMode = controlPlane
self.ospfOnlyMode = ospfOnly
self.destinationDAGs = dict()
# SMT Variables
#self.smtlib2file = open("genesis-z3-smt", 'w')
# Initialize SMT LIB2 file.
#self.smtlib2file.write("; Genesis Generated SMT-LIB2 \n(set-info :status unknown)\n(set-logic QF_LIA)\n")
def initializeSATVariables(self) :
swCount = self.topology.getSwitchCount()
pcRange = self.pdb.getPacketClassRange()
maxPathLen = self.topology.getMaxPathLength()
# Fwd Relation Variables
self.fwdvars = [[[0 for x in range(pcRange)] for x in range(swCount + 1)] for x in range(swCount + 1)]
# Reach Relation Variables
self.reachvars = [[[0 for x in range(maxPathLen+1)] for x in range(pcRange)] for x in range(swCount + 1)]
for sw1 in range(1,swCount+1):
for sw2 in range(1,swCount+1):
for pc in range(pcRange) :
self.fwdvars[sw1][sw2][pc] = Bool(str(sw1)+"-"+str(sw2)+":"+str(pc))
for sw in range(1,swCount+1):
for pc in range(pcRange) :
for plen in range(1,maxPathLen +1) :
self.reachvars[sw][pc][plen] = Bool(str(sw)+":"+str(pc)+":"+str(plen))
# Fwd relation
def Fwd(self, sw1, sw2, pc) :
if self.pdb.getOriginalPacketClass(pc) <> pc :
neighbours = self.topology.getSwitchNeighbours(sw2)
if sw1 not in neighbours :
return False
else :
return self.stackfwdvars[pc][sw1][sw2]
else :
neighbours = self.topology.getSwitchNeighbours(sw2)
if sw1 not in neighbours :
return False
else :
return self.fwdvars[sw1][sw2][pc]
# Reach relation
def Reach(self, sw, pc, plen) :
if self.pdb.getOriginalPacketClass(pc) <> pc :
if plen == 0 :
if sw == self.pdb.getSourceSwitch(pc) :
return True
else :
return False
return self.stackreachvars[pc][sw][plen]
else :
if plen == 0 :
if sw == self.pdb.getSourceSwitch(pc) :
return True
else :
return False
return self.reachvars[sw][pc][plen]
def pushSATVariables(self, pclist):
swCount = self.topology.getSwitchCount()
pcRange = self.pdb.getPacketClassRange()
maxPathLen = self.topology.getMaxPathLength()
for pc in pclist :
if self.pdb.getOriginalPacketClass(pc) <> pc :
# Need to add variables.
self.stackfwdvars[pc] = [[0 for x in range(swCount + 1)] for x in range(swCount + 1)]
self.stackreachvars[pc] = [[0 for x in range(maxPathLen+1)] for x in range(swCount + 1)]
for sw1 in range(1,swCount+1):
for sw2 in range(1,swCount+1):
self.stackfwdvars[pc][sw1][sw2] = Bool(str(sw1)+"-"+str(sw2)+":"+str(pc))
for sw in range(1,swCount+1):
for plen in range(1,maxPathLen +1) :
self.stackreachvars[pc][sw][plen] = Bool(str(sw)+":"+str(pc)+":"+str(plen))
def popSATVariables(self, pclist) :
for pc in pclist :
if self.pdb.getOriginalPacketClass(pc) <> pc :
del self.stackfwdvars[pc]
del self.reachvars[pc]
def enforcePolicies(self):
# If there are bridges in the topology, we can split the
# synthesis into different parts. Optimization only
# applicable in sparse topologies with bridges.
if self.bridgeSlicingFlag:
self.bridgeSlicingFlag = self.topology.findTopologyBridges()
# If there are traffic engineering objectives, use the Optimize() class of Z3
if self.pdb.trafficEngineeringEnabled() :
self.z3Solver = Optimize()
print "==GENESIS=="
print "Input size: "+ str(self.pdb.getPacketClassRange()) + " packet classes "
start_t = time.time()
self.initializeSATVariables()
# Enforce Tactics
if self.useTacticFlag :
#st = time.time()
self.useTactic()
#et = time.time()
# Generate the relational classes (maximal set of related packet classes)
# pc1 is related to pc2 if pc1 || pc2 or there are global policies like
# link capacities or TE
self.pdb.createRelationalClasses()
# If DC synthesis mode is enabled
if self.DCSynthesisFlag :
rcGraphs = self.pdb.getRelationalClassGraphs()
# Add link capacity constraints
self.DCLinkCapacityConstraints = self.pdb.getLinkCapacityConstraints()
# To make DC synthesis complete, we increase
# current graph threshold by a factor by 2 each time DC synthesis fails.
for rcGraph in rcGraphs :
rcGraphSat = False
self.CURR_GRAPH_SIZE_THRESHOLD = self.BASE_GRAPH_SIZE_THRESHOLD # reset the graph size to base value.
while rcGraphSat == False and self.CURR_GRAPH_SIZE_THRESHOLD < rcGraph.number_of_nodes() :
(rcGraphSat, synPaths) = self.enforceGraphPoliciesDC(rcGraph)
if rcGraphSat == False :
# Incremental Graph recovery.
self.CURR_GRAPH_SIZE_THRESHOLD = self.CURR_GRAPH_SIZE_THRESHOLD * 2 # Doubling the current graph size
#print "Incrementing the solver graph size to " + str(self.CURR_GRAPH_SIZE_THRESHOLD)
if rcGraphSat == False :
# Apply non-DC synthesis.
(rcGraphSat, synPaths) = self.enforceGraphPolicies(rcGraph=rcGraph, recovery=False)
self.synthesisSuccessFlag = self.synthesisSuccessFlag & rcGraphSat
#self.enforceMulticastPolicies()
elif self.noOptimizationsFlag :
#st = time.time()
self.synthesisSuccessFlag = self.enforceUnicastPoliciesNoOptimizations()
#et = time.time()
#print "No Optimizations time is", et - st
else :
self.synthesisSuccessFlag = self.enforceUnicastPolicies()
end_t = time.time()
self.zepFile = open("zeppelin-timing", 'a')
self.zepFile.write("Zeppelin\t" + str(self.pdb.getPacketClassRange()) + "\t" + str(end_t - start_t))
self.zepFile.write("\t")
self.zepFile.close()
if self.synthesisSuccessFlag and self.DCSynthesisFlag:
for pc in self.DCPaths :
self.pdb.addPath(pc, self.DCPaths[pc])
self.pdb.validatePolicies(self.topology)
elif self.synthesisSuccessFlag and not self.DCSynthesisFlag :
self.pdb.validatePolicies(self.topology)
self.pdb.printPaths(self.topology)
self.pdb.validatePolicies(self.topology)
# Control plane synthesis: outside scope of POPL17 Genesis paper.
if self.controlPlaneMode :
from OuterZeppelinSynthesiser import OuterZeppelinSynthesiser
from ZeppelinSynthesiser import ZeppelinSynthesiser
if not self.ospfOnlyMode :
self.endpoints = []
paths = dict()
policyDatabase = PolicyDatabase()
for pc in range(self.pdb.getPacketClassRange()) :
endpt = [self.pdb.getSourceSwitch(pc), self.pdb.getDestinationSwitch(pc)]
if endpt not in self.endpoints :
self.endpoints.append(endpt)
pc1 = policyDatabase.addReachabilityPolicy(self.pdb.getDestinationSwitch(pc), self.pdb.getSourceSwitch(pc), self.pdb.getDestinationSwitch(pc))
policyDatabase.addPath(pc1, self.pdb.getPath(pc))
paths[pc1] = self.pdb.getPath(pc)
dsts = self.pdb.getDestinations()
for dst in dsts :
policyDatabase.addDestinationDAG(dst, self.destinationDAGs[dst])
self.outerZepSynthesizer = OuterZeppelinSynthesiser(topology=self.topology, pdb=policyDatabase, timeout=600, numDomains=4, rfOpt=False, configOpt=False)
self.outerZepSynthesizer.enforceDAGs(policyDatabase.getDestinationDAGs(), paths, self.endpoints)
else :
# Only OSPF Synthesis.
self.endpoints = []
self.waypoints = dict()
self.waypointClasses = []
waypointPaths = dict()
paths = dict()
policyDatabase = PolicyDatabase()
newpc = 0
dags = dict()
self.backups = dict()
self.waypointFile = open("waypoint-classes")
for line in self.waypointFile:
W = line.split("-")
wclass = []
for w in W :
wclass.append(int(w))
self.waypointClasses.append(wclass)
if len(self.waypointClasses) == 0 :
for pc in range(0, self.pdb.getPacketClassRange()) :
dst = int(self.pdb.getPredicate(pc))
path = self.pdb.getPath(pc)
pc1 = policyDatabase.addReachabilityPolicy(dst, self.pdb.getSourceSwitch(pc), self.pdb.getDestinationSwitch(pc))
policyDatabase.addPath(pc1, path)
if dst not in dags :
dags[dst] = dict()
dag = dags[dst]
for index in range(len(path) - 1):
dag[path[index]] = path[index + 1]
dag[self.pdb.getDestinationSwitch(pc)] = None
for dst in dags :
policyDatabase.addDestinationDAG(dst, dags[dst])
self.zepSynthesiser = ZeppelinSynthesiser(topology=self.topology, pdb=policyDatabase, resilience=False, waypointCompliance=False )
self.zepSynthesiser.enforceDAGs(dags=policyDatabase.getDestinationDAGs(), endpoints=self.endpoints, waypoints=self.waypoints, backups=self.backups)
else :
for pc in range(0, self.pdb.getPacketClassRange()) :
dst = int(self.pdb.getPredicate(pc))
if dst not in self.waypoints :
self.waypoints[dst] = []
self.waypoints[dst] = self.waypointClasses[dst % len(self.waypointClasses)]
for pc in range(0, self.pdb.getPacketClassRange()) :
dst = int(self.pdb.getPredicate(pc))
path = self.pdb.getPath(pc)
srcSw = self.pdb.getSourceSwitch(pc)
dstSw = self.pdb.getDestinationSwitch(pc)
endpt = [srcSw, dstSw]
if len(path) == 0 : # no path
continue
if endpt in self.endpoints :
# pc is a backup path. Check if traversing waypoint and provide as backup.
backupFlag = False
# Check if backup already present.
if dst in self.backups :
for bpath in self.backups[dst] :
if bpath[0] == srcSw :
# Backup already exists. Ignore this path.
backupFlag = True
if backupFlag :
continue
waypointFlag = False
if len(self.pdb.getWaypoints(pc)) == 0 :
waypointFlag = True
for w in self.waypoints[dst] :
if w in path :
waypointFlag = True
break
if waypointFlag :
if dst not in self.backups :
self.backups[dst] = []
self.backups[dst].append(path)
continue
# path = []
# sw = srcSw
# while sw != None:
# path.append(sw)
# sw = dag[sw]
if path[len(path) - 1] != dstSw :
print "Something is wrong!"
exit(0)
self.waypointMode = True
waypointFlag = False
if len(self.pdb.getWaypoints(pc)) == 0 :
waypointFlag = True
self.waypointMode = False
for w in self.waypoints[dst] :
if w in path :
waypointFlag = True
if waypointFlag :
if endpt not in self.endpoints :
self.endpoints.append(endpt)
pc1 = policyDatabase.addReachabilityPolicy(dst, self.pdb.getSourceSwitch(pc), self.pdb.getDestinationSwitch(pc))
policyDatabase.addPath(pc1, path)
if dst not in dags :
dags[dst] = dict()
dag = dags[dst]
for index in range(len(path) - 1):
dag[path[index]] = path[index + 1]
dag[dstSw] = None
for dst in dags :
policyDatabase.addDestinationDAG(dst, dags[dst])
self.zepSynthesiser = ZeppelinSynthesiser(topology=self.topology, pdb=policyDatabase, resilience=True, waypointCompliance=True )
self.zepSynthesiser.enforceDAGs(dags=policyDatabase.getDestinationDAGs(), endpoints=self.endpoints, waypoints=self.waypoints, backups=self.backups)
self.pdb.writeForwardingRulesToFile(self.topology)
self.printProfilingStats()
if self.repairMode :
self.enforceChangedPolicies()
def addReachabilityPolicy(self, predicate, src, dst, waypoints=None, pathlen=None) :
""" src = next hop switch of source host(s)
dst = next hop switch of destination host(s)
W = Waypoint Set (list of nodes)
pathlen = Maxpath length of the path from source to destination"""
# Translate s, d, W into logical topology numbers.
srcSw = self.topology.getSwID(src)
dstSw = self.topology.getSwID(dst)
W = None
if not waypoints == None :
W = []
for bag in waypoints :
logicalBag = []
for w in bag :
logicalBag.append(self.topology.getSwID(w))
W.append(logicalBag)
# Add policy to PDB :
pc = self.pdb.addReachabilityPolicy(predicate, srcSw, dstSw, W, pathlen)
return pc
def addTrafficIsolationPolicy(self, policy1, policy2) :
# Isolation of traffic for Policies policy1 and policy2
pc = self.pdb.addIsolationPolicy(policy1,policy2)
def addEqualMulticastPolicy(self, srcIP, srcSw, dstIPs, dstSws) :
pc = self.pdb.addEqualMulticastPolicy(srcIP, srcSw, dstIPs, dstSws)
def addMulticastPolicy(self, srcIP, srcSw, dstIPs, dstSws) :
pc = self.pdb.addMulticastPolicy(srcIP, srcSw, dstIPs, dstSws)
def addSwitchTablePolicy(self, swName, tableSize) :
swID = self.topology.getSwID(swName)
self.pdb.addSwitchTableConstraint(swID, tableSize)
def addLinkCapacityPolicy(self, sw1, sw2, cap) :
swID1 = self.topology.getSwID(sw1)
swID2 = self.topology.getSwID(sw2)
self.pdb.addLinkCapacityConstraint(swID1, swID2, cap)
def addTrafficEngineeringObjective(self, minavg=False, minmax=False):
""" Add a traffic engineering objective.
minavg : Minimizing average utilization of links
"""
self.pdb.addTrafficEngineeringObjective(minavg, minmax)
def enforceUnicastPolicies(self) :
""" Enforcement of Policies stored in the PDB. """
# Create Relational Packet Classses.
relClasses = self.pdb.getRelationalClasses()
if self.controlPlaneMode :
print "In control plane generation mode"
start_t = time.time()
# Need to generate paths for synthesis of control plane
for pc1 in range(self.pdb.getPacketClassRange()) :
for pc2 in range(pc1 + 1, self.pdb.getPacketClassRange()) :
self.addDestinationTreeConstraints(pc1, pc2)
#self.addDiamondConstraints(pc1, pc2)
print "Added control plane constraints", time.time() - start_t
linkCapacityConstraints = self.pdb.getLinkCapacityConstraints()
self.addLinkConstraints(range(self.pdb.getPacketClassRange()), linkCapacityConstraints)
switchTableConstraints = self.pdb.getSwitchTableConstraints()
self.addSwitchTableConstraints(switchTableConstraints) # Adding switch table constraints.
for relClass in relClasses :
# Independent Synthesis of relClass. There is one relClass if there are global policies
self.z3Solver.push()
#reachtime = time.time()
for pc in relClass :
if not self.pdb.isMulticast(pc):
policy = self.pdb.getReachabilityPolicy(pc)
self.addReachabilityConstraints(srcIP=policy[0][0], srcSw=policy[0][2], dstIP=policy[0][1], dstSw=policy[0][3],pc=pc, W=policy[1], pathlen=policy[2])
if not self.addGlobalTopoFlag :
#st = time.time()
# Add Topology Constraints
self.addSinglePathConstraints(pc)
#isolationtime = time.time()
# Add traffic isolation constraints.
for pno in range(self.pdb.getIsolationPolicyCount()) :
pc = self.pdb.getIsolationPolicy(pno)
pc1 = pc[0]
pc2 = pc[1]
if pc1 in relClass and pc2 in relClass:
self.addTrafficIsolationConstraints(pc1, pc2)
#print "Time taken to add isolation constraints is", time.time() - isolationtime
# check if global traffic engineering constraints
if self.pdb.minimizeAverageUtilizationTE() :
self.addAverageUtilizationMinimizationConstraints()
elif self.pdb.minimizeMaxUtilizationTE() :
self.addMaxUtilizationMinimizationConstraints()
# Each relational class can be synthesised independently.
solvetime = time.time()
modelsat = self.z3Solver.check()
self.z3solveTime += time.time() - solvetime
#tprint "Time taken to solve constraints is " + str(time.time() - st)
if modelsat == z3.sat :
#print "Solver return SAT"
self.fwdmodel = self.z3Solver.model()
# print "Total utilization", self.fwdmodel.evaluate(self.totalUtilizationVar)
# print "Max utilization", self.fwdmodel.evaluate(self.maxUtilizationVar)
for pc in relClass :
self.pdb.addPath(pc, self.getPathFromModel(pc))
else :
print "Input Policies not realisable"
# These unsat cores could be used to generate policy violations for the operator.
unsatCores = self.z3Solver.unsat_core()
for unsatCore in unsatCores :
print str(unsatCore)
self.z3Solver.pop()
def enforceUnicastPoliciesNoOptimizations(self) :
""" Enforcement of Policies stored in the PDB without any optimizations """
self.addSinglePathConstraints(0, self.pdb.getPacketClassRange())
switchTableConstraints = self.pdb.getSwitchTableConstraints()
self.addSwitchTableConstraints(switchTableConstraints) # Adding switch table constraints.
linkCapacityConstraints = self.pdb.getLinkCapacityConstraints()
self.addLinkConstraints(range(self.pdb.getPacketClassRange()), linkCapacityConstraints)
# Add reachability constraints.
for pc in range(self.pdb.getPacketClassRange()) :
if not self.pdb.isMulticast(pc) :
policy = self.pdb.getReachabilityPolicy(pc)
self.addReachabilityConstraints(srcIP=policy[0][0], srcSw=policy[0][2], dstIP=policy[0][1], dstSw=policy[0][3],pc=pc, W=policy[1], pathlen=policy[2])
# Add traffic constraints.
for pno in range(self.pdb.getIsolationPolicyCount()) :
pcs = self.pdb.getIsolationPolicy(pno)
pc1 = pcs[0]
pc2 = pcs[1]
self.addTrafficIsolationConstraints(pc1, pc2)
# Apply synthesis
solvetime = time.time()
modelsat = self.z3Solver.check()
self.z3solveTime += time.time() - solvetime
if modelsat == z3.sat :
#print "Solver return SAT"
self.fwdmodel = self.z3Solver.model()
for pc in range(self.pdb.getPacketClassRange()) :
self.pdb.addPath(pc, self.getPathFromModel(pc))
else :
print "Input Policies not realisable"
def addSinglePathConstraints(self, pcStart, pcEnd=0) :
""" Adds constraints used in waypoints to ensure single path"""
if pcEnd == 0 :
""" Topology Constraint for one packet class"""
pcEnd = pcStart + 1
st = time.time()
swCount = self.topology.getSwitchCount()
# \forall sw \forall n \in neighbours(sw) and NextHop = {n | F(sw,n,pc,1) = True}. |NextHop| \leq 1
# None or only one of F(sw,n,pc,1) can be true.
for pc in range(pcStart, pcEnd) :
if not self.pdb.isMulticast(pc) :
""" Unicast packet class """
if not self.pdb.hasWaypoints(pc) :
# Dont need to have topology forwarding constraints for unicast forwarding
continue
useBridgeSlicing = False
if self.bridgeSlicingFlag :
# Find if exists in a bridge slice.
srcSlice = self.topology.getBridgeSliceNumber(self.pdb.getSourceSwitch(pc))
dstSlice = self.topology.getBridgeSliceNumber(self.pdb.getDestinationSwitch(pc))
if srcSlice == dstSlice and srcSlice <> None :
# Path will exist only in this slice.
swList = self.topology.getBridgeSlice(srcSlice)
useBridgeSlicing = True
else :
swList = range(1,swCount + 1)
else :
swList = range(1,swCount + 1)
for sw in swList :
neighbours = self.topology.getSwitchNeighbours(sw, useBridgeSlicing)
# Add assertions to ensure f(sw,*) leads to a valid neighbour.
topoAssertions = []
unreachedAssertions = []
for n in neighbours :
#neighbourAssert = self.F(sw,n,pc,1) == True
neighbourAssertions = [self.Fwd(sw,n,pc)]
unreachedAssertions.append(Not(self.Fwd(sw,n,pc)))
for n1 in neighbours :
if n == n1 :
continue
else :
neighbourAssertions.append(Not(self.Fwd(sw,n1,pc)))
neighbourAssert = And(*neighbourAssertions)
topoAssertions.append(neighbourAssert)
unreachedAssert = And(*unreachedAssertions)
topoAssertions.append(unreachedAssert) # Either one forwarding rule or no forwarding rules.
topoAssert = Or(*topoAssertions)
self.z3numberofadds += 1
#addtime = time.time() # Profiling z3 add.
self.z3Solver.add(topoAssert)
#self.z3addTime += time.time() - addtime
else :
""" Multicast packet class. No restrictions on forwarding set """
pass
# def addSinglePathConstraints(self, pcStart, pcEnd=0) :
# if self.UseTopoSAT == True :
# self.addSinglePathConstraints(pcStart, pcEnd)
# return
# if pcEnd == 0 :
# """ Topology Constraint for one packet class"""
# pcEnd = pcStart + 1
# swCount = self.topology.getSwitchCount()
# # \forall sw \forall n \in neighbours(sw) and NextHop = {n | F(sw,n,pc,1) = True}. |NextHop| \leq 1
# # None or only one of F(sw,n,pc,1) can be true.
# for sw in range(1,swCount+1) :
# for pc in range(pcStart, pcEnd) :
# if not self.pdb.isMulticast(pc) :
# """ Unicast packet class """
# neighbours = self.topology.getSwitchNeighbours(sw)
# fname = "fwdSet" + str(sw) + "#" + str(pc)
# fwdSet = Function(fname, IntSort(), IntSort(), IntSort(), IntSort())
# i = 0
# for n in neighbours :
# if n == neighbours[0] :
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(Implies(self.Fwd(sw, n, pc), fwdSet(sw, pc, n) == 1))
# self.z3addTime += time.time() - addtime
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(Implies(Not(self.Fwd(sw, n, pc)), fwdSet(sw, pc, n) == 0))
# self.z3addTime += time.time() - addtime
# else :
# prevn = neighbours[i - 1]
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(Implies(self.Fwd(sw, n, pc), fwdSet(sw, pc, n) == 1 + fwdSet(sw, pc, prevn)))
# self.z3addTime += time.time() - addtime
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(Implies(Not(self.Fwd(sw, n, pc)), fwdSet(sw, pc, n) == fwdSet(sw, pc, prevn)))
# self.z3addTime += time.time() - addtime
# i +=1
# n = neighbours[i - 1] # Last element in the list.
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(fwdSet(sw, pc, n) < 2)
# self.z3addTime += time.time() - addtime
# else :
# """ Multicast packet class. No restrictions on forwarding set """
# pass
# def addTopologySliceConstraints(self, slice, pcStart, pcEnd=0) :
# if pcEnd == 0 :
# """ Topology Constraint for one packet class"""
# pcEnd = pcStart + 1
# topologySlice = self.topology.getTopologySlice(slice)
# # \forall sw \forall n \in neighbours(sw) and NextHop = {n | F(sw,n,pc,1) = True}. |NextHop| \leq 1
# # None or only one of F(sw,n,pc,1) can be true.
# for sw in topologySlice :
# for pc in range(pcStart, pcEnd) :
# if not self.pdb.isMulticast(pc) :
# """ Unicast packet class """
# neighbours = self.topology.getSwitchNeighbours(sw)
# # Add assertions to ensure f(sw,*) leads to a valid neighbour.
# topoAssert = False
# unreachedAssert = True
# for n in neighbours :
# #neighbourAssert = self.F(sw,n,pc,1) == True
# neighbourAssert = self.Fwd(sw,n,pc)
# unreachedAssert = And(unreachedAssert, Not(self.Fwd(sw,n,pc)))
# for n1 in neighbours :
# if n == n1 :
# continue
# else :
# neighbourAssert = And(neighbourAssert, Not(self.Fwd(sw,n1,pc)))
# topoAssert = Or(topoAssert, neighbourAssert)
# topoAssert = Or(topoAssert, unreachedAssert) # Either one forwarding rule or no forwarding rules.
# self.z3numberofadds += 1
# addtime = time.time() # Profiling z3 add.
# self.z3Solver.add(topoAssert)
# self.z3addTime += time.time() - addtime
# else :
# """ Multicast packet class. No restrictions on forwarding set """
# pass
def addReachabilityConstraints(self, srcIP, srcSw, dstIP, dstSw, pc, W=None, pathlen=0) :
#reachtime = time.time()
if pathlen == 0 :
# Default argument. Set to max.
pathlen = self.topology.getMaxPathLength()
# Add Reachability in atmost pathlen steps constraint.
#reachAssert = self.Reach(dstSw,pc,pathlen) == True
# Destination is reachable in <= plen steps
reachAssertions = []
for plen in range(1,pathlen+1) :
reachAssertions.append(self.Reach(dstSw,pc,plen))
reachAssert = Or(*reachAssertions)
self.z3numberofadds += 1
#addtime = time.time() # Profiling z3 add.
self.z3Solver.add(reachAssert)
#self.z3addTime += time.time() - addtime
# At Destination, forwarding has to stop here. So, F(d,neighbour(d),pc,1) == False
# When we perform the translation to rules, we can forward it to host accordingly.
neighbours = self.topology.getSwitchNeighbours(dstSw)
destAssert = True
for n in neighbours :
destAssert = And(destAssert, self.Fwd(dstSw,n,pc) == False)
self.z3numberofadds += 1
#addtime = time.time() # Profiling z3 add.
self.z3Solver.add(destAssert)
#self.z3addTime += time.time() - addtime
# If waypoints, add ordered waypoint constraints.
if len(W) > 0 :
totalwaypointCount = 0
currwaypointCount = 0
for wayptSet in W :
totalwaypointCount += len(wayptSet)
prevWayptSet = None
for wayptSet in W :
# ordered Waypoints.
# Add the Waypoint Constraints.
currwaypointCount += len(wayptSet)
for w in wayptSet :
reachAssertions = []
#for plen in range(1 + currwaypointCount - len(wayptSet), pathlen - (totalwaypointCount - currwaypointCount)) :
for plen in range(1, pathlen + 1):
reachAssertions.append(self.Reach(w,pc,plen))
if prevWayptSet <> None :
for w2 in prevWayptSet :
orderAssertions = []
for plen2 in range(1, plen):
orderAssertions.append(self.Reach(w2, pc, plen2))
orderAssert = Implies(self.Reach(w, pc, plen), Or(*orderAssertions))
self.z3Solver.add(orderAssert)
reachAssert = Or(*reachAssertions)
self.z3numberofadds += 1
#addtime = time.time() # Profiling z3 add.
self.z3Solver.add(reachAssert)
#self.z3addTime += time.time() - addtime
prevWayptSet = wayptSet
#st = time.time()
# This prunes the Reach relation to only valid
# states by constructing a tree from the source switch
# For example, if a switch sw is a distance = 3 from src, then
# Reach(sw,pc,[0,1,2]) is trivially False.
self.addTopologyTreeConstraints(srcSw, pc)
# Add Path Constraints for this flow to find the forwarding model for this flow.
self.addPathConstraints(srcSw,pc)
#et = time.time()
#print "Path Constraints time is " + str(et - st)
#print "total function takes ", time.time() - reachtime
# Note This functions take the most time for each pc. Look for ways to improve this.
def addPathConstraints(self, src, pc) :
swCount = self.topology.getSwitchCount()
maxPathLen = self.topology.getMaxPathLength()
useBridgeSlicing = False
if self.topologySlicingFlag :
swList = self.topology.getTopologySlice(self.topology.getSliceNumber(src))
elif self.bridgeSlicingFlag :
# Find if exists in a bridge slice.
srcSlice = self.topology.getBridgeSliceNumber(src)
dstSlice = self.topology.getBridgeSliceNumber(self.pdb.getDestinationSwitch(pc))
if srcSlice == dstSlice and srcSlice <> None :
# Path will exist only in this slice.
swList = self.topology.getBridgeSlice(srcSlice)
useBridgeSlicing = True
else :
swList = range(1,swCount + 1)
else :
swList = range(1,swCount + 1)
neighbours = self.topology.getSwitchNeighbours(src, useBridgeSlicing)
srcAssertions = []
for n in neighbours :
srcAssertions.append(And(self.Fwd(src,n,pc), self.Reach(n, pc, 1)))
self.z3numberofadds += 1
#addtime = time.time() # Profiling z3 add.
self.z3Solver.add(Or(*srcAssertions))
#self.z3addTime += time.time() - addtime
st = time.time()
#constime = 0
#addtime = 0
for i in swList :
if i == src :
continue
for pathlen in range(1,maxPathLen+1) :
if i not in self.bfsLists[pathlen] :
# Not at distance i in the topology tree, dont add constraints.
continue
ineighbours = self.topology.getSwitchNeighbours(i, useBridgeSlicing)
if self.useTacticFlag and pc in self.tactics :
# Use Tactic to reduce constraints.
tactic = self.tactics[pc]
labels = tactic.getPreviousLabels(self.topology.getLabel(i), pathlen)
labelneighbours = []
if len(labels) == 0 :
# self.Reach(i,pc,pathlen) = False
self.z3Solver.add(Not(self.Reach(i,pc,pathlen)))
continue
elif labels == ["!DST!"] :
if i != self.pdb.getDestinationSwitch(pc) :
# self.Reach(i,pc,pathlen) = False
self.z3Solver.add(Not(self.Reach(i,pc,pathlen)))
continue
else :
# Modify the ineighbours
for n in ineighbours :
if self.topology.getLabel(n) in labels :
labelneighbours.append(n)
ineighbours = labelneighbours
# Backward reachability proogation constraints.
# If a node $n_1$ is reachable in $k$ steps, there must be a node $n_2$ reachable in $k-1$ steps and
# a forwarding rule $n_2 \rightarrow n_1$.
constraintKey = str(i) + ":" + str(pc) + "*" + str(pathlen)
if constraintKey in self.backwardReachPropagationConstraints :
# Reuse constraint object if already created.
backwardReachConstraint = self.backwardReachPropagationConstraints[constraintKey]
else :
# Create constraint.
beforeHopAssertions = []
#beforeHopAssertionsStr = ""
ct = time.time()
for isw in ineighbours :
beforeHopAssertions.append(And(self.Fwd(isw, i, pc), self.Reach(isw, pc, pathlen - 1)))
backwardReachConstraint = Implies(self.Reach(i,pc,pathlen), Or(*beforeHopAssertions))
#constime += time.time() - ct
#at = time.time()
self.z3Solver.add(backwardReachConstraint)
#addtime += time.time() - at
# Store constraint for reuse.
constraintKey = str(i) + ":" + str(pc) + "*" + str(pathlen)
if constraintKey not in self.backwardReachPropagationConstraints :
self.backwardReachPropagationConstraints[constraintKey] = backwardReachConstraint
# print "constime", constime
# print "addTime", addtimw
# st = time.time()
def addTopologyTreeConstraints(self, srcSw, pc) :
""" Construct a topology tree for each packet class from src to
prune the Reach relation for unreachable switches"""
swCount = self.topology.getSwitchCount()
maxPathLen = self.topology.getMaxPathLength()
swList = [srcSw]
for k in range(1, maxPathLen + 1) :
newSwList = []
for sw in swList :
neighbours = self.topology.getSwitchNeighbours(sw)
for n in neighbours :
if n not in newSwList :
newSwList.append(n)
self.bfsLists[k] = newSwList
# Set switches not in newSwList to false at Reach(k)
for sw in range(1, swCount+1) :
if sw not in newSwList :
self.z3Solver.add(Not(self.Reach(sw, pc, k)))
swList = newSwList
def addTrafficIsolationConstraints(self, pc1, pc2) :
""" Adding constraints for Isolation Policy enforcement of traffic for packet classes pc1 and pc2 """
swCount = self.topology.getSwitchCount()
useBridgeSlicing = False
# Find bridges for pc1 and pc2.
if self.bridgeSlicingFlag :
# Find if exists in a bridge slice.
srcSlice1 = self.topology.getBridgeSliceNumber(self.pdb.getSourceSwitch(pc1))
dstSlice1 = self.topology.getBridgeSliceNumber(self.pdb.getDestinationSwitch(pc1))
srcSlice2 = self.topology.getBridgeSliceNumber(self.pdb.getSourceSwitch(pc2))
dstSlice2 = self.topology.getBridgeSliceNumber(self.pdb.getDestinationSwitch(pc2))
slice1 = None
slice2 = None
if srcSlice1 == dstSlice1 and srcSlice1 <> None :
slice1 = srcSlice1
if srcSlice2 == dstSlice2 and srcSlice2 <> None :
slice2 = srcSlice2
if slice1 <> None and slice2 <> None :
# Both are in bridge slices.
if slice1 <> slice2:
# pc1 and pc2 will be isolated naturally.
return
if slice1 <> None or slice2 <> None :
# One of them is in a bridge slice. Only add traffic isolation constraints in that slice.
if slice1 <> None :
slice = slice1