-
Notifications
You must be signed in to change notification settings - Fork 25
/
interface.py
2429 lines (2066 loc) · 84.9 KB
/
interface.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
# (C) Copyright 2019-2023 Hewlett Packard Enterprise Development LP.
# Apache License 2.0
import json
import logging
import re
from copy import deepcopy
from urllib.parse import quote_plus, unquote_plus
from warnings import warn
from netaddr import mac_eui48
from netaddr import EUI as MacAddress
from netaddr.core import AddrFormatError
from pyaoscx.exceptions.generic_op_error import GenericOperationError
from pyaoscx.exceptions.parameter_error import ParameterError
from pyaoscx.exceptions.response_error import ResponseError
from pyaoscx.exceptions.verification_error import VerificationError
from pyaoscx.utils import util as utils
from pyaoscx.utils.iptools import overlapping_ips
from pyaoscx.utils.list_attributes import ListDescriptor
import pyaoscx.vrf as vrf_mod
from pyaoscx.ipv6 import Ipv6
from pyaoscx.vlan import Vlan
from pyaoscx.device import Device
from pyaoscx.pyaoscx_module import PyaoscxModule
class Interface(PyaoscxModule):
"""
Provide configuration management for Interface on AOS-CX devices.
"""
base_uri = "system/interfaces"
indices = ["name"]
resource_uri_name = "interfaces"
ip6_addresses = ListDescriptor("ip6_addresses")
def __init__(self, session, name, uri=None, ip6_addresses=[], **kwargs):
self.session = session
self._uri = uri
# List used to determine attributes related to the configuration
self.config_attrs = []
self.materialized = False
# Attribute dictionary used to manage the original data
# obtained from the GET
self.__original_attributes = {}
# Set name, percents name and determine if Interface is a LAG
self.name = ""
self.__set_name(name)
# List of previous interfaces before update
# used to verify if an interface is deleted from lag
self.__prev_interfaces = []
# Set ip6 addresses
self.ip6_addresses = ip6_addresses
# Type required for configuration
self.type = None
# Set type
self.__set_type()
# Check if data should be added to object
if self.__is_special_type:
utils.set_creation_attrs(self, **kwargs)
# Attribute used to know if object was changed recently
self.__modified = False
@property
def modified(self):
return self.__modified
def __set_name(self, name):
"""
Set name attribute in the proper form for Interface object. Also sets
the "percents name"-the name with any special characters replaced
with percent-encodings.
:param name: Interface name.
"""
# Add attributes to class
self.name = None
self.percents_name = None
if r"%2F" in name or r"%2C" in name or r"%3A" in name:
self.name = unquote_plus(name)
self.percents_name = name
else:
self.name = name
self.percents_name = quote_plus(self.name)
def __set_type(self):
"""
Set Interface type when creating an Interface Object.
"""
# Define all patterns
lag_pattern = re.compile(r"lag[0-9]+$")
loopback_pattern = re.compile(r"loopback[0-9]+$")
tunnel_pattern = re.compile(r"tunnel(.*)")
vlan_pattern = re.compile(r"vlan[0-9]+$")
vxlan_pattern = re.compile(r"vxlan(.*)")
# Sets interface as a special type
self.__is_special_type = True
if lag_pattern.match(self.name):
self.type = "lag"
elif loopback_pattern.match(self.name):
self.type = "loopback"
elif tunnel_pattern.match(self.name):
self.type = "tunnel"
elif vlan_pattern.match(self.name):
self.type = "vlan"
elif vxlan_pattern.match(self.name):
self.type = "vxlan"
else:
self.__is_special_type = False
@PyaoscxModule.connected
def get(self, depth=None, selector=None):
"""
Perform a GET call to retrieve data for a Interface table entry.
:param depth: Integer deciding how many levels into the API JSON
that references will be returned.
:param selector: Alphanumeric option to select specific
information to return.
:return: Returns True if no exception is raised.
"""
logging.info("Retrieving %s from switch", self)
depth = depth or self.session.api.default_depth
selector = selector or self.session.api.default_selector
if not self.session.api.valid_depth(depth):
depths = self.session.api.valid_depths
raise Exception("ERROR: Depth should be {0}".format(depths))
if selector not in self.session.api.valid_selectors:
selectors = " ".join(self.session.api.valid_selectors)
raise Exception(
"ERROR: Selector should be one of {0}".format(selectors)
)
payload = {"depth": depth, "selector": selector}
uri = "{0}/{1}".format(Interface.base_uri, self.percents_name)
try:
response = self.session.request("GET", uri, params=payload)
except Exception as e:
raise ResponseError("GET", e)
if not utils._response_ok(response, "GET"):
raise GenericOperationError(response.text, response.status_code)
data = json.loads(response.text)
# Add dictionary as attributes for the object
utils.create_attrs(self, data)
# Determines if the module is configurable
if selector in self.session.api.configurable_selectors:
# Set self.config_attrs and delete ID from it
utils.set_config_attrs(
self, data, "config_attrs", ["name", "type"]
)
# Set original attributes
self.__original_attributes = deepcopy(data)
# Set a list of interfaces as an attribute
if hasattr(self, "interfaces") and self.interfaces is not None:
interfaces_list = []
# Get all URI elements in the form of a list
uri_list = self.session.api.get_uri_from_data(self.interfaces)
for uri in uri_list:
# Create an Interface object
name, interface = Interface.from_uri(self.session, uri)
# Check for circular reference
# No need to get() if it's circular; it is already
# materialized. Just set flag
if name == self.name:
interface.materialized = True
else:
# Materialize interface
interface.get()
# Add interface to list
interfaces_list.append(interface)
# Set list as Interfaces
self.interfaces = interfaces_list
# Set list of previous Interfaces
self.__prev_interfaces = list(self.interfaces)
# Set VRF
if hasattr(self, "vrf") and self.vrf is not None:
# Set VRF as a Vrf object
vrf_obj = vrf_mod.Vrf.from_response(self.session, self.vrf)
self.vrf = vrf_obj
# Materialized VRF
self.vrf.get()
# Set VLAN
if hasattr(self, "vlan_tag") and self.vlan_tag is not None:
# Set vlan_tag as a Vlan object
vlan_obj = Vlan.from_response(self.session, self.vlan_tag)
self.vlan_tag = vlan_obj
# Materialized Vlan
self.vlan_tag.get()
# vlan_trunks
# Set a list of VLANs as an attribute
if hasattr(self, "vlan_trunks") and self.vlan_trunks is not None:
vlan_trunks = []
# Get all URI elements in the form of a list
uri_list = self.session.api.get_uri_from_data(self.vlan_trunks)
for uri in uri_list:
# Create a Vlan object
vlan_id, vlan = Vlan.from_uri(self.session, uri)
# Add VLAN to dictionary
vlan_trunks.append(vlan)
# Set list as VLANs
self.vlan_trunks = vlan_trunks
# Set all ACLs
ACL = self.session.api.get_module_class(self.session, "ACL")
if hasattr(self, "aclmac_in_cfg") and self.aclmac_in_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclmac_in_cfg)
# Materialize Acl object
acl.get()
self.aclmac_in_cfg = acl
if hasattr(self, "aclmac_out_cfg") and self.aclmac_out_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclmac_out_cfg)
# Materialize Acl object
acl.get()
self.aclmac_out_cfg = acl
if hasattr(self, "aclv4_in_cfg") and self.aclv4_in_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv4_in_cfg)
# Materialize Acl object
acl.get()
self.aclv4_in_cfg = acl
if hasattr(self, "aclv4_out_cfg") and self.aclv4_out_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv4_out_cfg)
# Materialize Acl object
acl.get()
self.aclv4_out_cfg = acl
if hasattr(self, "aclv4_routed_in_cfg") and self.aclv4_routed_in_cfg:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv4_routed_in_cfg)
# Materialize Acl object
acl.get()
self.aclv4_routed_in_cfg = acl
if hasattr(self, "aclv4_routed_out_cfg") and self.aclv4_routed_out_cfg:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv4_routed_out_cfg)
# Materialize Acl object
acl.get()
self.aclv4_routed_out_cfg = acl
if hasattr(self, "aclv6_in_cfg") and self.aclv6_in_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv6_in_cfg)
# Materialize Acl object
acl.get()
self.aclv6_in_cfg = acl
if hasattr(self, "aclv6_out_cfg") and self.aclv6_out_cfg is not None:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv6_out_cfg)
# Materialize Acl object
acl.get()
self.aclv6_out_cfg = acl
if hasattr(self, "aclv6_routed_in_cfg") and self.aclv6_routed_in_cfg:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv6_routed_in_cfg)
# Materialize Acl object
acl.get()
self.aclv6_routed_in_cfg = acl
if hasattr(self, "aclv6_routed_out_cfg") and self.aclv6_routed_out_cfg:
# Create Acl object
acl = ACL.from_response(self.session, self.aclv6_routed_out_cfg)
# Materialize Acl object
acl.get()
self.aclv6_routed_out_cfg = acl
# Sets object as materialized
# Information is loaded from the Device
self.materialized = True
if self.ip6_addresses == []:
# Set IPv6 addresses if any
# Loads IPv6 objects already into the Interface
ipv6s = Ipv6.get_all(self.session, self)
for ipv6 in ipv6s.values():
self.ip6_addresses.append(ipv6)
return True
@classmethod
def get_all(cls, session):
"""
Perform a GET call to retrieve all system Interfaces and create.
a dictionary containing each Interface as a Interface Object.
:param cls: Object's class.
:param session: pyaoscx.Session object used to represent a logical
connection to the device.
:return: Dictionary containing Interface's name as key and a Interface
objects as values.
"""
logging.info("Retrieving all %s data from switch", cls.__name__)
try:
response = session.request("GET", Interface.base_uri)
except Exception as e:
raise ResponseError("GET", e)
if not utils._response_ok(response, "GET"):
raise GenericOperationError(response.text, response.status_code)
data = json.loads(response.text)
interfaces_dict = {}
# Get all URI elements in the form of a list
uri_list = session.api.get_uri_from_data(data)
for uri in uri_list:
# Create an Interface object
name, interface = Interface.from_uri(session, uri)
interfaces_dict[name] = interface
return interfaces_dict
@classmethod
def from_response(cls, session, response_data):
"""
Create an Interface object given a response_data related to the
Interface object.
:param cls: Object's class.
:param session: pyaoscx.Session object used to represent a logical
connection to the device.
:param response_data: The response must be a dictionary of the form:
{ "<interface_name>": URL }, with URL:
"/rest/v10.04/system/interfaces/<interface_name>"
:return: Interface object.
"""
interfaces_id_arr = session.api.get_keys(
response_data, Interface.resource_uri_name
)
interface_name = interfaces_id_arr[0]
return session.api.get_module(session, "Interface", interface_name)
@classmethod
def from_uri(cls, session, uri):
"""
Create an Interface object given a interface URI.
:param cls: Object's class.
:param session: pyaoscx.Session object used to represent a logical
connection to the device.
:param uri: a String with a URI.
:return name, interface_obj: tuple containing both the Interface's name
and an Interface object.
"""
# Obtain ID from URI
index_pattern = re.compile(r"(.*)/(?P<index>.+)")
name_percents = index_pattern.match(uri).group("index")
name = unquote_plus(name_percents)
# Create Interface object
interface_obj = session.api.get_module(
session, "Interface", name, uri=uri
)
return name, interface_obj
@classmethod
def get_facts(cls, session):
"""
Perform a GET call to retrieve all Interfaces and their data.
:param cls: Class reference.
:param session: pyaoscx.Session object used to represent a logical
connection to the device.
:return facts: Dictionary containing Interface IDs as keys and
Interface objects as values.
"""
logging.info("Retrieving the switch interfaces facts")
# Set depth
interface_depth = session.api.default_facts_depth
# Build URI
uri = "{0}?depth={1}".format(Interface.base_uri, interface_depth)
try:
# Try to get facts via GET method
response = session.request("GET", uri)
except Exception as e:
raise ResponseError("GET", e)
if not utils._response_ok(response, "GET"):
raise GenericOperationError(response.text, response.status_code)
# Load into json format
facts = json.loads(response.text)
return facts
@PyaoscxModule.connected
def create(self):
"""
Perform a POST call to create an Interface Object. Only returns if no
exception is raised.
:return True if entry was created inside Device.
"""
interface_data = utils.get_attrs(self, self.config_attrs)
interface_data["name"] = self.name
# Set Type
if self.type is not None:
interface_data["type"] = self.type
post_data = json.dumps(interface_data)
try:
response = self.session.request(
"POST", Interface.base_uri, data=post_data
)
except Exception as e:
raise ResponseError("POST", e)
if not utils._response_ok(response, "POST"):
raise GenericOperationError(response.text, response.status_code)
logging.info("SUCCESS: Adding %s", self)
# Get all objects data
self.get()
return True
@PyaoscxModule.connected
def apply(self):
"""
Main method used to update or create a Interface or Port table entry.
Checks whether the Interface exists in the switch. Calls
self.update() if Interface is being updated. Calls self.create() if
a Interface table entry is being created.
:return modified: Boolean, True if object was created or modified.
"""
modified = False
if self.materialized:
modified = self.update()
else:
modified = self.create()
# Set internal attribute
self.__modified = modified
return modified
@PyaoscxModule.connected
def delete(self):
"""
Perform DELETE call to delete Interface table entry.
"""
if "lacp-aggregation-key" in self.other_config:
aggregation_key = self.other_config["lacp-aggregation-key"]
lag = self.session.api.get_module(
self.session, "Interface", "lag{}".format(aggregation_key)
)
try:
lag.get()
lag.remove_port_from_lag(self.name)
except Exception as e:
print(str(e))
if not self.__is_special_type:
self.initialize_interface_entry()
else:
# Delete Interface via a DELETE REQUEST
uri = "{0}/{1}".format(Interface.base_uri, self.name)
try:
response = self.session.request("DELETE", uri)
except Exception as e:
raise ResponseError("DELETE", e)
if not utils._response_ok(response, "DELETE"):
raise GenericOperationError(
response.text, response.status_code
)
# Clean LAG from interfaces
# Delete interface references
for interface in self.__prev_interfaces:
# If interface name is not the same as the current one
if interface.name != self.name and self.type == "lag":
interface.__delete_lag(self)
# Delete object attributes
utils.delete_attrs(self, self.config_attrs)
@PyaoscxModule.connected
def update(self):
"""
Perform a PUT call to apply changes to an existing Interface or Port
table entry.
:return modified: True if Object was modified and a PUT request was
made.
"""
# Variable returned
modified = False
# Get interface PUT data depending on the configuration attributes
# list
iface_data = utils.get_attrs(self, self.config_attrs)
# Check if VRF is inside the data related to interface
if hasattr(self, "vrf") and self.vrf is not None:
# Set VRF in the correct format for PUT
iface_data["vrf"] = (
None
if self.vrf.name == "default"
else self.vrf.get_info_format()
)
# Check if vlan_tag is inside the data related to interface
if hasattr(self, "vlan_tag") and self.vlan_tag is not None:
# Set VLAN in the correct format for PUT
iface_data["vlan_tag"] = self.vlan_tag.get_info_format()
# Set interfaces into correct form
if hasattr(self, "interfaces") and self.interfaces is not None:
formatted_interfaces = {}
# Check for interfaces no longer in LAG
if self.__is_special_type and self.type == "lag":
for element in self.__prev_interfaces:
# If element was deleted from interfaces
if element not in self.interfaces:
# Delete element reference to current LAG
element.__delete_lag(self)
# Set prev interfaces with current ones
# Copies interfaces
self.__prev_interfaces = list(self.interfaces)
# Set interfaces into correct form
for element in self.interfaces:
if isinstance(element, str):
element = self.session.api.get_module(
self.session, "Interface", element
)
element.get()
# If element is the same as current, ignore
if element.name == self.name and self.type == "lag":
pass
else:
# Verify object is materialized
if not element.materialized:
raise VerificationError(
"Interface {0}".format(element.name),
"Object inside interfaces not materialized",
)
if self.type != "lag" or element.__add_member_to_lag(self):
formated_element = element.get_info_format()
formatted_interfaces.update(formated_element)
# Set values in correct form
iface_data["interfaces"] = formatted_interfaces
# Set VLANs into correct form
if "vlan_trunks" in iface_data:
formated_vlans = {}
# Set VLANs into correct form
for element in self.vlan_trunks:
formated_element = element.get_info_format()
formated_vlans.update(formated_element)
# Set values in correct form
iface_data["vlan_trunks"] = formated_vlans
# Set all ACLs
if "aclmac_in_cfg" in iface_data and self.aclmac_in_cfg:
# Set values in correct form
self.aclmac_in_cfg.get()
iface_data["aclmac_in_cfg"] = self.aclmac_in_cfg.get_info_format()
iface_data[
"aclmac_in_cfg_version"
] = self.aclmac_in_cfg_version
if "aclmac_out_cfg" in iface_data and self.aclmac_out_cfg:
# Set values in correct form
self.aclmac_out_cfg.get()
iface_data[
"aclmac_out_cfg"
] = self.aclmac_out_cfg.get_info_format()
iface_data[
"aclmac_out_cfg_version"
] = self.aclmac_out_cfg_version
if "aclv4_in_cfg" in iface_data and self.aclv4_in_cfg:
# Set values in correct form
self.aclv4_in_cfg.get()
iface_data["aclv4_in_cfg"] = self.aclv4_in_cfg.get_info_format()
iface_data["aclv4_in_cfg_version"] = self.aclv4_in_cfg_version
if "aclv4_out_cfg" in iface_data and self.aclv4_out_cfg:
# Set values in correct form
self.aclv4_out_cfg.get()
iface_data["aclv4_out_cfg"] = self.aclv4_out_cfg.get_info_format()
iface_data[
"aclv4_out_cfg_version"
] = self.aclv4_out_cfg_version
if "aclv4_routed_in_cfg" in iface_data and self.aclv4_routed_in_cfg:
# Set values in correct form
self.aclv4_routed_in_cfg.get()
iface_data[
"aclv4_routed_in_cfg"
] = self.aclv4_routed_in_cfg.get_info_format()
iface_data[
"aclv4_routed_in_cfg_version"
] = self.aclv4_routed_in_cfg_version
if "aclv4_routed_out_cfg" in iface_data and self.aclv4_routed_out_cfg:
# Set values in correct form
self.aclv4_routed_out_cfg.get()
iface_data[
"aclv4_routed_out_cfg"
] = self.aclv4_routed_out_cfg.get_info_format()
iface_data[
"aclv4_routed_out_cfg_version"
] = self.aclv4_routed_out_cfg_version
if "aclv6_in_cfg" in iface_data and self.aclv6_in_cfg:
# Set values in correct form
self.aclv6_in_cfg.get()
iface_data["aclv6_in_cfg"] = self.aclv6_in_cfg.get_info_format()
iface_data["aclv6_in_cfg_version"] = self.aclv6_in_cfg_version
if "aclv6_out_cfg" in iface_data and self.aclv6_out_cfg:
# Set values in correct form
self.aclv6_out_cfg.get()
iface_data["aclv6_out_cfg"] = self.aclv6_out_cfg.get_info_format()
iface_data[
"aclv6_out_cfg_version"
] = self.aclv6_out_cfg_version
if "aclv6_routed_in_cfg" in iface_data and self.aclv6_routed_in_cfg:
# Set values in correct form
self.aclv6_routed_in_cfg.get()
iface_data[
"aclv6_routed_in_cfg"
] = self.aclv6_routed_in_cfg.get_info_format()
iface_data[
"aclv6_routed_in_cfg_version"
] = self.aclv6_routed_in_cfg_version
if "aclv6_routed_out_cfg" in iface_data and self.aclv6_routed_out_cfg:
# Set values in correct form
self.aclv6_routed_out_cfg.get()
iface_data[
"aclv6_routed_out_cfg"
] = self.aclv6_routed_out_cfg.get_info_format()
iface_data[
"aclv6_routed_out_cfg_version"
] = self.aclv6_routed_out_cfg_version
uri = "{0}/{1}".format(Interface.base_uri, self.percents_name)
# Compare dictionaries
if iface_data == self.__original_attributes:
# Object was not modified
modified = False
else:
put_data = json.dumps(iface_data)
try:
response = self.session.request("PUT", uri, data=put_data)
except Exception as e:
raise ResponseError("PUT", e)
if not utils._response_ok(response, "PUT"):
raise GenericOperationError(
response.text, response.status_code
)
logging.info("SUCCESS: Updating %s", self)
# Set new original attributes
self.__original_attributes = deepcopy(iface_data)
# Object was modified
modified = True
return modified
@PyaoscxModule.connected
def __add_member_to_lag(self, lag):
"""
Perform PUT calls to configure a Port as a LAG member, and enable it.
:param lag: pyaoscx.Interface object, to which the current port is
being assigned to.
"""
if not lag.materialized:
raise VerificationError(
"LAG {0}".format(lag.name),
"Object is not materialized - Perform get()",
)
lag_name = lag.name
# Extract LAG ID from LAG name
lag_id = int(re.search("\\d+", lag_name).group())
if (
"lacp-aggregation-key" in self.other_config
and self.other_config["lacp-aggregation-key"] != lag_id
):
logging.warning(
"Could not add member to {0}: ".format(lag_name),
"Interface {0} belongs to lag{1}".format(
self.name, self.other_config["lacp-aggregation-key"]
),
)
return False
else:
self.other_config["lacp-aggregation-key"] = lag_id
self.admin_state = lag.admin_state
# Make a POST call and update values
self.update()
return True
@PyaoscxModule.connected
def __delete_lag(self, lag):
"""
Perform PUT calls to update Interface, deleting the LAG reference
inside of the Port that was assigned to that LAG.
:param lag: pyaoscx.Interface object.
"""
if not lag.materialized:
raise VerificationError(
"LAG {0}".format(lag.name),
"Object is not materialized - Perform get()",
)
# Update Values
self.admin_state = "down"
self.other_config.pop("lacp-aggregation-key", None)
# Make a PUT call and update values
self.update()
@PyaoscxModule.deprecated
def get_uri(self):
"""
Method used to obtain the specific Interface URI.
return: Object's URI.
"""
if self._uri is None:
self._uri = "{0}{1}/{2}".format(
self.session.resource_prefix,
Interface.base_uri,
self.percents_name,
)
return self._uri
@PyaoscxModule.deprecated
def get_info_format(self):
"""
Method used to obtain correct object format for referencing inside
other objects.
return: Object format depending on the API Version.
"""
return self.session.api.get_index(self)
def __str__(self):
"""
String containing the Interface name.
:return: This class' string representation.
"""
return "Interface Object, name: '{0}'".format(self.name)
def __set_to_default(self):
"""
Perform a PUT call to set Interface to default settings.
:return: True if object was changed.
"""
# Check for IPv6 addresses and delete them
for address in self.ip6_addresses:
address.delete()
# Clean Attribute
self.ip6_addresses = []
interface_data = {}
# Clear Interfaces
if hasattr(self, "interfaces") and self.interfaces is not None:
if self.__is_special_type and self.name == "lag":
self.interfaces = []
for element in self.__prev_interfaces:
# If element was deleted from interfaces
if element not in self.interfaces:
# Delete element reference to current LAG
try:
element.__delete_lag(self)
except AttributeError:
# Ignore error
pass
else:
self.interfaces = [self]
# Set prev interfaces with current ones
# Copies interfaces
self.__prev_interfaces = list(self.interfaces)
uri = "{0}/{1}".format(Interface.base_uri, self.percents_name)
put_data = json.dumps(interface_data)
try:
response = self.session.request("PUT", uri, data=put_data)
except Exception as e:
raise ResponseError("PUT", e)
if not utils._response_ok(response, "PUT"):
raise GenericOperationError(response.text, response.status_code)
logging.info("SUCCESS: Setting %s default settings", self)
# Update values with new ones
self.get()
return True
@PyaoscxModule.deprecated
def was_modified(self):
"""
Getter method for the __modified attribute.
:return: Boolean True if the object was recently modified.
"""
return self.modified
####################################################################
# IMPERATIVE FUNCTIONS
####################################################################
@PyaoscxModule.materialized
def configure_mclag_options(self, mc_lag=None, lacp_fallback=None):
"""
Configure an Interface object, set its LAG attributes. Requires a
call to apply() afterwards.
:param mc_lag: Boolean to set the LAG as a multi-chassis LAG.
:param lacp_fallback: Boolean to set the LAG's LACP fallback mode.
"""
if not self.__is_special_type:
logging.warning(
"Interface is not a LAG Interface, cannot set MCLAG options"
)
if self.__is_special_type:
if mc_lag is not None:
self.other_config["mclag_enabled"] = mc_lag
if lacp_fallback is not None:
self.other_config["lacp-fallback"] = lacp_fallback
@PyaoscxModule.materialized
def configure_l2(
self,
phys_ports=None,
ipv4=None,
vlan_ids_list=None,
vlan_tag=1,
lacp=None,
description=None,
fallback_enabled=None,
mc_lag=None,
vlan_mode="native-untagged",
trunk_allowed_all=False,
native_vlan_tag=True,
):
"""
Configure an Interface object, set the attributes to a L2 LAG and
apply() changes inside Switch.
:param phys_ports: List of physical ports to aggregate (e.g. ["1/1/1",
"1/1/2", "1/1/3"]) or list of Interface Objects.
:param ipv4: Optional list of IPv4 address to assign to the interface.
If more than one is specified, all addresses except for the first
are added as secondary_ip4. Defaults to nothing if not specified.
Example: ['1.1.1.1', '2.2.2.2']
:param vlan_ids_list: Optional list of integer VLAN IDs or VLAN objects
to add as trunk VLANS. Defaults to empty list if not specified.
:param vlan_tag: Optional VLAN ID or Vlan object to be added as
vlan_tag. Defaults to VLAN 1.
:param lacp: Must be either "passive" or "active." Does not change if
not specified.
:param description: Optional description for the interface. Defaults
to nothing if not specified.
:param fallback_enabled: Boolean to set the LAG's LACP fallback mode.
:param mc_lag: Boolean to set the LAG as a multi-chassis LAG.
:param vlan_mode: Vlan mode on Interface, should be access or trunk
Defaults to 'native-untagged'.
:param trunk_allowed_all: Flag for vlan trunk allowed all on L2
interface, vlan_mode must be set to trunk.
:param native_vlan_tag: Flag for accepting only tagged packets on
VLAN trunk native, vlan_mode must be set to trunk.
:return: True if object was changed.
"""
# Set Physical Ports
if phys_ports is not None:
self.interfaces = []
for port in phys_ports:
port_obj = self.session.api.get_module(
self.session, "Interface", port
)
# Materialize Port
port_obj.get()
self.interfaces.append(port_obj)
if lacp:
self.lacp = lacp
# Set Mode, but keep it as it was if it receives None
if vlan_mode:
self.vlan_mode = vlan_mode
if vlan_mode == "access":
# Convert VLAN Tag into Object
if isinstance(vlan_tag, int):
# Create Vlan object
vlan_tag = Vlan(self.session, vlan_tag)
# Try to get data; if non-existent, throw error
vlan_tag.get()
self.vlan_tag = vlan_tag
# Modify if trunk
elif vlan_mode == "trunk":
if vlan_tag is None:
vlan_tag = 1
# Create Vlan object
vlan_tag = Vlan(self.session, vlan_tag)
# Try to get data; if non-existent, throw error
vlan_tag.get()
# Set VLAN tag
self.vlan_tag = vlan_tag
# Set VLAN mode
if native_vlan_tag:
self.vlan_mode = "native-tagged"
else:
self.vlan_mode = "native-untagged"
if trunk_allowed_all:
self.vlan_trunks = []
else:
# Set VLAN Trunks
if vlan_ids_list is not None:
self.vlan_trunks = []