idx
int64
0
7.85k
idx_lca
int64
0
223
offset
int64
162
55k
repo
stringclasses
62 values
commit_hash
stringclasses
113 values
target_file
stringclasses
134 values
line_type_lca
stringclasses
7 values
ground_truth
stringlengths
1
46
in_completions
bool
1 class
completion_type
stringclasses
6 values
non_dunder_count_intellij
int64
0
529
non_dunder_count_jedi
int64
0
128
start_with_
bool
2 classes
first_occurrence
bool
2 classes
intellij_completions
listlengths
1
532
jedi_completions
listlengths
3
148
prefix
stringlengths
162
55k
1,019
33
7,942
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__bgp_asns
true
statement
17
17
true
false
[ "__bgp_asns", "bgp", "_ipv4_address", "_full_name", "__subnets", "__init__", "__mtu", "__type", "_name", "full_name", "ipv4_address", "ipv4_network", "mtu", "name", "network_from_sls_data", "subnets", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__bgp_asns", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__mtu", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__subnets", "type": "statement" }, { "name": "__type", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.
1,020
33
8,008
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__bgp_asns
true
statement
17
17
true
false
[ "__bgp_asns", "to_sls", "_full_name", "_ipv4_address", "_name", "__init__", "__mtu", "__subnets", "__type", "bgp", "full_name", "ipv4_address", "ipv4_network", "mtu", "name", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__bgp_asns", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__mtu", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__subnets", "type": "statement" }, { "name": "__type", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.
1,021
33
8,075
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__bgp_asns
true
statement
17
17
true
false
[ "__bgp_asns", "to_sls", "_full_name", "_ipv4_address", "_name", "__init__", "__mtu", "__subnets", "__type", "bgp", "full_name", "ipv4_address", "ipv4_network", "mtu", "name", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__bgp_asns", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__mtu", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__subnets", "type": "statement" }, { "name": "__type", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.
1,022
33
8,400
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
commited
__init__
true
function
17
13
true
true
[ "to_sls", "_full_name", "_name", "name", "ipv4_network", "__bgp_asns", "__init__", "__mtu", "__subnets", "__type", "_ipv4_address", "bgp", "full_name", "ipv4_address", "mtu", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().
1,025
33
8,680
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
mtu
true
function
13
15
false
false
[ "_full_name", "__system_default_route", "name", "ipv4_network", "full_name", "__init__", "bgp", "ipv4_address", "mtu", "network_from_sls_data", "subnets", "system_default_route", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "system_default_route", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__system_default_route", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.
1,027
33
9,199
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__system_default_route
true
statement
13
15
true
true
[ "__system_default_route", "_full_name", "name", "ipv4_network", "mtu", "__init__", "bgp", "full_name", "ipv4_address", "network_from_sls_data", "subnets", "system_default_route", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "system_default_route", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__system_default_route", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.
1,028
33
9,399
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
to_sls
true
function
17
13
false
true
[ "to_sls", "__init__", "mtu", "_name", "__mtu", "__bgp_asns", "__subnets", "__type", "_full_name", "_ipv4_address", "bgp", "full_name", "ipv4_address", "ipv4_network", "name", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().
1,029
33
9,468
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__system_default_route
true
statement
13
15
true
false
[ "__system_default_route", "to_sls", "system_default_route", "_full_name", "mtu", "__init__", "bgp", "full_name", "ipv4_address", "ipv4_network", "name", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "system_default_route", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__system_default_route", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.
1,030
33
9,975
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
commited
__init__
true
function
17
13
true
false
[ "to_sls", "__subnets", "_name", "_ipv4_address", "_full_name", "__bgp_asns", "__init__", "__mtu", "__type", "bgp", "full_name", "ipv4_address", "ipv4_network", "mtu", "name", "network_from_sls_data", "subnets", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().
1,039
33
10,930
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
ipv4_gateway
true
function
27
30
false
true
[ "to_sls", "subnets", "vlan", "full_name", "dhcp_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.
1,040
33
11,013
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
ipv4_gateway
true
function
27
30
false
false
[ "to_sls", "subnets", "subnet_from_sls_data", "name", "ipv4_network", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "metallb_pool_name", "mtu", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.
1,041
33
11,046
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
ipv4_network
true
function
27
30
false
true
[ "to_sls", "ipv4_network", "subnets", "__ipv4_gateway", "ipv4_gateway", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.
1,042
33
11,146
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
name
true
function
27
30
false
false
[ "subnets", "to_sls", "ipv4_gateway", "__ipv4_gateway", "subnet_from_sls_data", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.
1,043
33
11,215
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
full_name
true
function
27
30
false
false
[ "to_sls", "subnets", "vlan", "ipv4_gateway", "name", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_network", "metallb_pool_name", "mtu", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.
1,044
33
11,270
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
vlan
true
function
27
30
false
true
[ "to_sls", "subnets", "full_name", "ipv4_gateway", "dhcp_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "ipv4_address", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.
1,045
33
11,473
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
ipv4_network
true
function
27
30
false
false
[ "to_sls", "subnets", "dhcp_start_address", "__ipv4_dhcp_start_address", "ipv4_network", "__init__", "__ipv4_dhcp_end_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "full_name", "ipv4_address", "ipv4_gateway", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.
1,046
33
11,570
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
dhcp_start_address
true
function
27
30
false
true
[ "to_sls", "subnets", "vlan", "full_name", "dhcp_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.
1,047
33
11,763
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
ipv4_network
true
function
27
30
false
false
[ "to_sls", "dhcp_end_address", "subnets", "__ipv4_dhcp_end_address", "ipv4_network", "__init__", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.
1,048
33
11,858
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
dhcp_end_address
true
function
27
30
false
true
[ "to_sls", "subnets", "vlan", "full_name", "ipv4_gateway", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "ipv4_address", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.
1,049
33
12,085
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
reservation_start_address
true
function
27
30
false
true
[ "to_sls", "subnets", "vlan", "full_name", "dhcp_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.
1,050
33
12,320
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
reservation_end_address
true
function
27
30
false
true
[ "to_sls", "subnets", "vlan", "full_name", "dhcp_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.
1,054
33
13,380
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__vlan
true
statement
27
30
true
true
[ "__vlan", "subnets", "__pool_name", "__ipv4_gateway", "__reservations", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.
1,056
33
13,799
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_gateway
true
statement
27
30
true
true
[ "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__init__", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.
1,058
33
14,361
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_dhcp_start_address
true
statement
27
30
true
true
[ "__ipv4_reservation_start_address", "__ipv4_dhcp_end_address", "__ipv4_reservation_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__init__", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.
1,060
33
14,914
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_dhcp_end_address
true
statement
27
30
true
true
[ "__ipv4_reservation_end_address", "__ipv4_dhcp_start_address", "__ipv4_dhcp_end_address", "__ipv4_reservation_start_address", "__ipv4_gateway", "__init__", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.
1,062
33
15,486
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_start_address
true
statement
27
30
true
true
[ "__reservations", "__ipv4_reservation_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_start_address", "__ipv4_dhcp_end_address", "__init__", "__ipv4_gateway", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.
1,064
33
16,020
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_end_address
true
statement
27
30
true
true
[ "__reservations", "__ipv4_reservation_start_address", "__ipv4_dhcp_end_address", "__ipv4_reservation_end_address", "__ipv4_dhcp_start_address", "__init__", "__ipv4_gateway", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.
1,066
33
16,449
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__pool_name
true
statement
27
30
true
true
[ "__pool_name", "name", "__vlan", "__ipv4_gateway", "__reservations", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.
1,068
33
16,863
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__reservations
true
statement
27
30
true
true
[ "__reservations", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__vlan", "subnets", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__pool_name", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.
1,072
33
17,184
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_gateway
true
statement
28
30
true
false
[ "__ipv4_gateway", "ipv4_gateway", "__ipv4_reservation_start_address", "__ipv4_reservation_end_address", "__ipv4_dhcp_end_address", "__init__", "__ipv4_dhcp_start_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.
1,073
33
17,228
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__vlan
true
statement
28
30
true
false
[ "__vlan", "vlan", "__reservations", "__pool_name", "__ipv4_reservation_end_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_start_address", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.
1,074
33
17,263
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
random
__ipv4_dhcp_start_address
true
statement
27
30
true
false
[ "__reservations", "__pool_name", "vlan", "mtu", "subnets", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.
1,075
33
17,298
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
random
__ipv4_dhcp_end_address
true
statement
27
30
true
false
[ "__ipv4_reservation_end_address", "__ipv4_dhcp_end_address", "__ipv4_reservation_start_address", "ipv4_address", "dhcp_start_address", "__init__", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "full_name", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.
1,076
33
17,382
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_dhcp_start_address
true
statement
28
30
true
false
[ "__ipv4_reservation_start_address", "__ipv4_dhcp_start_address", "dhcp_start_address", "__ipv4_dhcp_end_address", "__ipv4_reservation_end_address", "__init__", "__ipv4_gateway", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.
1,077
33
17,446
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_dhcp_end_address
true
statement
28
30
true
false
[ "__ipv4_dhcp_end_address", "dhcp_end_address", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__ipv4_dhcp_start_address", "__init__", "__ipv4_gateway", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.
1,078
33
17,546
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_start_address
true
statement
28
30
true
false
[ "__ipv4_reservation_end_address", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_reservation_start_address", "__ipv4_gateway", "__init__", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "yield", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.
1,079
33
17,612
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_end_address
true
statement
28
30
true
false
[ "__ipv4_dhcp_end_address", "vlan", "__ipv4_reservation_start_address", "mtu", "subnets", "__init__", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__pool_name", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "to_sls", "type", "yield", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.
1,080
33
17,746
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_start_address
true
statement
28
30
true
false
[ "__ipv4_reservation_start_address", "__reservations", "reservation_start_address", "__ipv4_reservation_end_address", "__ipv4_dhcp_start_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_gateway", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.
1,081
33
17,824
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__ipv4_reservation_end_address
true
statement
28
30
true
false
[ "__ipv4_reservation_end_address", "__reservations", "__ipv4_reservation_start_address", "reservation_end_address", "__ipv4_dhcp_end_address", "__init__", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.__ipv4_reservation_start_address), "ReservationEnd": str(self.
1,082
33
17,918
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__pool_name
true
statement
27
30
true
false
[ "__reservations", "__ipv4_dhcp_start_address", "vlan", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__init__", "__ipv4_dhcp_end_address", "__ipv4_gateway", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.__ipv4_reservation_start_address), "ReservationEnd": str(self.__ipv4_reservation_end_address), } sls.update(range) if self.
1,083
33
17,991
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
common
__pool_name
true
statement
28
30
true
false
[ "__pool_name", "metallb_pool_name", "name", "full_name", "to_sls", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "ipv4_address", "ipv4_gateway", "ipv4_network", "mtu", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "subnets", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.__ipv4_reservation_start_address), "ReservationEnd": str(self.__ipv4_reservation_end_address), } sls.update(range) if self.__pool_name is not None: sls.update({"MetalLBPoolName": self.
1,084
33
18,022
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
Unknown
__reservations
true
statement
27
30
true
false
[ "__ipv4_dhcp_start_address", "__pool_name", "vlan", "mtu", "subnets", "__init__", "__ipv4_dhcp_end_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__reservations", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "name", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "reservations", "subnet_from_sls_data", "to_sls", "type", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.__ipv4_reservation_start_address), "ReservationEnd": str(self.__ipv4_reservation_end_address), } sls.update(range) if self.__pool_name is not None: sls.update({"MetalLBPoolName": self.__pool_name}) if self.
1,085
33
18,127
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/sls_utils/Networks.py
infile
__reservations
true
statement
28
30
true
false
[ "__reservations", "reservations", "subnets", "to_sls", "name", "__init__", "__ipv4_dhcp_end_address", "__ipv4_dhcp_start_address", "__ipv4_gateway", "__ipv4_reservation_end_address", "__ipv4_reservation_start_address", "__pool_name", "__vlan", "bgp", "dhcp_end_address", "dhcp_start_address", "full_name", "ipv4_address", "ipv4_gateway", "ipv4_network", "metallb_pool_name", "mtu", "network_from_sls_data", "reservation_end_address", "reservation_start_address", "subnet_from_sls_data", "type", "vlan", "for", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "bgp", "type": "function" }, { "name": "dhcp_end_address", "type": "function" }, { "name": "dhcp_start_address", "type": "function" }, { "name": "full_name", "type": "function" }, { "name": "ipv4_address", "type": "function" }, { "name": "ipv4_gateway", "type": "function" }, { "name": "ipv4_network", "type": "function" }, { "name": "metallb_pool_name", "type": "function" }, { "name": "mtu", "type": "function" }, { "name": "name", "type": "function" }, { "name": "network_from_sls_data", "type": "function" }, { "name": "reservation_end_address", "type": "function" }, { "name": "reservation_start_address", "type": "function" }, { "name": "reservations", "type": "function" }, { "name": "subnet_from_sls_data", "type": "function" }, { "name": "subnets", "type": "function" }, { "name": "to_sls", "type": "function" }, { "name": "type", "type": "function" }, { "name": "vlan", "type": "function" }, { "name": "_full_name", "type": "statement" }, { "name": "_ipv4_address", "type": "statement" }, { "name": "_name", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__ipv4_dhcp_end_address", "type": "statement" }, { "name": "__ipv4_dhcp_start_address", "type": "statement" }, { "name": "__ipv4_gateway", "type": "statement" }, { "name": "__ipv4_reservation_end_address", "type": "statement" }, { "name": "__ipv4_reservation_start_address", "type": "statement" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__pool_name", "type": "statement" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__reservations", "type": "statement" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" }, { "name": "__vlan", "type": "statement" } ]
# MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """Classes for management of SLS Networks and Subnets.""" from collections import defaultdict import ipaddress from .Reservations import Reservation # A Subnet is a Network inside a Network CIDR range. # A Subnet has IP reservations, a network does not # https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html class Network: """Represent a Network from and SLS data structure.""" def __init__(self, name, network_type, ipv4_address): """Create a Network. Args: name (str): Short name of the network network_type (str): Type of the network: ethernet, etc. ipv4_address: (str): IPv4 CIDR of the network """ self._name = name self._full_name = "" self._ipv4_address = ipaddress.IPv4Interface(ipv4_address) # IPRanges self.__type = network_type self.__mtu = None self.__subnets = defaultdict() self.__bgp_asns = [None, None] # [MyASN, PeerASN] @classmethod def network_from_sls_data(cls, sls_data): """Construct Network and any data-associated Subnets from SLS data. Args: sls_data: SLS data structure used to construct the network Returns: cls: Network object constructed from the SLS data structure """ # "Promote" any ExtraProperties in Networks to ease initialization. if sls_data.get("ExtraProperties"): for key, value in sls_data["ExtraProperties"].items(): sls_data[key] = value del sls_data["ExtraProperties"] # Cover specialty network(s) if sls_data.get("Name") == "BICAN": sls_network = BicanNetwork( default_route_network_name=sls_data.get("SystemDefaultRoute", "CMN"), ) else: # Cover regular networks sls_network = cls( name=sls_data.get("Name"), network_type=sls_data.get("Type"), ipv4_address=sls_data.get("CIDR"), ) sls_network.full_name(sls_data.get("FullName")) # Check that the CIDR is in the IPRange, if IPRange exists. ipv4_range = sls_data.get("IPRanges") if ipv4_range and len(ipv4_range) > 0: temp_address = ipaddress.IPv4Interface(ipv4_range[0]) if temp_address != sls_network.ipv4_address(): print(f"WARNING: CIDR not in IPRanges from input {sls_network.name()}.") sls_network.mtu(sls_data.get("MTU")) subnets = sls_data.get("Subnets", defaultdict()) for subnet in subnets: new_subnet = Subnet.subnet_from_sls_data(subnet) sls_network.subnets().update({new_subnet.name(): new_subnet}) sls_network.bgp(sls_data.get("MyASN", None), sls_data.get("PeerASN")) return sls_network def name(self, network_name=None): """Short name of the network. Args: network_name (str): Short name of the network for the setter Returns: name (str): Short name of the network for the getter """ if network_name is not None: self._name = network_name return self._name def full_name(self, network_name=None): """Long, descriptive name of the network. Args: network_name (str): Full Name of the network for the setter Returns: full_name (str): Full name of the network for the getter """ if network_name is not None: self._full_name = network_name return self._full_name def ipv4_address(self, network_address=None): """IPv4 network addressing. Args: network_address: IPv4 address of the network for the setter Returns: ipv4_address: IPv4 address of the network for the getter """ if network_address is not None: self._ipv4_address = ipaddress.IPv4Interface(network_address) return self._ipv4_address def ipv4_network(self): """IPv4 network of the CIDR, Ranges, etc. Returns: ipv4_address.network: IPv4 network address of the Network. """ return self._ipv4_address.network def mtu(self, network_mtu=None): """MTU of the network. Args: network_mtu (int): MTU of the network for the setter Returns: mtu (int): MTU of the network for the getter """ if network_mtu is not None: self.__mtu = network_mtu return self.__mtu def type(self, network_type=None): """Ethernet or specialty type of the network. Args: network_type (str): Type of the network (ethernet or otherwise) for the setter Returns: type (str): Type of the network for the getter """ if network_type is not None: self.__type = network_type return self.__type def subnets(self, network_subnets=None): """List of subnet objects in the network. Args: network_subnets: A dict of subnets in the network for the setter Returns: subnets: A dict of subnets in the network for the getter """ if network_subnets is not None: self.__subnets = network_subnets return self.__subnets def bgp(self, my_bgp_asn=None, peer_bgp_asn=None): """Network BGP peering properties (optional). Args: my_bgp_asn (int): Local BGP ASN for setter peer_bgp_asn (int): Remote BGP ASN for setter Returns: bgp_asns (list): List containing local and peer BGP ASNs [MyASN, PeerASN] """ if my_bgp_asn is not None: self.__bgp_asns[0] = my_bgp_asn if peer_bgp_asn is not None: self.__bgp_asns[1] = peer_bgp_asn return self.__bgp_asns def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: SLS data structure for the network """ subnets = [x.to_sls() for x in self.__subnets.values()] # TODO: Is the VlanRange a list of used or a min/max? # x vlans = [min(vlans_list), max(vlans_list)] vlans_list = list(dict.fromkeys([x.vlan() for x in self.__subnets.values()])) vlans = vlans_list sls = { "Name": self._name, "FullName": self._full_name, "Type": self.__type, "IPRanges": [str(self._ipv4_address)], "ExtraProperties": { "CIDR": str(self._ipv4_address), "MTU": self.__mtu, "VlanRange": vlans, "Subnets": subnets, }, } if self.__bgp_asns[0] and self.__bgp_asns[1]: sls["ExtraProperties"]["MyASN"] = self.__bgp_asns[0] sls["ExtraProperties"]["PeerASN"] = self.__bgp_asns[1] return sls class BicanNetwork(Network): """A customized BICAN Network.""" def __init__(self, default_route_network_name="CMN"): """Create a new BICAN network. Args: default_route_network_name (str): Name of the user network for BICAN """ super().__init__( name="BICAN", network_type="ethernet", ipv4_address="0.0.0.0/0", ) self._full_name = "System Default Route Network Name for Bifurcated CAN" self.__system_default_route = default_route_network_name self.mtu(network_mtu=9000) def system_default_route(self, default_route_network_name): """Retrieve or set the default route network name. Args: default_route_network_name (str): Name of the BICAN network path [CMN, CAN, CHN] for setter Returns: system_default_route (str): Name of the BICAN network path """ if default_route_network_name in ["CMN", "CAN", "CHN"]: self.__system_default_route = default_route_network_name return self.__system_default_route def to_sls(self): """Serialize the Network to SLS Networks format. Returns: sls: BICAN SLS Network structure """ sls = super().to_sls() sls["ExtraProperties"]["SystemDefaultRoute"] = self.__system_default_route return sls class Subnet(Network): """Subnets are Networks with extra metadata: DHCP info, IP reservations, etc...""" def __init__(self, name, ipv4_address, ipv4_gateway, vlan): """Create a new Subnet. Args: name (str): Name of the subnet ipv4_address (str): IPv4 CIDR of the subnet ipv4_gateway (str): IPv4 address of the network gateway vlan (int): VLAN ID of the subnet """ super().__init__(name=name, network_type=None, ipv4_address=ipv4_address) self.__ipv4_gateway = ipaddress.IPv4Address(ipv4_gateway) self.__vlan = int(vlan) self.__ipv4_dhcp_start_address = None self.__ipv4_dhcp_end_address = None self.__ipv4_reservation_start_address = None self.__ipv4_reservation_end_address = None self.__pool_name = None self.__reservations = {} @classmethod def subnet_from_sls_data(cls, sls_data): """Create a Subnet from SLS data via a factory method. Args: sls_data (dict): Dictionary of Subnet SLS data Returns: cls (sls_utils.Subnet): Subnet constructed from SLS data """ sls_subnet = cls( name=sls_data.get("Name"), ipv4_address=sls_data.get("CIDR"), ipv4_gateway=sls_data.get("Gateway"), vlan=sls_data.get("VlanID"), ) sls_subnet.ipv4_gateway(ipaddress.IPv4Address(sls_data.get("Gateway"))) if sls_subnet.ipv4_gateway() not in sls_subnet.ipv4_network(): print( f"WARNING: Gateway not in Subnet for {sls_subnet.name()} (possibly supernetting).", ) sls_subnet.full_name(sls_data.get("FullName")) sls_subnet.vlan(sls_data.get("VlanID")) dhcp_start = sls_data.get("DHCPStart") if dhcp_start: dhcp_start = ipaddress.IPv4Address(dhcp_start) if dhcp_start not in sls_subnet.ipv4_network(): print("ERROR: DHCP start not in Subnet.") sls_subnet.dhcp_start_address(dhcp_start) dhcp_end = sls_data.get("DHCPEnd") if dhcp_end: dhcp_end = ipaddress.IPv4Address(dhcp_end) if dhcp_end not in sls_subnet.ipv4_network(): print("ERROR: DHCP end not in Subnet.") sls_subnet.dhcp_end_address(dhcp_end) reservation_start = sls_data.get("ReservationStart") if reservation_start is not None: reservation_start = ipaddress.IPv4Address(reservation_start) sls_subnet.reservation_start_address(reservation_start) reservation_end = sls_data.get("ReservationEnd") if reservation_end is not None: reservation_end = ipaddress.IPv4Address(reservation_end) sls_subnet.reservation_end_address(reservation_end) pool_name = sls_data.get("MetalLBPoolName") if pool_name is not None: sls_subnet.metallb_pool_name(pool_name) reservations = sls_data.get("IPReservations", {}) for reservation in reservations: sls_subnet.reservations().update( { reservation.get("Name"): Reservation( name=reservation.get("Name"), ipv4_address=reservation.get("IPAddress"), aliases=list(reservation.get("Aliases", [])), comment=reservation.get("Comment"), ), }, ) return sls_subnet def vlan(self, subnet_vlan=None): """VLAN of the subnet. Args: subnet_vlan (int): Subnet VLAN ID for the setter Returns: vlan (int): Subnet VLAN ID for the getter """ if subnet_vlan is not None: self.__vlan = subnet_vlan return self.__vlan def ipv4_gateway(self, subnet_ipv4_gateway=None): """IPv4 Gateway of the subnet. Args: subnet_ipv4_gateway (str): IPv4 gateway of the subnet for the setter Returns: ipv4_gateway (xxx): IPv4 gateway of the subnet for the getter """ if subnet_ipv4_gateway is not None: self.__ipv4_gateway = subnet_ipv4_gateway return self.__ipv4_gateway def dhcp_start_address(self, subnet_dhcp_start_address=None): """IPv4 starting address if DHCP is used in the subnet. Args: subnet_dhcp_start_address (str): IPv4 start of the DHCP range for setter Returns: ipv4_dhcp_start_address (ipaddress.IPv4Address): Start DHCP address for getter """ if subnet_dhcp_start_address is not None: self.__ipv4_dhcp_start_address = ipaddress.IPv4Address( subnet_dhcp_start_address, ) return self.__ipv4_dhcp_start_address def dhcp_end_address(self, subnet_dhcp_end_address=None): """IPv4 ending address if DHCP is used in the subnet. Args: subnet_dhcp_end_address (str): IPv4 end of the DHCP range for setter Returns: ipv4_dhcp_end_address (ipaddress.IPv4Address): End DHCP address for getter """ if subnet_dhcp_end_address is not None: self.__ipv4_dhcp_end_address = ipaddress.IPv4Address( subnet_dhcp_end_address, ) return self.__ipv4_dhcp_end_address def reservation_start_address(self, reservation_start=None): """IPv4 starting address used in uai_macvlan subnet. Args: reservation_start (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_start_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_start is not None: self.__ipv4_reservation_start_address = ipaddress.IPv4Address( reservation_start, ) return self.__ipv4_reservation_start_address def reservation_end_address(self, reservation_end=None): """IPv4 ending address used in uai_macvlan subnet. Args: reservation_end (ipaddress.IPv4Address): Start address of the reservations Returns: ipv4_reservation_end_address (ipaddress.IPv4Address): Start address of the reservation """ if reservation_end is not None: self.__ipv4_reservation_end_address = ipaddress.IPv4Address(reservation_end) return self.__ipv4_reservation_end_address def metallb_pool_name(self, pool_name=None): """Retrieve or set the MetalLBPool name for the network (optional). Args: pool_name (str): Name of the MetalLBPool (optional) Returns: pool_name (str|None): Name of the MetalLBPool (or None) """ if pool_name is not None: self.__pool_name = pool_name return self.__pool_name def reservations(self, subnet_reservations=None): """List of reservations for the subnet. Args: subnet_reservations (list): List of reservations for setter Returns: reservations (list): Lit of reservations for getter """ if subnet_reservations is not None: self.__reservations = subnet_reservations return self.__reservations def to_sls(self): """Return SLS JSON for each Subnet. Returns: sls: SLS subnet data structure """ sls = { "Name": self._name, "FullName": self._full_name, "CIDR": str(self._ipv4_address), "Gateway": str(self.__ipv4_gateway), "VlanID": self.__vlan, } if self.__ipv4_dhcp_start_address and self.__ipv4_dhcp_end_address: dhcp = { "DHCPStart": str(self.__ipv4_dhcp_start_address), "DHCPEnd": str(self.__ipv4_dhcp_end_address), } sls.update(dhcp) if ( self.__ipv4_reservation_start_address is not None and self.__ipv4_reservation_end_address is not None # noqa W503 ): range = { "ReservationStart": str(self.__ipv4_reservation_start_address), "ReservationEnd": str(self.__ipv4_reservation_end_address), } sls.update(range) if self.__pool_name is not None: sls.update({"MetalLBPoolName": self.__pool_name}) if self.__reservations: reservations = { "IPReservations": [x.to_sls() for x in self.
1,088
36
2,473
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
log_file
true
statement
5
5
false
true
[ "log_file", "error", "info", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.
1,089
36
2,603
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
log_file
true
statement
5
5
false
false
[ "log_file", "info", "error", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.
1,090
36
2,732
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
log_file
true
statement
5
5
false
false
[ "log_file", "info", "error", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.
1,108
36
3,525
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
true
[ "directory", "parent", "ncn_name", "remove_ips", "aliases", "__init__", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "run_ipmitool", "save", "verbose", "workers", "xname", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.
1,109
36
4,065
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
false
[ "directory", "run_ipmitool", "parent", "ncn_name", "remove_ips", "__init__", "aliases", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "save", "verbose", "workers", "xname", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.
1,110
36
4,233
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
false
[ "directory", "parent", "remove_ips", "ncn_name", "aliases", "__init__", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "run_ipmitool", "save", "verbose", "workers", "xname", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.
1,111
36
4,319
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
false
[ "directory", "run_ipmitool", "parent", "remove_ips", "ncn_name", "__init__", "aliases", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "save", "verbose", "workers", "xname", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.
1,112
36
4,364
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
false
[ "directory", "ncn_name", "parent", "remove_ips", "aliases", "__init__", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "run_ipmitool", "save", "verbose", "workers", "xname", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.
1,113
36
4,626
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
directory
true
statement
17
17
false
false
[ "directory", "ncn_name", "verbose", "xname", "parent", "__init__", "aliases", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "remove_ips", "run_ipmitool", "save", "workers", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.
1,114
36
4,674
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
commited
directory
true
statement
17
17
false
false
[ "directory", "ncn_name", "verbose", "xname", "parent", "__init__", "aliases", "bmc_mac", "hsm_macs", "ifnames", "ip_reservation_aliases", "ip_reservation_ips", "ipmi_password", "ipmi_username", "remove_ips", "run_ipmitool", "save", "workers", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "aliases", "type": "statement" }, { "name": "bmc_mac", "type": "statement" }, { "name": "directory", "type": "statement" }, { "name": "hsm_macs", "type": "statement" }, { "name": "ifnames", "type": "statement" }, { "name": "ip_reservation_aliases", "type": "statement" }, { "name": "ip_reservation_ips", "type": "statement" }, { "name": "ipmi_password", "type": "statement" }, { "name": "ipmi_username", "type": "statement" }, { "name": "ncn_name", "type": "statement" }, { "name": "parent", "type": "statement" }, { "name": "remove_ips", "type": "statement" }, { "name": "run_ipmitool", "type": "statement" }, { "name": "save", "type": "function" }, { "name": "verbose", "type": "statement" }, { "name": "workers", "type": "statement" }, { "name": "xname", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.
1,129
36
5,526
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
logs
true
statement
10
10
false
true
[ "logs", "url", "method", "log", "request_body", "__init__", "completed", "get_response_body", "response", "response_body", "success", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.
1,130
36
5,659
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
true
[ "response_body", "response", "request_body", "url", "logs", "__init__", "completed", "get_response_body", "log", "method", "success", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.
1,131
36
5,689
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
false
[ "response_body", "request_body", "response", "url", "logs", "__init__", "completed", "get_response_body", "log", "method", "success", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.
1,132
36
5,728
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
false
[ "response_body", "response", "request_body", "url", "logs", "__init__", "completed", "get_response_body", "log", "method", "success", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.
1,133
36
6,618
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
true
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.
1,134
36
6,654
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.
1,135
36
6,690
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.
1,136
36
6,726
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.
1,137
36
6,790
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.
1,138
36
6,815
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.
1,140
36
6,860
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.
1,142
36
6,902
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.
1,144
36
6,950
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.
1,145
36
6,981
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.
1,147
36
7,042
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.
1,152
36
7,212
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.
1,155
36
7,297
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
true
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.
1,158
36
7,369
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.
1,160
36
7,440
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.
1,164
36
7,538
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.
1,166
36
7,721
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.
1,169
36
7,818
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.
1,171
36
7,882
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.
1,173
36
7,941
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.
1,176
36
8,029
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.
1,179
36
8,122
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.
1,181
36
8,187
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.
1,185
36
8,787
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.
1,186
36
9,310
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
success
true
statement
10
10
false
true
[ "success", "completed", "url", "method", "log", "__init__", "get_response_body", "logs", "request_body", "response", "response_body", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.
1,188
36
9,367
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
commited
response_body
true
statement
10
10
false
false
[ "response_body", "success", "method", "url", "request_body", "__init__", "completed", "get_response_body", "log", "logs", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.
1,189
36
9,456
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response
true
statement
10
10
false
true
[ "success", "log", "url", "logs", "method", "__init__", "completed", "get_response_body", "request_body", "response", "response_body", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.
1,191
36
9,569
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
log
true
function
10
10
false
true
[ "success", "url", "method", "log", "logs", "__init__", "completed", "get_response_body", "request_body", "response", "response_body", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.
1,194
36
9,755
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.
1,195
36
9,802
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.
1,196
36
9,878
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
error
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.
1,198
36
10,029
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.
1,199
36
10,076
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.
1,200
36
10,152
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
error
true
function
5
5
false
false
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.
1,201
36
10,585
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
false
[ "log", "url", "response_body", "logs", "success", "__init__", "completed", "get_response_body", "method", "request_body", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.
1,207
36
11,479
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
log
true
function
10
10
false
false
[ "log", "url", "response_body", "logs", "success", "__init__", "completed", "get_response_body", "method", "request_body", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.
1,211
36
11,849
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
inproject
log
true
function
10
10
false
false
[ "log", "response_body", "url", "logs", "success", "__init__", "completed", "get_response_body", "method", "request_body", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.
1,214
36
11,957
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
inproject
warning
true
function
5
5
false
true
[ "info", "error", "log_file", "init_logger", "warning", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.
1,218
36
12,112
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "log_file", "error", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.warning(f'Expected to find only one alias. Instead found {state.aliases}') if alias_count > 0: state.ncn_name = list(state.aliases)[0] log.
1,220
36
12,150
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
info
true
function
5
5
false
false
[ "info", "error", "log_file", "warning", "init_logger", "__init__", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "error", "type": "function" }, { "name": "info", "type": "function" }, { "name": "init_logger", "type": "function" }, { "name": "log_file", "type": "statement" }, { "name": "warning", "type": "function" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.warning(f'Expected to find only one alias. Instead found {state.aliases}') if alias_count > 0: state.ncn_name = list(state.aliases)[0] log.info(f'xname: {state.xname}') log.
1,226
36
12,908
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
infile
log
true
function
10
10
false
false
[ "log", "url", "response_body", "logs", "success", "__init__", "completed", "get_response_body", "method", "request_body", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.warning(f'Expected to find only one alias. Instead found {state.aliases}') if alias_count > 0: state.ncn_name = list(state.aliases)[0] log.info(f'xname: {state.xname}') log.info(f'ncn name: {state.ncn_name}') if state.ncn_name in NCN_DO_NOT_REMOVE_IPS: state.remove_ips = False # Requires that the parent is known. # The loop through the hardware_list above finds the given node and parent # That is why this must loop through the hardware list again after the loop above. hardware_connectors = [] for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) # Check for nic connections for nic in extra_properties.get("NodeNics", []): if nic == state.parent: hardware_connectors.append(hardware.get('Xname')) state.save(f'sls-hardware-{hardware.get("Xname")}', hardware) hardware_action.
1,232
36
13,927
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
false
[ "url", "response_body", "logs", "success", "log", "__init__", "completed", "get_response_body", "method", "request_body", "response", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.warning(f'Expected to find only one alias. Instead found {state.aliases}') if alias_count > 0: state.ncn_name = list(state.aliases)[0] log.info(f'xname: {state.xname}') log.info(f'ncn name: {state.ncn_name}') if state.ncn_name in NCN_DO_NOT_REMOVE_IPS: state.remove_ips = False # Requires that the parent is known. # The loop through the hardware_list above finds the given node and parent # That is why this must loop through the hardware list again after the loop above. hardware_connectors = [] for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) # Check for nic connections for nic in extra_properties.get("NodeNics", []): if nic == state.parent: hardware_connectors.append(hardware.get('Xname')) state.save(f'sls-hardware-{hardware.get("Xname")}', hardware) hardware_action.log(f'Found Connector Hardware: Xname: {hardware.get("Xname")}, NodeNic: {nic}') type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string == 'Node' and role == 'Management' and sub_role in ['Worker', 'Storage', 'Master']: aliases = extra_properties.get('Aliases', []) for alias in aliases: if alias not in state.aliases: state.workers.add(alias) for connector in hardware_connectors: actions.append(HttpAction('delete', f'{SLS_URL}/hardware/{connector}')) if found_hardware_for_xname: actions.append(HttpAction('delete', f'{SLS_URL}/hardware/{state.xname}')) state.save('sls-hardware', hardware_list) else: log_error_and_exit(actions, f'Failed to find sls hardware entry for xname: {state.xname}') # Find network references for the aliases and the parent networks = json.loads(networks_action.
1,245
36
16,742
cray-hpe__docs-csm
3aeddea9f5df21148c84af36f97fed541a4ab1f5
scripts/operations/node_management/Add_Remove_Replace_NCNs/remove_management_ncn.py
Unknown
response_body
true
statement
10
10
false
false
[ "url", "logs", "log", "success", "method", "__init__", "completed", "get_response_body", "request_body", "response", "response_body", "__annotations__", "__class__", "__delattr__", "__dict__", "__dir__", "__eq__", "__format__", "__getattribute__", "__hash__", "__init_subclass__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__setattr__", "__sizeof__", "__str__", "__subclasshook__", "__doc__", "__module__" ]
[ { "name": "completed", "type": "statement" }, { "name": "get_response_body", "type": "function" }, { "name": "log", "type": "function" }, { "name": "logs", "type": "statement" }, { "name": "method", "type": "statement" }, { "name": "request_body", "type": "statement" }, { "name": "response", "type": "statement" }, { "name": "response_body", "type": "statement" }, { "name": "success", "type": "statement" }, { "name": "url", "type": "statement" }, { "name": "__annotations__", "type": "statement" }, { "name": "__class__", "type": "property" }, { "name": "__delattr__", "type": "function" }, { "name": "__dict__", "type": "statement" }, { "name": "__dir__", "type": "function" }, { "name": "__doc__", "type": "statement" }, { "name": "__eq__", "type": "function" }, { "name": "__format__", "type": "function" }, { "name": "__getattribute__", "type": "function" }, { "name": "__hash__", "type": "function" }, { "name": "__init__", "type": "function" }, { "name": "__init_subclass__", "type": "function" }, { "name": "__module__", "type": "statement" }, { "name": "__ne__", "type": "function" }, { "name": "__new__", "type": "function" }, { "name": "__reduce__", "type": "function" }, { "name": "__reduce_ex__", "type": "function" }, { "name": "__repr__", "type": "function" }, { "name": "__setattr__", "type": "function" }, { "name": "__sizeof__", "type": "function" }, { "name": "__slots__", "type": "statement" }, { "name": "__str__", "type": "function" } ]
#!/usr/bin/env python3 # MIT License # # (C) Copyright [2022] Hewlett Packard Enterprise Development LP # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import pathlib import re import requests import shutil import subprocess import sys import urllib3 BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' # This is the list of NCNs for which the IPs should not be removed from /etc/hosts NCN_DO_NOT_REMOVE_IPS = [ 'ncn-m001', 'ncn-m002', 'ncn-m003', 'ncn-w001', 'ncn-w002', 'ncn-w003', 'ncn-s001', 'ncn-s002', 'ncn-s003', ] class Logger: def __init__(self): self.log_file = None def init_logger(self, log_file, verbose=False): self.log_file = log_file if log_file: if verbose: logging.basicConfig(filename=log_file, filemode='w', level=logging.DEBUG, format='%(levelname)s: %(message)s') else: logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s') # the encoding argument is not in python 3.6.15 # logging.basicConfig(filename=log_file, filemode='w', level=logging.INFO, encoding='utf-8', # format='%(levelname)s: %(message)s') def info(self, message): print(message) if self.log_file: logging.info(message) def warning(self, message): print(f'Warning: {message}') if self.log_file: logging.warning(message) def error(self, message): print(f'Error: {message}') if self.log_file: logging.error(message) log = Logger() class State: def __init__(self, xname=None, directory=None, dry_run=False, verbose=False): self.xname = xname self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_aliases = set() self.ip_reservation_ips = set() self.hsm_macs = set() self.workers = set() self.remove_ips = True self.ifnames = [] self.bmc_mac = None self.verbose = verbose self.ipmi_username = None self.ipmi_password = None self.run_ipmitool = False if directory and xname: self.directory = os.path.join(directory, xname) else: self.directory = directory if self.directory: # todo possibly add check that prevents saved files from being overwritten # file_list = os.listdir(self.directory) # if 'dry-run' in file_list: # # continue because the previous run was a dry-run # pass # elif len(os.listdir(self.directory)) != 0: # print(f'Error: Save directory is not empty: {self.directory}. Use --force option to over write it.') # sys.exit(1) dry_run_flag_file = os.path.join(self.directory, 'dry-run') # remove directory if previous run was a dry run if os.path.exists(dry_run_flag_file): shutil.rmtree(self.directory) # create the directory if not os.path.exists(self.directory): os.makedirs(self.directory) if dry_run: pathlib.Path(dry_run_flag_file).touch() else: if os.path.exists(dry_run_flag_file): os.remove(dry_run_flag_file) def save(self, name, data): if self.directory: file = os.path.join(self.directory, f'{name}.json') with open(file, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose class HttpAction: def __init__(self, method, url, logs=None, request_body="", response_body="", completed=False, success=False): self.method = method self.url = url self.logs = [] if logs is None else logs self.request_body = request_body self.response_body = response_body self.completed = completed self.success = success self.response = None def log(self, message): self.logs.append(message) def get_response_body(self, default_value=None): if default_value is None: return self.response_body if self.response_body: return self.response_body return default_value def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'http://localhost:27778/boot/v1' else: BSS_URL = f'{BASE_URL}/bss/boot/v1' if args.hsm_url: HSM_URL = args.hsm_url elif args.test_urls: HSM_URL = 'http://localhost:27779/hsm/v2' else: HSM_URL = f'{BASE_URL}/smd/hsm/v2' if args.sls_url: SLS_URL = args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls(): log.info(f'BSS_URL: {BSS_URL}') log.info(f'HSM_URL: {HSM_URL}') log.info(f'SLS_URL: {SLS_URL}') log.info(f'KEA_URL: {KEA_URL}') def print_summary(state): log.info('Summary:') log.info(f' Logs: {state.directory}') log.info(f' xname: {state.xname}') log.info(f' ncn_name: {state.ncn_name}') log.info(f' ncn_macs:') log.info(f' ifnames: {", ".join(state.ifnames)}') log.info(f' bmc_mac: {state.bmc_mac if state.bmc_mac else "Unknown"}') def print_action(action): if action.completed: if action.success: log.info(f"Called: {action.method.upper()} {action.url}") else: log.error(f"Failed: {action.method.upper()} {action.url}") log.info(json.dumps(action.response_body, indent=2)) else: log.info(f"Planned: {action.method.upper()} {action.url}") for a_log in action.logs: log.info(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action): if action.has_run: log.info(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.info(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def http_get(session, actions, url, exit_on_error=True): r = session.get(url) action = HttpAction('get', url, response_body=r.text, completed=True) actions.append(action) action.response = r if r.status_code == http.HTTPStatus.OK: action.success = True elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None def add_delete_action_if_component_present(actions, state, session, url, save_file): action = http_get(session, actions, url, exit_on_error=False) if action.success: state.save(save_file, json.loads(action.response_body)) actions.append(HttpAction('delete', url)) not_found = action.response.status_code == http.HTTPStatus.NOT_FOUND if not_found: action.success = True action.log('The item does not need to be deleted, because it does not exist.') def validate_ipmi_config(state): if state.run_ipmitool: if not state.ipmi_password: log.error('IPMI_PASSWORD not set') log.error('The environment variable IPMI_PASSWORD is required') log.error('It should be set to the password of the BMC that is being removed') sys.exit(1) if not state.ipmi_username: log.error('IPMI_USERNAME not set') log.error('The environment variable IPMI_USERNAME is required') log.error('It should be set to the username of the BMC that is being removed') sys.exit(1) def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases found_hardware_for_xname = False hardware_list = json.loads(hardware_action.response_body) for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) if state.xname == hardware['Xname']: type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string != 'Node' or role != 'Management' or sub_role not in ['Worker', 'Storage', 'Master']: log_error_and_exit( actions, f'{state.xname} is Type: {type_string}, Role: {role}, SubRole: {sub_role}. ' + 'The node must be Type: Node, Role: Management, SubRole: one of Worker, Storage, or Master.') found_hardware_for_xname = True state.save(f'sls-hardware-{state.xname}', hardware) state.parent = hardware.get('Parent') hardware_action.log( f'Found Hardware: Xname: {state.xname}, ' + f'Parent: {state.parent}, ' + f'TypeString: {hardware["TypeString"]}, ' + f'Role: {hardware.get("ExtraProperties").get("Role")}') state.aliases.update(extra_properties.get('Aliases', [])) hardware_action.log(f'Aliases: {state.aliases}') alias_count = len(state.aliases) if alias_count != 1: log.warning(f'Expected to find only one alias. Instead found {state.aliases}') if alias_count > 0: state.ncn_name = list(state.aliases)[0] log.info(f'xname: {state.xname}') log.info(f'ncn name: {state.ncn_name}') if state.ncn_name in NCN_DO_NOT_REMOVE_IPS: state.remove_ips = False # Requires that the parent is known. # The loop through the hardware_list above finds the given node and parent # That is why this must loop through the hardware list again after the loop above. hardware_connectors = [] for hardware in hardware_list: extra_properties = hardware.get('ExtraProperties', {}) # Check for nic connections for nic in extra_properties.get("NodeNics", []): if nic == state.parent: hardware_connectors.append(hardware.get('Xname')) state.save(f'sls-hardware-{hardware.get("Xname")}', hardware) hardware_action.log(f'Found Connector Hardware: Xname: {hardware.get("Xname")}, NodeNic: {nic}') type_string = hardware.get('TypeString') role = extra_properties.get('Role') sub_role = extra_properties.get('SubRole') if type_string == 'Node' and role == 'Management' and sub_role in ['Worker', 'Storage', 'Master']: aliases = extra_properties.get('Aliases', []) for alias in aliases: if alias not in state.aliases: state.workers.add(alias) for connector in hardware_connectors: actions.append(HttpAction('delete', f'{SLS_URL}/hardware/{connector}')) if found_hardware_for_xname: actions.append(HttpAction('delete', f'{SLS_URL}/hardware/{state.xname}')) state.save('sls-hardware', hardware_list) else: log_error_and_exit(actions, f'Failed to find sls hardware entry for xname: {state.xname}') # Find network references for the aliases and the parent networks = json.loads(networks_action.response_body) state.save('sls-networks', networks) for network in networks: network_name = network.get("Name") if network_name == 'HSN': # Skip the HSN network. This network is owned by slingshot. continue logs = [] network_has_changes = False extra_properties = network.get('ExtraProperties') subnets = extra_properties['Subnets'] if subnets is None: continue for subnet in subnets: ip_reservations = subnet.get('IPReservations') if ip_reservations is None: continue new_ip_reservations = [] subnet_has_changes = False for ip_reservation in ip_reservations: rname = ip_reservation['Name'] if rname not in state.aliases and rname != state.parent and rname != state.xname: new_ip_reservations.append(ip_reservation) else: subnet_has_changes = True a = ip_reservation.get('Aliases') if a: state.ip_reservation_aliases.update(ip_reservation.get('Aliases')) state.ip_reservation_aliases.add(ip_reservation.get('Name')) state.ip_reservation_ips.add(ip_reservation.get('IPAddress')) if state.remove_ips: logs.append( f'Removed IP Reservation in {network["Name"]} ' + f'in subnet {subnet["Name"]} for {ip_reservation["Name"]}') logs.append( 'IP Reservation Details: ' + f'Name: {ip_reservation.get("Name")}, ' + f'IPAddress: {ip_reservation.get("IPAddress")}, ' + f'Aliases: {ip_reservation.get("Aliases")}') state.save(f'sls-ip-reservation-{network["Name"]}-{subnet["Name"]}-{ip_reservation["Name"]}', ip_reservation) if state.remove_ips and subnet_has_changes: network_has_changes = True subnet['IPReservations'] = new_ip_reservations if state.remove_ips and network_has_changes: request_body = json.dumps(network) action = HttpAction( 'put', f'{SLS_URL}/networks/{network["Name"]}', logs=logs, request_body=request_body) actions.append(action) return actions def create_hsm_actions(session, state): actions = [] # xname ethernet interfaces ethernet_xname_action = http_get(session, actions, f'{HSM_URL}/Inventory/EthernetInterfaces?ComponentId={state.xname}') ethernet_list = json.loads(ethernet_xname_action.