-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtopology_manager.py
1831 lines (1452 loc) · 66.4 KB
/
topology_manager.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
# This file is a part of the The Fog Development Kit (FDK)
#
# Developed by:
# - Colton Powell
# - Christopher Desiniotis
# - Dr. Behnam Dezfouli
#
# In the Internet of Things Research Lab, Santa Clara University, CA, USA
import fdk
import topology
import manager
import copy
import json
import requests as req
import selectors
import socket
import sys
import time
import timeit
import threading
import types
import math
class TopologyManager(manager.Manager):
"""
Manages topologies, constantly querying ODL RESTCONF API's and then updating
them over time (updates are currently WIP). Provides high level API's to
grab information on the stored topology information, as well as the
topology according to the ODL operational data store.
This class:
Does not write flows to switches (See flow_manager.FlowManager)
Does not gather/manage resources (See resource_manager.ResourceManager)
"""
def __init__(self, mgrs, head, ctrlr_ip_addr="localhost",
open_link_capacity=100000000):
# Call Manager constructor
super().__init__(mgrs, head, ctrlr_ip_addr)
# A number which is the reserved bandwidth on all links for any
# free-flowing traffic. Example: For 1Gbps links, you might set this to
# 100000000 bits/sec to allocate 10% of all links to any generic traffic
self.open_link_capacity = open_link_capacity
# Map of topology-id's to actual Topology objects
self.tops = {}
# Map of switch OF id's to topology ID's for fast access
self.switchid_to_oftopid = {}
# Bridge the information between the real and the OVSDB topologies
self.ofid_to_ovsdbid = {}
self.ovsdbid_to_ofid = {}
# Init and update topology data
self.network_topology = None
self.opendaylight_inventory = None
# Greetings which must still be serviced.
# Greetings remain unserviced when a device greets the FDK but has not
# been discovered by ODL
self.unserviced_greetings = {}
# Init functions (Moved outside of Constructor - should be called after
# FlowManager is initialized
# self.update_topology()
# self.init_link_qos()
# Debug: print the topology data
# #print(json.dumps(self.network_topology, indent=3))
def shutdown(self):
super(TopologyManager, self).shutdown()
# Release any held mutexes
for top_id in self.tops:
cur_top = self.tops[top_id]
try:
cur_top.release_mutex(sys._getframe().f_code.co_name)
except RuntimeError:
# Already unlocked - do nothing
pass
self.shutdown_link_qos()
for top_id in self.tops:
# Attempt to close any open sockets
for node_id in self.unserviced_greetings[top_id]:
try:
self.unserviced_greetings[top_id][node_id]["socket"].close()
except BaseException:
pass
# Add other shutdown capabilities here
def get_topology(self, top_id):
""" Return the stored topology object with ID top_id """
return self.tops[top_id]
def get_ovsnode_top_ofid(self, node_id):
cur_node = self.get_ovsnode(node_id)
return cur_node.top_id
def get_ovsnode(self, node_id):
""" Return the OVSNode without specifying which topology it is in. """
cur_top_id = self.switchid_to_oftopid[node_id]
cur_top = self.get_topology(cur_top_id)
cur_node = cur_top.get_node(node_id)
return cur_node
# Get all topologies via RESTCONF
# Returns a list of topologies.
def query_network_topology(self):
""" Get all topology information from ODL """
# URL to grab entire topology
url = ("http://{}:8181/restconf/operational/"
"network-topology:network-topology/").format(self.ctrlr_ip_addr)
# Make the request
resp = req.get(url, auth=("admin", "admin"), headers=self.head)
# Parse and get topology
network_topology = resp.json()["network-topology"]["topology"]
self.update_network_topology(network_topology)
return self.network_topology
def update_network_topology(self, data):
self.network_topology = data
def query_network_topology_node(self, top_id, node_id):
url = ("http://{}:8181/restconf/operational/".format(self.ctrlr_ip_addr) +
"network-topology:network-topology/topology/{}/".format(top_id) +
"node/{}".format(node_id.replace("/", "%2F")))
resp = req.get(url, auth=("admin", "admin"), headers=self.head)
data = resp.json()["node"][0] # check node array, only 1 elem
return data
def get_network_topology(self):
return self.network_topology
def query_opendaylight_inventory(self):
# Create URL
url = ("http://{}:8181/restconf/".format(self.ctrlr_ip_addr) +
"operational/opendaylight-inventory:nodes/")
# Issue and parse the request
resp = req.get(url, auth=("admin", "admin"), headers=self.head)
self.opendaylight_inventory = resp.json()["nodes"]["node"]
return self.opendaylight_inventory
def get_opendaylight_inventory(self):
return self.opendaylight_inventory
def start_topology_update_thread(self, interval=1.0):
""" Spin off a thread that will repeatedly query ODL for changes to the
topology and update the topologies in TopologyManager accordingly """
self.threads["top_update"] = threading.Thread(
target=self.__start_topology_update_loop,
args=(interval, ))
self.threads["top_update"].start()
def __start_topology_update_loop(self, interval):
""" Helper function for start_topology_update_thread """
while True:
start_time = timeit.default_timer()
self.update_topology()
# Not sure why we had another thread spinning off here
# thread = threading.Thread(target=self.update_bandwidth_data,
# args=(top_id, interval, ))
# thread.start()
# thread.join()
elapsed_time = timeit.default_timer() - start_time
if elapsed_time > interval:
fname = sys._getframe().f_code.co_name
#print("{} WARNING: update_topology took {}s > {}s (interval)".
# format(fname, elapsed_time, interval),
# file=sys.stderr)
# return
else:
time.sleep(interval - elapsed_time)
def update_topology(self):
"""
Grab new information and update all topology objects
"""
# Query network-topology and OVSDB API
# Update according to network-topology data returned
# Contains nodes, links, etc.
self.query_network_topology()
# Go through all OF topologies
for top in self.network_topology:
top_id = top["topology-id"]
if top_id.startswith("flow"):
# Create a new topology if this one doesn't already exist
try:
self.tops[top_id]
except KeyError:
self.tops[top_id] = topology.Topology(self)
# Get top data and add any missing nodes (duplicates not added)
cur_top = self.get_topology(top_id)
# Add new nodes
cur_top.acquire_mutex(sys._getframe().f_code.co_name)
for node_data in top["node"]:
node_id = node_data["node-id"]
cur_top.add_node(node_data)
# Construct switch-to-topology id mapping
if isinstance(cur_top.get_node(node_id), topology.OVSNode):
self.switchid_to_oftopid[node_id] = top_id
# # Initialize ARP flows on new switches
# for node_id in cur_top.get_switch_ids():
# flow_mgr = self.mgrs["flow"]
# top_id = self.switchid_to_oftopid[node_id]
# try:
# flow_mgr.flows[node_id][0]
# except KeyError:
# flow_mgr.init_flows(top_id, 0, 1000)
cur_top.release_mutex(sys._getframe().f_code.co_name)
# Check that links exist before attempting to add them
# For tops w/ 1 switch, a KeyError is raised so this is important
try:
top["link"]
except KeyError:
return
# Connect the nodes by checking link information
for link in top["link"]:
# src info
src_node_id = link["source"]["source-node"]
src_is_switch = src_node_id.startswith("openflow")
if src_is_switch:
src_port = link["source"]["source-tp"]
else:
src_port = src_node_id
# dst info
dst_node_id = link["destination"]["dest-node"]
dst_is_switch = dst_node_id.startswith("openflow")
if dst_is_switch:
dst_port = link["destination"]["dest-tp"]
else:
dst_port = dst_node_id
# Add links, specifying the corresponding ports on each device the
# ends of the link are connected to. Will not add the link if
# it already exists.
# cur_top = self.get_topology(top_id)
cur_top.acquire_mutex(sys._getframe().f_code.co_name)
cur_top.add_link(src_node_id, dst_node_id, src_port, dst_port)
cur_top.release_mutex(sys._getframe().f_code.co_name)
# Query opendaylight-inventory:nodes API and update topologies
# Contains information on OVSNode ports and flows
self.query_opendaylight_inventory()
# Go through nodes
for node in self.opendaylight_inventory:
node_id = node["id"]
top_id = self.switchid_to_oftopid[node_id]
cur_top = self.tops[top_id]
cur_node = cur_top.get_node(node_id)
cur_top.acquire_mutex(sys._getframe().f_code.co_name)
for port in node["node-connector"]:
# Save the node connector data
port_ofid = port["id"]
if port_ofid.endswith("LOCAL"):
continue
cur_node.set_node_connector_data(port_ofid, port)
# Relate the port name to the port ofid in the switch
port_name = port["flow-node-inventory:name"]
cur_node.set_portname_to_portofid(port_name, port_ofid)
cur_top.release_mutex(sys._getframe().f_code.co_name)
# Go through OVSDB topologies AFTER OF topologies
for top in self.network_topology:
top_id = top["topology-id"]
if top_id.startswith("ovsdb"):
# Go through nodes in ovsdb topology
for node in top["node"]:
# Only consider bridges (OVSNodes)
try:
# 1-to-1 correspondence between bridge MACs AND OVSNodes
br_uuid = node["ovsdb:bridge-uuid"]
br_name = node["ovsdb:bridge-name"]
br_mac = node["ovsdb:datapath-id"]
br_ovsdb_id = node["node-id"]
ovsdb_id = node["node-id"].rsplit("/", 2)[-3]
tp_info = node["termination-point"]
except KeyError:
continue
# Each bridge is represented as a node in the openflow topology
# So parse bridge name, get MAC addr, and convert to OF id
node_id = "openflow:" + str(self.mac_to_int(br_mac))
# Find the topology where this node is located in:
of_top_id = self.get_of_top_id(top_id) # top_id is an ovsdb top id
cur_top = self.get_topology(of_top_id)
# Update the node with the appropriate information
# Can cause KeyError if manager is set but ctrlr isnt
try:
cur_node = cur_top.nodes[node_id]
except KeyError:
continue
cur_top.acquire_mutex(sys._getframe().f_code.co_name)
cur_node.node_id = node_id
cur_node.top_id = of_top_id
cur_node.ovsdb_top_id = top_id
cur_node.ovsdb_id = ovsdb_id
cur_node.br_ovsdb_id = br_ovsdb_id
cur_node.br_uuid = br_uuid
cur_node.br_name = br_name
cur_node.br_mac = br_mac
new_tp = False
for tp in tp_info:
##print(tp)
# Skip bridges and other non-default ports
if "ovsdb:interface-type" in tp:
continue
# Get ofport of some TP
try:
tp_ofid = node_id + ":" + str(tp["ovsdb:ofport"])
except KeyError:
# Sometimes
tp_name = tp["ovsdb:name"]
tp_ofid = cur_node.get_portofid_from_portname(tp_name)
tp_stats = cur_node.get_node_connector_data(tp_ofid)
if tp_stats is None:
# #print("TPOFPORT NOT FOUND ")
continue
tp_ofid = tp_stats["id"]
# #print("FOUND " + tp_ofid)
# cur_node.port_dict[tp_ofid] = {
# "info": tp,
# "port-qos": {}
# }
# Skip over ports which are already in the dict
# CHANGE: to update fields
if tp_ofid in cur_node.port_dict:
continue
# Otherwise put the new port info in the dict
new_tp = True
cur_node.set_port_data(tp_ofid, {
"termination-point": [
tp
]
})
# Map OVSDB ids to OF ids + vice versa
self.ofid_to_ovsdbid[node_id] = ovsdb_id
self.ovsdbid_to_ofid[ovsdb_id] = node_id
# Not needed since the node data set here is only set here.
# But may assist keeping data consistent between threads
cur_top.release_mutex(sys._getframe().f_code.co_name)
# ==============================================================================
# Greeting Threads
# ==============================================================================
def start_unserviced_greeting_handler(self, top_id="flow:1", interval=1.0):
self.threads["unserviced_greeting_handler"] = threading.Thread(
target=self.__start_unserviced_greeting_handler,
args=(top_id, interval, )
)
self.threads["unserviced_greeting_handler"].start()
def __start_unserviced_greeting_handler(self, top_id="flow:1", interval=1.0):
cur_top = self.get_topology(top_id)
while True:
try:
self.unserviced_greetings[top_id]
except BaseException:
time.sleep(interval)
continue
serviced_nodes = []
cur_top.acquire_mutex()
# Attempt to service all unserviced greetings, if any exist
for node_id in self.unserviced_greetings[top_id]:
greeting_data = self.unserviced_greetings[top_id][node_id]
greeting = greeting_data["greeting"]
sock = greeting_data["socket"]
if self.__service_greeting(top_id, sock, greeting, False):
# note which nodes are successfully serviced
serviced_nodes.append(greeting["node_id"])
# Stop tracking greeting on successful servicing
for node_id in serviced_nodes:
self.untrack_greeting(top_id, node_id)
cur_top.release_mutex()
# Try again in interval seconds
time.sleep(interval)
# Get cpu utilization for fog nodes
def start_greeting_server(self, top_id="flow:1", interval=1.0):
"""
Spin off a thread that will host the server which receives and
processes greetings.
"""
self.threads["greeting"] = threading.Thread(
target=self.__start_greeting_server,
args=(top_id, interval, )
)
self.threads["greeting"].start()
def __start_greeting_server(self, top_id, interval=1.0):
HOST = ""
PORT = 65433
sel = selectors.DefaultSelector()
# Create, bind, and listen on socket
self.socks["greeting"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socks["greeting"].bind((HOST, PORT))
self.socks["greeting"].listen()
#print("listening on", (HOST, PORT))
self.socks["greeting"].setblocking(False)
# Select self.socks["greeting"] for I/O event monitoring
sel.register(self.socks["greeting"], selectors.EVENT_READ, data=None)
while True:
# wait until selector is ready (or timeout expires)
events = sel.select(timeout=None)
# For each file object, process
for key, mask in events:
if key.data is None:
self.accept_wrapper(key.fileobj, sel)
else:
cur_top = self.get_topology(top_id)
cur_top.acquire_mutex(sys._getframe().f_code.co_name)
self.service_greeting(top_id, key, mask, sel)
cur_top.release_mutex(sys._getframe().f_code.co_name)
def accept_wrapper(self, sock, sel):
conn, addr = sock.accept() # Should be ready to read
#print("accepted connection from", addr)
conn.setblocking(False)
data = types.SimpleNamespace(addr=addr, inb=b"", outb=b"")
#events = selectors.EVENT_READ | selectors.EVENT_WRITE
events = selectors.EVENT_READ
try:
sel.register(conn, events, data=data)
except KeyError:
print("WARNING - Socket is already registered. Exiting")
def service_greeting(self, top_id, key, mask, sel):
sock = key.fileobj
data = key.data
if mask & selectors.EVENT_READ:
recv_data = sock.recv(1024) # Should be ready to read
if recv_data:
# Decode the data received
if __debug__:
print("Received data from", data.addr[0])
raw_data = recv_data.decode()
greeting = json.loads(raw_data)
if __debug__:
print(json.dumps(greeting, indent=3))
# Attempt to service the greeting
self.__service_greeting(top_id, sock, greeting, True)
# send ack for greeting
# (moved to __service_greeting, only ACKs once greeting is complete)
# sock.sendall(" ".encode())
else:
if __debug__:
print("closing connection to", data.addr)
sel.unregister(sock)
sock.close()
def __service_greeting(self, top_id, sock, greeting, should_track=True):
# Finally store the data in the topology
cur_top = self.get_topology(top_id) # Get topology
# Parse request
try:
node_id = greeting["node_id"]
host_type = greeting["host_type"]
hostname = greeting["hostname"]
docker_port = greeting["docker_port"]
except KeyError:
fname = sys._getframe().f_code.co_name
print("{} ERROR - Malformed greeting. Skipping.".format(fname),
file=sys.stderr)
return False
try:
cur_top.nodes[node_id]
except KeyError:
# Greeting received before the topology receives it!
# Should track it and service later, unless already tracked
fname = sys._getframe().f_code.co_name
print(("{} WARNING - greeting received from".format(fname) +
"{} which is not in topology {}. ".format(node_id, top_id)),
file=sys.stderr)
if should_track:
self.track_greeting(top_id, sock, greeting)
# Can't yet service
return False
# Update node in the topology
if host_type == "Fog":
cur_top.nodes[node_id] = cur_top.nodes[node_id].create_fog_node()
elif host_type == "Edge":
cur_top.nodes[node_id] = cur_top.nodes[node_id].create_edge_node()
else:
# Bad greeting
return False
cur_top.nodes[node_id].hostname = hostname
cur_top.nodes[node_id].docker_port = docker_port
# Add Fog nodes to docker swarm
if(isinstance(cur_top.nodes[node_id], topology.FogNode)):
# Return if node is already in the swarm
if (node_id in self.mgrs["res"].swarm.nodes):
if __debug__:
print("Received greeting from fog node that is already in the swarm", file=sys.stderr)
return
fog_ip = cur_top.nodes[node_id].ip_addr
fog_port = cur_top.nodes[node_id].docker_port
# TODO: Add docker port for fog node here
self.mgrs["res"].swarm.join_swarm(node_id, fog_ip, fog_port)
# get memory limit from swarm node information
swarm_node = self.mgrs["res"].swarm.nodes[node_id]
mem_max = int(swarm_node["Description"]["Resources"]["MemoryBytes"])
cur_top.nodes[node_id].mem_max = int(mem_max/math.pow(10,6)) # convert to MB
# if __debug__:
# print(cur_top.nodes[node_id].mem_max)
# ACK that the greeting has been successful
sock.sendall(" ".encode())
return True
def track_greeting(self, top_id, socket, greeting):
"""
Tracks a greeting that cannot yet be fulfilled.
Stores information in unserviced_greetings.
"""
node_id = greeting["node_id"]
try:
self.unserviced_greetings[top_id][node_id] = {
"greeting": greeting,
"socket": socket
}
except KeyError:
self.unserviced_greetings[top_id] = {
node_id: {
"greeting": greeting,
"socket": socket
}
}
def untrack_greeting(self, top_id, node_id):
# self.unserviced_greetings[top_id][node_id]["socket"].close()
del self.unserviced_greetings[top_id][node_id]
# ==============================================================================
# Bandwidth Allocation / QoS / Queue API
#
# Do not attach mutexes to these functions
# The RAA/RDA are wrapped in mutexes
# ==============================================================================
# Full process to remove Bandwidth allocation from a port:
# QoS exists on port, and queues exist on the QoS.
# So then we must:
# - Remove queues from the QoS
# - Delete the queues from the Switch
# - Remove the QoS from the port
# - Delete the QoS
def is_queue_operational(self, node_id, q_id):
"""
Return True if the queue is found in the operational data store.
Return False otherwise.
"""
of_top_id = self.switchid_to_oftopid[node_id]
cur_top = self.get_topology(of_top_id)
cur_node = cur_top.get_node(node_id)
ovsdb_top_id = cur_node.ovsdb_top_id
ovsdb_id = cur_node.ovsdb_id
op_node_data = self.query_network_topology_node(ovsdb_top_id, ovsdb_id)
try:
queues = op_node_data["ovsdb:queues"]
except KeyError:
return False # Queue not created
for queue in queues:
if q_id == queue["queue-id"]:
return True
return False
def is_qos_operational(self, node_id, qos_id):
"""
Return True if the QoS is found in the operational data store.
Return False otherwise.
"""
of_top_id = self.switchid_to_oftopid[node_id]
cur_top = self.get_topology(of_top_id)
cur_node = cur_top.get_node(node_id)
ovsdb_top_id = cur_node.ovsdb_top_id
ovsdb_id = cur_node.ovsdb_id
op_node_data = self.query_network_topology_node(ovsdb_top_id, ovsdb_id)
try:
qoses = op_node_data["ovsdb:qos-entries"]
except KeyError:
return False # Qos not created
for qos in qoses:
if qos_id == qos["qos-id"]:
return True
return False
def is_queue_on_qos(self, node_id, q_id, qos_id):
"""
Return True if the queue with id q_id is on the QoS with id qos_id.
Return False otherwise.
Results are based on the contents of the operational data store.
"""
of_top_id = self.switchid_to_oftopid[node_id]
cur_top = self.get_topology(of_top_id)
cur_node = cur_top.get_node(node_id)
ovsdb_top_id = cur_node.ovsdb_top_id
ovsdb_id = cur_node.ovsdb_id
op_node_data = self.query_network_topology_node(ovsdb_top_id, ovsdb_id)
try:
qoses = op_node_data["ovsdb:qos-entries"]
except KeyError:
return False # Qos not created
# Go through QoSes
for qos in qoses:
# On a QoS match, check all of its queues
if qos_id == qos["qos-id"]:
try:
queues = qos["queue-list"]
except KeyError:
return False
for queue in queues:
cur_q_id = queue["queue-ref"].rsplit("'", 2)[-2]
# #print(cur_q_id + " vs " + q_id)
if q_id == cur_q_id:
return True
# Note: returns false for nonexistant qos and/or queues (versus
# throwing error)
return False
def is_qos_on_tp(self, node_id, tp_ofid):
"""
Return True if there is SOME QoS on the specified tp with OF id tp_ofid
Return False otherwise.
Results are based on the contents of the operational data store.
"""
of_top_id = self.switchid_to_oftopid[node_id]
cur_top = self.get_topology(of_top_id)
cur_node = cur_top.get_node(node_id)
ovsdb_top_id = cur_node.ovsdb_top_id
br_ovsdb_id = cur_node.br_ovsdb_id
op_node_data = self.query_network_topology_node(ovsdb_top_id, br_ovsdb_id)
try:
tps = op_node_data["termination-point"]
except KeyError:
return False # No tps -> no QoS on any tp
# Go through the tps:
for tp in tps:
cur_tp_id = tp["tp-id"]
try:
cur_tp_ofid = cur_node.get_portofid_from_portname(cur_tp_id)
except KeyError:
continue
# On a match, go through all QoS'es on the tp
if tp_ofid == cur_tp_ofid:
try:
tp["ovsdb:qos-entry"]
return True
except KeyError:
return False
# Note: returns false for nonexistant qos and/or queues (versus
# throwing error)
return False
# Functions for creating/deleting queues.
def get_queue_skeleton(self):
queue_dict = {
"ovsdb:queues": [
{
# "queue-id": "q0",
"dscp": 25,
"queues-other-config": [
#{
# "queue-other-config-key": "max-rate",
# "queue-other-config-value": "500000"
#}
]
}
]
}
return queue_dict
def set_queue_field(self, queue_dict, key, val):
queue_dict["ovsdb:queues"][0][key] = val
return queue_dict
def add_queue_other_config(self, queue_dict, key, val):
if not isinstance(key, str):
fname = sys._getframe().f_code.co_name
#print(("{} - ERROR: key must be a string".format(fname)),
# file = sys.stderr)
return -1
if not isinstance(val, str):
fname = sys._getframe().f_code.co_name
#print(("{} - ERROR: val must be a string".format(fname)),
# file = sys.stderr)
return -1
queue_dict["ovsdb:queues"][0]["queues-other-config"].append({
"queue-other-config-key": key,
"queue-other-config-value": val
})
return queue_dict
def create_queue(self, node_id, q_id, max_rate):
"""
Create a queue on the OVSNode with node_id.
Check to confirm creation and make repeated requests until the queue is
on the node.
"""
# Create the queue
# print("Creating queue {} on node {}".format(q_id, node_id))
queue_dict = self.__create_queue(node_id, q_id, max_rate)
while True:
# Check that the creation is successful
# Concurrency ensured here since we wait before adding another queue
if self.is_queue_operational(node_id, q_id):
cur_node = self.get_ovsnode(node_id)
cur_top = self.get_topology(cur_node.get_top_id())
cur_node.add_queue(queue_dict)
break
def __create_queue(self, node_id, q_id, max_rate):
#ovsdb_top_id, ovsdb_id, q_id, max_rate):
"""
Helper function to create_queue().
Create a new queue but doesn't double check if it actually exists after.
"""
# Get the necessary data
try:
top_id = self.switchid_to_oftopid[node_id]
except KeyError:
# Not a switch - skip this node
return
cur_top = self.tops[top_id]
cur_node = cur_top.nodes[node_id]
ovsdb_top_id = cur_node.ovsdb_top_id
ovsdb_id = cur_node.ovsdb_id
# Create URL
url = ("http://{}:8181/restconf/config/".format(self.ctrlr_ip_addr) +
"network-topology:network-topology/topology/{}/".format(ovsdb_top_id) +
"node/{}/ovsdb:queues/{}".format(ovsdb_id.replace("/", "%2F"), q_id))
# Create HTTP body data - the payload
queue_dict = self.get_queue_skeleton()
queue_dict = self.set_queue_field(queue_dict, "queue-id", q_id)
queue_dict = self.add_queue_other_config(queue_dict, "max-rate",
str(max_rate))
# if __debug__:
# fname = sys._getframe().f_code.co_name
# print("%s:" % fname)
# print("URL: %s" % url)
# print("JSON:")
# print(json.dumps(queue_dict, indent=4))
# Make the request
resp = req.put(url, auth=("admin", "admin"),
headers=self.head, data=json.dumps(queue_dict))
return queue_dict
def delete_queue(self, node_id, q_id):
""" Delete a queue on the specified node. It must be an OVSNode. """
# print("Deleting queue {} on node {}".format(q_id, node_id))
# Delete the queue
self.__delete_queue(node_id, q_id)
while True:
# Exit once queue is no longer operational
if not self.is_queue_operational(node_id, q_id):
cur_node = self.get_ovsnode(node_id)
cur_node.del_queue(q_id)
break
def __delete_queue(self, node_id, q_id):
"""
Helper function to delete_queue().
Deletes a queue but doesn't double check if it still exists after.
"""
# ovsdb_top_id, ovsdb_id, q_id):
# Get the necessary data
try:
top_id = self.switchid_to_oftopid[node_id]
except KeyError:
# Not a switch - skip this node
return
cur_top = self.tops[top_id]
cur_node = cur_top.nodes[node_id]
ovsdb_top_id = cur_node.ovsdb_top_id
ovsdb_id = cur_node.ovsdb_id
# Create URL
url = ("http://{}:8181/restconf/config/".format(self.ctrlr_ip_addr) +
"network-topology:network-topology/topology/{}/".format(ovsdb_top_id) +
"node/{}/ovsdb:queues/{}".format(ovsdb_id.replace("/", "%2F"), q_id))
# if __debug__:
# fname = sys._getframe().f_code.co_name
# print("%s:" % fname)
# print("URL: %s" % url)
# Make request
resp = req.delete(url, auth=("admin", "admin"), headers=self.head)
def get_qos_skeleton(self):
qos = {
"ovsdb:qos-entries": [
{
# "qos-id": "qos1",
"qos-type": "ovsdb:qos-type-linux-htb",
"qos-other-config": [
# {
# "other-config-key": "max-rate",
# "other-config-value": "10000000"
# }
],
"queue-list": [
# {
# "queue-number": "0",
# "queue-ref": "/network-topology:network-topology/network-topology:topology[network-topology:topology-id='ovsdb:1']/network-topology:node[network-topology:node-id='ovsdb://uuid/c5686a7b-cf19-4bb1-878f-516527c9ffbc']/ovsdb:queues[ovsdb:queue-id='q0']"
# },
# {
# "queue-number": "1",
# "queue-ref": "/network-topology:network-topology/network-topology:topology[network-topology:topology-id='ovsdb:1']/network-topology:node[network-topology:node-id='ovsdb://uuid/c5686a7b-cf19-4bb1-878f-516527c9ffbc']/ovsdb:queues[ovsdb:queue-id='q1']"
# },
# {
# "queue-number": "2",
# "queue-ref": "/network-topology:network-topology/network-topology:topology[network-topology:topology-id='ovsdb:1']/network-topology:node[network-topology:node-id='ovsdb://uuid/c5686a7b-cf19-4bb1-878f-516527c9ffbc']/ovsdb:queues[ovsdb:queue-id='2']"
# }
]
}
]
}
return qos
def set_qos_field(self, qos_dict, key, val):
""" Set a top-level field in the qos_dict. """
qos_dict["ovsdb:qos-entries"][0][key] = val
return qos_dict
def add_qos_other_config(self, qos_dict, key, val):
""" Set qos-other-config in qos_dict """
if not isinstance(key, str):
fname = sys._getframe().f_code.co_name
#print(("{} - ERROR: key must be a string".format(fname)),
# file = sys.stderr)
return -1
if not isinstance(val, str):
fname = sys._getframe().f_code.co_name
#print(("{} - ERROR: val must be a string".format(fname)),
# file = sys.stderr)
return -1
qos_dict["ovsdb:qos-entries"][0]["qos-other-config"].append({
"other-config-key": key,
"other-config-value": val
})
return qos_dict
def create_qos(self, node_id, qos_id, max_rate, qos_dict=None, delete=False):
"""
Create a blank QoS.
Add queues later using the payload generated here.
"""
# print("Creating qos {} on node {}".format(qos_id, node_id))
# Create the QoS
temp = self.__create_qos(node_id, qos_id, max_rate, qos_dict)
qos_dict = temp