repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._init_baremetal_trunk_interfaces | def _init_baremetal_trunk_interfaces(self, port_seg, segment):
"""Initialize baremetal switch interfaces and DB entry.
With baremetal transactions, the interfaces are not
known during initialization so they must be initialized
when the transactions are received.
* Reserved switch entries are added if needed.
* Reserved port entries are added.
* Determine if port channel is configured on the
interface and store it so we know to create a port-channel
binding instead of that defined in the transaction.
In this case, the RESERVED binding is the ethernet interface
with port-channel stored in channel-group field.
When this channel-group is not 0, we know to create a port binding
as a port-channel instead of interface ethernet.
"""
# interfaces list requiring switch initialization and
# reserved port and port_binding db entry creation
list_to_init = []
# interfaces list requiring reserved port and port_binding
# db entry creation
inactive_switch = []
connections = self._get_baremetal_connections(
port_seg, False, True)
for switch_ip, intf_type, port, is_native, _ in connections:
try:
nxos_db.get_switch_if_host_mappings(
switch_ip,
nexus_help.format_interface_name(intf_type, port))
except excep.NexusHostMappingNotFound:
if self.is_switch_active(switch_ip):
# channel-group added later
list_to_init.append(
(switch_ip, intf_type, port, is_native, 0))
else:
inactive_switch.append(
(switch_ip, intf_type, port, is_native, 0))
# channel_group is appended to tuples in list_to_init
self.driver.initialize_baremetal_switch_interfaces(list_to_init)
host_id = port_seg.get('dns_name')
if host_id is None:
host_id = const.RESERVED_PORT_HOST_ID
# Add inactive list to list_to_init to create RESERVED
# port data base entries
list_to_init += inactive_switch
for switch_ip, intf_type, port, is_native, ch_grp in list_to_init:
nxos_db.add_host_mapping(
host_id,
switch_ip,
nexus_help.format_interface_name(intf_type, port),
ch_grp, False) | python | def _init_baremetal_trunk_interfaces(self, port_seg, segment):
"""Initialize baremetal switch interfaces and DB entry.
With baremetal transactions, the interfaces are not
known during initialization so they must be initialized
when the transactions are received.
* Reserved switch entries are added if needed.
* Reserved port entries are added.
* Determine if port channel is configured on the
interface and store it so we know to create a port-channel
binding instead of that defined in the transaction.
In this case, the RESERVED binding is the ethernet interface
with port-channel stored in channel-group field.
When this channel-group is not 0, we know to create a port binding
as a port-channel instead of interface ethernet.
"""
# interfaces list requiring switch initialization and
# reserved port and port_binding db entry creation
list_to_init = []
# interfaces list requiring reserved port and port_binding
# db entry creation
inactive_switch = []
connections = self._get_baremetal_connections(
port_seg, False, True)
for switch_ip, intf_type, port, is_native, _ in connections:
try:
nxos_db.get_switch_if_host_mappings(
switch_ip,
nexus_help.format_interface_name(intf_type, port))
except excep.NexusHostMappingNotFound:
if self.is_switch_active(switch_ip):
# channel-group added later
list_to_init.append(
(switch_ip, intf_type, port, is_native, 0))
else:
inactive_switch.append(
(switch_ip, intf_type, port, is_native, 0))
# channel_group is appended to tuples in list_to_init
self.driver.initialize_baremetal_switch_interfaces(list_to_init)
host_id = port_seg.get('dns_name')
if host_id is None:
host_id = const.RESERVED_PORT_HOST_ID
# Add inactive list to list_to_init to create RESERVED
# port data base entries
list_to_init += inactive_switch
for switch_ip, intf_type, port, is_native, ch_grp in list_to_init:
nxos_db.add_host_mapping(
host_id,
switch_ip,
nexus_help.format_interface_name(intf_type, port),
ch_grp, False) | [
"def",
"_init_baremetal_trunk_interfaces",
"(",
"self",
",",
"port_seg",
",",
"segment",
")",
":",
"# interfaces list requiring switch initialization and",
"# reserved port and port_binding db entry creation",
"list_to_init",
"=",
"[",
"]",
"# interfaces list requiring reserved port ... | Initialize baremetal switch interfaces and DB entry.
With baremetal transactions, the interfaces are not
known during initialization so they must be initialized
when the transactions are received.
* Reserved switch entries are added if needed.
* Reserved port entries are added.
* Determine if port channel is configured on the
interface and store it so we know to create a port-channel
binding instead of that defined in the transaction.
In this case, the RESERVED binding is the ethernet interface
with port-channel stored in channel-group field.
When this channel-group is not 0, we know to create a port binding
as a port-channel instead of interface ethernet. | [
"Initialize",
"baremetal",
"switch",
"interfaces",
"and",
"DB",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L806-L862 | train | 37,600 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._get_host_switches | def _get_host_switches(self, host_id):
"""Get switch IPs from configured host mapping.
This method is used to extract switch information
from transactions where VNIC_TYPE is normal.
Information is extracted from ini file which
is stored in _nexus_switches.
:param host_id: host_name from transaction
:returns: list of all switches
:returns: list of only switches which are active
"""
all_switches = set()
active_switches = set()
try:
host_list = nxos_db.get_host_mappings(host_id)
for mapping in host_list:
all_switches.add(mapping.switch_ip)
if self.is_switch_active(mapping.switch_ip):
active_switches.add(mapping.switch_ip)
except excep.NexusHostMappingNotFound:
pass
return list(all_switches), list(active_switches) | python | def _get_host_switches(self, host_id):
"""Get switch IPs from configured host mapping.
This method is used to extract switch information
from transactions where VNIC_TYPE is normal.
Information is extracted from ini file which
is stored in _nexus_switches.
:param host_id: host_name from transaction
:returns: list of all switches
:returns: list of only switches which are active
"""
all_switches = set()
active_switches = set()
try:
host_list = nxos_db.get_host_mappings(host_id)
for mapping in host_list:
all_switches.add(mapping.switch_ip)
if self.is_switch_active(mapping.switch_ip):
active_switches.add(mapping.switch_ip)
except excep.NexusHostMappingNotFound:
pass
return list(all_switches), list(active_switches) | [
"def",
"_get_host_switches",
"(",
"self",
",",
"host_id",
")",
":",
"all_switches",
"=",
"set",
"(",
")",
"active_switches",
"=",
"set",
"(",
")",
"try",
":",
"host_list",
"=",
"nxos_db",
".",
"get_host_mappings",
"(",
"host_id",
")",
"for",
"mapping",
"in... | Get switch IPs from configured host mapping.
This method is used to extract switch information
from transactions where VNIC_TYPE is normal.
Information is extracted from ini file which
is stored in _nexus_switches.
:param host_id: host_name from transaction
:returns: list of all switches
:returns: list of only switches which are active | [
"Get",
"switch",
"IPs",
"from",
"configured",
"host",
"mapping",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L864-L889 | train | 37,601 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._get_host_connections | def _get_host_connections(self, host_id,
only_active_switch=False):
"""Get switch IPs and interfaces from config host mapping.
This method is used to extract switch/interface
information from ini files when VNIC_TYPE is
normal. The ini files contain host to interface
mappings.
:param host_id: Host name from transaction
:param only_active_switch: Indicator for selecting only
connections for switches that are active
:returns: list of switch_ip, intf_type, port_id, is_native
"""
host_found = False
host_connections = []
try:
host_ifs = nxos_db.get_host_mappings(host_id)
except excep.NexusHostMappingNotFound:
host_ifs = []
for ifs in host_ifs:
host_found = True
if (only_active_switch and
not self.is_switch_active(ifs.switch_ip)):
continue
intf_type, port = nexus_help.split_interface_name(
ifs.if_id, ifs.ch_grp)
# is_native set to const.NOT_NATIVE for
# VNIC_TYPE of normal
host_connections.append((
ifs.switch_ip, intf_type, port,
const.NOT_NATIVE, ifs.ch_grp))
if not host_found:
LOG.warning(HOST_NOT_FOUND, host_id)
return host_connections | python | def _get_host_connections(self, host_id,
only_active_switch=False):
"""Get switch IPs and interfaces from config host mapping.
This method is used to extract switch/interface
information from ini files when VNIC_TYPE is
normal. The ini files contain host to interface
mappings.
:param host_id: Host name from transaction
:param only_active_switch: Indicator for selecting only
connections for switches that are active
:returns: list of switch_ip, intf_type, port_id, is_native
"""
host_found = False
host_connections = []
try:
host_ifs = nxos_db.get_host_mappings(host_id)
except excep.NexusHostMappingNotFound:
host_ifs = []
for ifs in host_ifs:
host_found = True
if (only_active_switch and
not self.is_switch_active(ifs.switch_ip)):
continue
intf_type, port = nexus_help.split_interface_name(
ifs.if_id, ifs.ch_grp)
# is_native set to const.NOT_NATIVE for
# VNIC_TYPE of normal
host_connections.append((
ifs.switch_ip, intf_type, port,
const.NOT_NATIVE, ifs.ch_grp))
if not host_found:
LOG.warning(HOST_NOT_FOUND, host_id)
return host_connections | [
"def",
"_get_host_connections",
"(",
"self",
",",
"host_id",
",",
"only_active_switch",
"=",
"False",
")",
":",
"host_found",
"=",
"False",
"host_connections",
"=",
"[",
"]",
"try",
":",
"host_ifs",
"=",
"nxos_db",
".",
"get_host_mappings",
"(",
"host_id",
")"... | Get switch IPs and interfaces from config host mapping.
This method is used to extract switch/interface
information from ini files when VNIC_TYPE is
normal. The ini files contain host to interface
mappings.
:param host_id: Host name from transaction
:param only_active_switch: Indicator for selecting only
connections for switches that are active
:returns: list of switch_ip, intf_type, port_id, is_native | [
"Get",
"switch",
"IPs",
"and",
"interfaces",
"from",
"config",
"host",
"mapping",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L891-L928 | train | 37,602 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._get_switch_interfaces | def _get_switch_interfaces(self, requested_switch_ip, cfg_only=False):
"""Get switch interfaces from host mapping DB.
For a given switch, this returns all known port
interfaces for a given switch. These have been
learned from received baremetal transactions and
from configuration file.
:param requested_switch_ip: switch_ip
:returns: list of switch_ip, intf_type, port_id, is_native
"""
switch_ifs = []
try:
port_info = nxos_db.get_switch_host_mappings(
requested_switch_ip)
except excep.NexusHostMappingNotFound:
port_info = []
for binding in port_info:
if cfg_only and not binding.is_static:
continue
intf_type, port = nexus_help.split_interface_name(
binding.if_id)
switch_ifs.append(
(requested_switch_ip, intf_type, port,
const.NOT_NATIVE, binding.ch_grp))
return switch_ifs | python | def _get_switch_interfaces(self, requested_switch_ip, cfg_only=False):
"""Get switch interfaces from host mapping DB.
For a given switch, this returns all known port
interfaces for a given switch. These have been
learned from received baremetal transactions and
from configuration file.
:param requested_switch_ip: switch_ip
:returns: list of switch_ip, intf_type, port_id, is_native
"""
switch_ifs = []
try:
port_info = nxos_db.get_switch_host_mappings(
requested_switch_ip)
except excep.NexusHostMappingNotFound:
port_info = []
for binding in port_info:
if cfg_only and not binding.is_static:
continue
intf_type, port = nexus_help.split_interface_name(
binding.if_id)
switch_ifs.append(
(requested_switch_ip, intf_type, port,
const.NOT_NATIVE, binding.ch_grp))
return switch_ifs | [
"def",
"_get_switch_interfaces",
"(",
"self",
",",
"requested_switch_ip",
",",
"cfg_only",
"=",
"False",
")",
":",
"switch_ifs",
"=",
"[",
"]",
"try",
":",
"port_info",
"=",
"nxos_db",
".",
"get_switch_host_mappings",
"(",
"requested_switch_ip",
")",
"except",
"... | Get switch interfaces from host mapping DB.
For a given switch, this returns all known port
interfaces for a given switch. These have been
learned from received baremetal transactions and
from configuration file.
:param requested_switch_ip: switch_ip
:returns: list of switch_ip, intf_type, port_id, is_native | [
"Get",
"switch",
"interfaces",
"from",
"host",
"mapping",
"DB",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L940-L968 | train | 37,603 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._configure_nve_db | def _configure_nve_db(self, vni, device_id, mcast_group, host_id):
"""Create the nexus NVE database entry.
Called during update precommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
if not nxos_db.get_nve_vni_member_bindings(vni, switch_ip,
device_id):
nxos_db.add_nexusnve_binding(vni, switch_ip, device_id,
mcast_group) | python | def _configure_nve_db(self, vni, device_id, mcast_group, host_id):
"""Create the nexus NVE database entry.
Called during update precommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
if not nxos_db.get_nve_vni_member_bindings(vni, switch_ip,
device_id):
nxos_db.add_nexusnve_binding(vni, switch_ip, device_id,
mcast_group) | [
"def",
"_configure_nve_db",
"(",
"self",
",",
"vni",
",",
"device_id",
",",
"mcast_group",
",",
"host_id",
")",
":",
"host_nve_connections",
"=",
"self",
".",
"_get_switch_nve_info",
"(",
"host_id",
")",
"for",
"switch_ip",
"in",
"host_nve_connections",
":",
"if... | Create the nexus NVE database entry.
Called during update precommit port event. | [
"Create",
"the",
"nexus",
"NVE",
"database",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L992-L1002 | train | 37,604 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._configure_nve_member | def _configure_nve_member(self, vni, device_id, mcast_group, host_id):
"""Add "member vni" configuration to the NVE interface.
Called during update postcommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
# If configured to set global VXLAN values then
# If this is the first database entry for this switch_ip
# then configure the "interface nve" entry on the switch.
if cfg.CONF.ml2_cisco.vxlan_global_config:
nve_bindings = nxos_db.get_nve_switch_bindings(switch_ip)
if len(nve_bindings) == 1:
LOG.debug("Nexus: create NVE interface")
loopback = self.get_nve_loopback(switch_ip)
self.driver.enable_vxlan_feature(switch_ip,
const.NVE_INT_NUM, loopback)
# If this is the first database entry for this (VNI, switch_ip)
# then configure the "member vni #" entry on the switch.
member_bindings = nxos_db.get_nve_vni_switch_bindings(vni,
switch_ip)
if len(member_bindings) == 1:
LOG.debug("Nexus: add member")
self.driver.create_nve_member(switch_ip, const.NVE_INT_NUM,
vni, mcast_group) | python | def _configure_nve_member(self, vni, device_id, mcast_group, host_id):
"""Add "member vni" configuration to the NVE interface.
Called during update postcommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
# If configured to set global VXLAN values then
# If this is the first database entry for this switch_ip
# then configure the "interface nve" entry on the switch.
if cfg.CONF.ml2_cisco.vxlan_global_config:
nve_bindings = nxos_db.get_nve_switch_bindings(switch_ip)
if len(nve_bindings) == 1:
LOG.debug("Nexus: create NVE interface")
loopback = self.get_nve_loopback(switch_ip)
self.driver.enable_vxlan_feature(switch_ip,
const.NVE_INT_NUM, loopback)
# If this is the first database entry for this (VNI, switch_ip)
# then configure the "member vni #" entry on the switch.
member_bindings = nxos_db.get_nve_vni_switch_bindings(vni,
switch_ip)
if len(member_bindings) == 1:
LOG.debug("Nexus: add member")
self.driver.create_nve_member(switch_ip, const.NVE_INT_NUM,
vni, mcast_group) | [
"def",
"_configure_nve_member",
"(",
"self",
",",
"vni",
",",
"device_id",
",",
"mcast_group",
",",
"host_id",
")",
":",
"host_nve_connections",
"=",
"self",
".",
"_get_switch_nve_info",
"(",
"host_id",
")",
"for",
"switch_ip",
"in",
"host_nve_connections",
":",
... | Add "member vni" configuration to the NVE interface.
Called during update postcommit port event. | [
"Add",
"member",
"vni",
"configuration",
"to",
"the",
"NVE",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1008-L1035 | train | 37,605 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._delete_nve_db | def _delete_nve_db(self, vni, device_id, mcast_group, host_id):
"""Delete the nexus NVE database entry.
Called during delete precommit port event.
"""
rows = nxos_db.get_nve_vni_deviceid_bindings(vni, device_id)
for row in rows:
nxos_db.remove_nexusnve_binding(vni, row.switch_ip, device_id) | python | def _delete_nve_db(self, vni, device_id, mcast_group, host_id):
"""Delete the nexus NVE database entry.
Called during delete precommit port event.
"""
rows = nxos_db.get_nve_vni_deviceid_bindings(vni, device_id)
for row in rows:
nxos_db.remove_nexusnve_binding(vni, row.switch_ip, device_id) | [
"def",
"_delete_nve_db",
"(",
"self",
",",
"vni",
",",
"device_id",
",",
"mcast_group",
",",
"host_id",
")",
":",
"rows",
"=",
"nxos_db",
".",
"get_nve_vni_deviceid_bindings",
"(",
"vni",
",",
"device_id",
")",
"for",
"row",
"in",
"rows",
":",
"nxos_db",
"... | Delete the nexus NVE database entry.
Called during delete precommit port event. | [
"Delete",
"the",
"nexus",
"NVE",
"database",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1037-L1044 | train | 37,606 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._delete_nve_member | def _delete_nve_member(self, vni, device_id, mcast_group, host_id):
"""Remove "member vni" configuration from the NVE interface.
Called during delete postcommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
if not nxos_db.get_nve_vni_switch_bindings(vni, switch_ip):
self.driver.delete_nve_member(switch_ip,
const.NVE_INT_NUM, vni)
if (cfg.CONF.ml2_cisco.vxlan_global_config and
not nxos_db.get_nve_switch_bindings(switch_ip)):
self.driver.disable_vxlan_feature(switch_ip) | python | def _delete_nve_member(self, vni, device_id, mcast_group, host_id):
"""Remove "member vni" configuration from the NVE interface.
Called during delete postcommit port event.
"""
host_nve_connections = self._get_switch_nve_info(host_id)
for switch_ip in host_nve_connections:
if not nxos_db.get_nve_vni_switch_bindings(vni, switch_ip):
self.driver.delete_nve_member(switch_ip,
const.NVE_INT_NUM, vni)
if (cfg.CONF.ml2_cisco.vxlan_global_config and
not nxos_db.get_nve_switch_bindings(switch_ip)):
self.driver.disable_vxlan_feature(switch_ip) | [
"def",
"_delete_nve_member",
"(",
"self",
",",
"vni",
",",
"device_id",
",",
"mcast_group",
",",
"host_id",
")",
":",
"host_nve_connections",
"=",
"self",
".",
"_get_switch_nve_info",
"(",
"host_id",
")",
"for",
"switch_ip",
"in",
"host_nve_connections",
":",
"i... | Remove "member vni" configuration from the NVE interface.
Called during delete postcommit port event. | [
"Remove",
"member",
"vni",
"configuration",
"from",
"the",
"NVE",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1046-L1059 | train | 37,607 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._configure_nxos_db | def _configure_nxos_db(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Create the nexus database entry.
Called during update precommit port event.
"""
connections = self._get_port_connections(port, host_id)
for switch_ip, intf_type, nexus_port, is_native, ch_grp in connections:
port_id = nexus_help.format_interface_name(
intf_type, nexus_port, ch_grp)
try:
nxos_db.get_nexusport_binding(port_id, vlan_id, switch_ip,
device_id)
except excep.NexusPortBindingNotFound:
nxos_db.add_nexusport_binding(port_id, str(vlan_id), str(vni),
switch_ip, device_id,
is_native) | python | def _configure_nxos_db(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Create the nexus database entry.
Called during update precommit port event.
"""
connections = self._get_port_connections(port, host_id)
for switch_ip, intf_type, nexus_port, is_native, ch_grp in connections:
port_id = nexus_help.format_interface_name(
intf_type, nexus_port, ch_grp)
try:
nxos_db.get_nexusport_binding(port_id, vlan_id, switch_ip,
device_id)
except excep.NexusPortBindingNotFound:
nxos_db.add_nexusport_binding(port_id, str(vlan_id), str(vni),
switch_ip, device_id,
is_native) | [
"def",
"_configure_nxos_db",
"(",
"self",
",",
"port",
",",
"vlan_id",
",",
"device_id",
",",
"host_id",
",",
"vni",
",",
"is_provider_vlan",
")",
":",
"connections",
"=",
"self",
".",
"_get_port_connections",
"(",
"port",
",",
"host_id",
")",
"for",
"switch... | Create the nexus database entry.
Called during update precommit port event. | [
"Create",
"the",
"nexus",
"database",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1061-L1077 | train | 37,608 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._gather_config_parms | def _gather_config_parms(self, is_provider_vlan, vlan_id):
"""Collect auto_create, auto_trunk from config."""
if is_provider_vlan:
auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create
auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk
else:
auto_create = True
auto_trunk = True
return auto_create, auto_trunk | python | def _gather_config_parms(self, is_provider_vlan, vlan_id):
"""Collect auto_create, auto_trunk from config."""
if is_provider_vlan:
auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create
auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk
else:
auto_create = True
auto_trunk = True
return auto_create, auto_trunk | [
"def",
"_gather_config_parms",
"(",
"self",
",",
"is_provider_vlan",
",",
"vlan_id",
")",
":",
"if",
"is_provider_vlan",
":",
"auto_create",
"=",
"cfg",
".",
"CONF",
".",
"ml2_cisco",
".",
"provider_vlan_auto_create",
"auto_trunk",
"=",
"cfg",
".",
"CONF",
".",
... | Collect auto_create, auto_trunk from config. | [
"Collect",
"auto_create",
"auto_trunk",
"from",
"config",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1079-L1087 | train | 37,609 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._configure_port_binding | def _configure_port_binding(self, is_provider_vlan, duplicate_type,
is_native,
switch_ip, vlan_id,
intf_type, nexus_port, vni):
"""Conditionally calls vlan and port Nexus drivers."""
# This implies VLAN, VNI, and Port are all duplicate.
# Then there is nothing to configure in Nexus.
if duplicate_type == const.DUPLICATE_PORT:
return
auto_create, auto_trunk = self._gather_config_parms(
is_provider_vlan, vlan_id)
# if type DUPLICATE_VLAN, don't create vlan
if duplicate_type == const.DUPLICATE_VLAN:
auto_create = False
if auto_create and auto_trunk:
LOG.debug("Nexus: create vlan %s and add to interface", vlan_id)
self.driver.create_and_trunk_vlan(
switch_ip, vlan_id, intf_type,
nexus_port, vni, is_native)
elif auto_create:
LOG.debug("Nexus: create vlan %s", vlan_id)
self.driver.create_vlan(switch_ip, vlan_id, vni)
elif auto_trunk:
LOG.debug("Nexus: trunk vlan %s", vlan_id)
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, vlan_id,
intf_type, nexus_port, is_native) | python | def _configure_port_binding(self, is_provider_vlan, duplicate_type,
is_native,
switch_ip, vlan_id,
intf_type, nexus_port, vni):
"""Conditionally calls vlan and port Nexus drivers."""
# This implies VLAN, VNI, and Port are all duplicate.
# Then there is nothing to configure in Nexus.
if duplicate_type == const.DUPLICATE_PORT:
return
auto_create, auto_trunk = self._gather_config_parms(
is_provider_vlan, vlan_id)
# if type DUPLICATE_VLAN, don't create vlan
if duplicate_type == const.DUPLICATE_VLAN:
auto_create = False
if auto_create and auto_trunk:
LOG.debug("Nexus: create vlan %s and add to interface", vlan_id)
self.driver.create_and_trunk_vlan(
switch_ip, vlan_id, intf_type,
nexus_port, vni, is_native)
elif auto_create:
LOG.debug("Nexus: create vlan %s", vlan_id)
self.driver.create_vlan(switch_ip, vlan_id, vni)
elif auto_trunk:
LOG.debug("Nexus: trunk vlan %s", vlan_id)
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, vlan_id,
intf_type, nexus_port, is_native) | [
"def",
"_configure_port_binding",
"(",
"self",
",",
"is_provider_vlan",
",",
"duplicate_type",
",",
"is_native",
",",
"switch_ip",
",",
"vlan_id",
",",
"intf_type",
",",
"nexus_port",
",",
"vni",
")",
":",
"# This implies VLAN, VNI, and Port are all duplicate.",
"# Then... | Conditionally calls vlan and port Nexus drivers. | [
"Conditionally",
"calls",
"vlan",
"and",
"port",
"Nexus",
"drivers",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1089-L1119 | train | 37,610 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._get_compressed_vlan_list | def _get_compressed_vlan_list(self, pvlan_ids):
"""Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])
Returned compressed XML list:
----------------------------
1 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30', '50']
2 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30',
'50', '87-88']
"""
if not pvlan_ids:
return []
pvlan_list = list(pvlan_ids)
pvlan_list.sort()
compressed_list = []
begin = -1
prev_vlan = -1
for port_vlan in pvlan_list:
if prev_vlan == -1:
prev_vlan = port_vlan
else:
if (port_vlan - prev_vlan) == 1:
if begin == -1:
begin = prev_vlan
prev_vlan = port_vlan
else:
if begin == -1:
compressed_list.append(str(prev_vlan))
else:
compressed_list.append("%d-%d" % (begin, prev_vlan))
begin = -1
prev_vlan = port_vlan
if begin == -1:
compressed_list.append(str(prev_vlan))
else:
compressed_list.append("%s-%s" % (begin, prev_vlan))
return compressed_list | python | def _get_compressed_vlan_list(self, pvlan_ids):
"""Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])
Returned compressed XML list:
----------------------------
1 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30', '50']
2 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30',
'50', '87-88']
"""
if not pvlan_ids:
return []
pvlan_list = list(pvlan_ids)
pvlan_list.sort()
compressed_list = []
begin = -1
prev_vlan = -1
for port_vlan in pvlan_list:
if prev_vlan == -1:
prev_vlan = port_vlan
else:
if (port_vlan - prev_vlan) == 1:
if begin == -1:
begin = prev_vlan
prev_vlan = port_vlan
else:
if begin == -1:
compressed_list.append(str(prev_vlan))
else:
compressed_list.append("%d-%d" % (begin, prev_vlan))
begin = -1
prev_vlan = port_vlan
if begin == -1:
compressed_list.append(str(prev_vlan))
else:
compressed_list.append("%s-%s" % (begin, prev_vlan))
return compressed_list | [
"def",
"_get_compressed_vlan_list",
"(",
"self",
",",
"pvlan_ids",
")",
":",
"if",
"not",
"pvlan_ids",
":",
"return",
"[",
"]",
"pvlan_list",
"=",
"list",
"(",
"pvlan_ids",
")",
"pvlan_list",
".",
"sort",
"(",
")",
"compressed_list",
"=",
"[",
"]",
"begin"... | Generate a compressed vlan list ready for XML using a vlan set.
Sample Use Case:
Input vlan set:
--------------
1 - s = set([11, 50, 25, 30, 15, 16, 3, 8, 2, 1])
2 - s = set([87, 11, 50, 25, 30, 15, 16, 3, 8, 2, 1, 88])
Returned compressed XML list:
----------------------------
1 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30', '50']
2 - compressed_list = ['1-3', '8', '11', '15-16', '25', '30',
'50', '87-88'] | [
"Generate",
"a",
"compressed",
"vlan",
"list",
"ready",
"for",
"XML",
"using",
"a",
"vlan",
"set",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1121-L1166 | train | 37,611 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._restore_port_binding | def _restore_port_binding(self,
switch_ip, pvlan_ids,
port, native_vlan):
"""Restores a set of vlans for a given port."""
intf_type, nexus_port = nexus_help.split_interface_name(port)
# If native_vlan is configured, this is isolated since
# two configs (native + trunk) must be sent for this vlan only.
if native_vlan != 0:
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, native_vlan,
intf_type, nexus_port, True)
# If this is the only vlan
if len(pvlan_ids) == 1:
return
concat_vlans = ''
compressed_vlans = self._get_compressed_vlan_list(pvlan_ids)
for pvlan in compressed_vlans:
if concat_vlans == '':
concat_vlans = "%s" % pvlan
else:
concat_vlans += ",%s" % pvlan
# if string starts getting a bit long, send it.
if len(concat_vlans) >= const.CREATE_PORT_VLAN_LENGTH:
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, concat_vlans,
intf_type, nexus_port, False)
concat_vlans = ''
# Send remaining vlans if any
if len(concat_vlans):
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, concat_vlans,
intf_type, nexus_port, False) | python | def _restore_port_binding(self,
switch_ip, pvlan_ids,
port, native_vlan):
"""Restores a set of vlans for a given port."""
intf_type, nexus_port = nexus_help.split_interface_name(port)
# If native_vlan is configured, this is isolated since
# two configs (native + trunk) must be sent for this vlan only.
if native_vlan != 0:
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, native_vlan,
intf_type, nexus_port, True)
# If this is the only vlan
if len(pvlan_ids) == 1:
return
concat_vlans = ''
compressed_vlans = self._get_compressed_vlan_list(pvlan_ids)
for pvlan in compressed_vlans:
if concat_vlans == '':
concat_vlans = "%s" % pvlan
else:
concat_vlans += ",%s" % pvlan
# if string starts getting a bit long, send it.
if len(concat_vlans) >= const.CREATE_PORT_VLAN_LENGTH:
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, concat_vlans,
intf_type, nexus_port, False)
concat_vlans = ''
# Send remaining vlans if any
if len(concat_vlans):
self.driver.send_enable_vlan_on_trunk_int(
switch_ip, concat_vlans,
intf_type, nexus_port, False) | [
"def",
"_restore_port_binding",
"(",
"self",
",",
"switch_ip",
",",
"pvlan_ids",
",",
"port",
",",
"native_vlan",
")",
":",
"intf_type",
",",
"nexus_port",
"=",
"nexus_help",
".",
"split_interface_name",
"(",
"port",
")",
"# If native_vlan is configured, this is isola... | Restores a set of vlans for a given port. | [
"Restores",
"a",
"set",
"of",
"vlans",
"for",
"a",
"given",
"port",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1168-L1205 | train | 37,612 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._restore_vxlan_entries | def _restore_vxlan_entries(self, switch_ip, vlans):
"""Restore vxlan entries on a Nexus switch."""
count = 1
conf_str = ''
vnsegment_sent = 0
path_str, conf_str = self.driver.start_create_vlan()
# At this time, this will only configure vni information when needed
while vnsegment_sent < const.CREATE_VLAN_BATCH and vlans:
vlan_id, vni = vlans.pop(0)
# Add it to the batch
conf_str = self.driver.get_create_vlan(
switch_ip, vlan_id, vni, conf_str)
# batch size has been met
if (count == const.CREATE_VLAN_SEND_SIZE):
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
vnsegment_sent += count
conf_str = ''
count = 1
else:
count += 1
# batch size was not met
if conf_str:
vnsegment_sent += count
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
conf_str = ''
LOG.debug("Switch %s VLAN vn-segment replay summary: %d",
switch_ip, vnsegment_sent) | python | def _restore_vxlan_entries(self, switch_ip, vlans):
"""Restore vxlan entries on a Nexus switch."""
count = 1
conf_str = ''
vnsegment_sent = 0
path_str, conf_str = self.driver.start_create_vlan()
# At this time, this will only configure vni information when needed
while vnsegment_sent < const.CREATE_VLAN_BATCH and vlans:
vlan_id, vni = vlans.pop(0)
# Add it to the batch
conf_str = self.driver.get_create_vlan(
switch_ip, vlan_id, vni, conf_str)
# batch size has been met
if (count == const.CREATE_VLAN_SEND_SIZE):
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
vnsegment_sent += count
conf_str = ''
count = 1
else:
count += 1
# batch size was not met
if conf_str:
vnsegment_sent += count
conf_str = self.driver.end_create_vlan(conf_str)
self.driver.send_edit_string(switch_ip, path_str, conf_str)
conf_str = ''
LOG.debug("Switch %s VLAN vn-segment replay summary: %d",
switch_ip, vnsegment_sent) | [
"def",
"_restore_vxlan_entries",
"(",
"self",
",",
"switch_ip",
",",
"vlans",
")",
":",
"count",
"=",
"1",
"conf_str",
"=",
"''",
"vnsegment_sent",
"=",
"0",
"path_str",
",",
"conf_str",
"=",
"self",
".",
"driver",
".",
"start_create_vlan",
"(",
")",
"# At... | Restore vxlan entries on a Nexus switch. | [
"Restore",
"vxlan",
"entries",
"on",
"a",
"Nexus",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1207-L1238 | train | 37,613 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._configure_port_entries | def _configure_port_entries(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Create a nexus switch entry.
if needed, create a VLAN in the appropriate switch or port and
configure the appropriate interfaces for this VLAN.
Called during update postcommit port event.
"""
connections = self._get_active_port_connections(port, host_id)
# (nexus_port,switch_ip) will be unique in each iteration.
# But switch_ip will repeat if host has >1 connection to same switch.
# So track which switch_ips already have vlan created in this loop.
vlan_already_created = []
starttime = time.time()
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
try:
all_bindings = nxos_db.get_nexusvlan_binding(
vlan_id, switch_ip)
except excep.NexusPortBindingNotFound:
LOG.warning("Switch %(switch_ip)s and Vlan "
"%(vlan_id)s not found in port binding "
"database. Skipping this update",
{'switch_ip': switch_ip, 'vlan_id': vlan_id})
continue
previous_bindings = [row for row in all_bindings
if row.instance_id != device_id]
if previous_bindings and (switch_ip in vlan_already_created):
duplicate_type = const.DUPLICATE_VLAN
else:
vlan_already_created.append(switch_ip)
duplicate_type = const.NO_DUPLICATE
port_starttime = time.time()
try:
self._configure_port_binding(
is_provider_vlan, duplicate_type,
is_native,
switch_ip, vlan_id,
intf_type, nexus_port,
vni)
except Exception:
with excutils.save_and_reraise_exception():
self.driver.capture_and_print_timeshot(
port_starttime, "port_configerr",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "configerr",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
port_starttime, "port_config",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "config") | python | def _configure_port_entries(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Create a nexus switch entry.
if needed, create a VLAN in the appropriate switch or port and
configure the appropriate interfaces for this VLAN.
Called during update postcommit port event.
"""
connections = self._get_active_port_connections(port, host_id)
# (nexus_port,switch_ip) will be unique in each iteration.
# But switch_ip will repeat if host has >1 connection to same switch.
# So track which switch_ips already have vlan created in this loop.
vlan_already_created = []
starttime = time.time()
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
try:
all_bindings = nxos_db.get_nexusvlan_binding(
vlan_id, switch_ip)
except excep.NexusPortBindingNotFound:
LOG.warning("Switch %(switch_ip)s and Vlan "
"%(vlan_id)s not found in port binding "
"database. Skipping this update",
{'switch_ip': switch_ip, 'vlan_id': vlan_id})
continue
previous_bindings = [row for row in all_bindings
if row.instance_id != device_id]
if previous_bindings and (switch_ip in vlan_already_created):
duplicate_type = const.DUPLICATE_VLAN
else:
vlan_already_created.append(switch_ip)
duplicate_type = const.NO_DUPLICATE
port_starttime = time.time()
try:
self._configure_port_binding(
is_provider_vlan, duplicate_type,
is_native,
switch_ip, vlan_id,
intf_type, nexus_port,
vni)
except Exception:
with excutils.save_and_reraise_exception():
self.driver.capture_and_print_timeshot(
port_starttime, "port_configerr",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "configerr",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
port_starttime, "port_config",
switch=switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "config") | [
"def",
"_configure_port_entries",
"(",
"self",
",",
"port",
",",
"vlan_id",
",",
"device_id",
",",
"host_id",
",",
"vni",
",",
"is_provider_vlan",
")",
":",
"connections",
"=",
"self",
".",
"_get_active_port_connections",
"(",
"port",
",",
"host_id",
")",
"# (... | Create a nexus switch entry.
if needed, create a VLAN in the appropriate switch or port and
configure the appropriate interfaces for this VLAN.
Called during update postcommit port event. | [
"Create",
"a",
"nexus",
"switch",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1240-L1296 | train | 37,614 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.configure_next_batch_of_vlans | def configure_next_batch_of_vlans(self, switch_ip):
"""Get next batch of vlans and send them to Nexus."""
next_range = self._pop_vlan_range(
switch_ip, const.CREATE_VLAN_BATCH)
if next_range:
try:
self.driver.set_all_vlan_states(
switch_ip, next_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vlan_range(switch_ip, [])
vxlan_range = self._get_switch_vxlan_range(switch_ip)
if vxlan_range:
try:
self._restore_vxlan_entries(switch_ip, vxlan_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vxlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vxlan_range(switch_ip, [])
# if no more vlans to restore, we're done. go active.
if (not self._get_switch_vlan_range(switch_ip) and
not self._get_switch_vxlan_range(switch_ip)):
self.set_switch_ip_and_active_state(
switch_ip, const.SWITCH_ACTIVE)
LOG.info("Restore of Nexus switch "
"ip %(switch_ip)s is complete",
{'switch_ip': switch_ip})
else:
LOG.debug(("Restored batch of VLANS on "
"Nexus switch ip %(switch_ip)s"),
{'switch_ip': switch_ip}) | python | def configure_next_batch_of_vlans(self, switch_ip):
"""Get next batch of vlans and send them to Nexus."""
next_range = self._pop_vlan_range(
switch_ip, const.CREATE_VLAN_BATCH)
if next_range:
try:
self.driver.set_all_vlan_states(
switch_ip, next_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vlan_range(switch_ip, [])
vxlan_range = self._get_switch_vxlan_range(switch_ip)
if vxlan_range:
try:
self._restore_vxlan_entries(switch_ip, vxlan_range)
except Exception:
with excutils.save_and_reraise_exception():
LOG.error("Error encountered restoring vxlans "
"for switch %(switch_ip)s",
{'switch_ip': switch_ip})
self._save_switch_vxlan_range(switch_ip, [])
# if no more vlans to restore, we're done. go active.
if (not self._get_switch_vlan_range(switch_ip) and
not self._get_switch_vxlan_range(switch_ip)):
self.set_switch_ip_and_active_state(
switch_ip, const.SWITCH_ACTIVE)
LOG.info("Restore of Nexus switch "
"ip %(switch_ip)s is complete",
{'switch_ip': switch_ip})
else:
LOG.debug(("Restored batch of VLANS on "
"Nexus switch ip %(switch_ip)s"),
{'switch_ip': switch_ip}) | [
"def",
"configure_next_batch_of_vlans",
"(",
"self",
",",
"switch_ip",
")",
":",
"next_range",
"=",
"self",
".",
"_pop_vlan_range",
"(",
"switch_ip",
",",
"const",
".",
"CREATE_VLAN_BATCH",
")",
"if",
"next_range",
":",
"try",
":",
"self",
".",
"driver",
".",
... | Get next batch of vlans and send them to Nexus. | [
"Get",
"next",
"batch",
"of",
"vlans",
"and",
"send",
"them",
"to",
"Nexus",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1298-L1336 | train | 37,615 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.configure_switch_entries | def configure_switch_entries(self, switch_ip, port_bindings):
"""Create a nexus switch entry in Nexus.
The port_bindings is sorted by vlan_id, vni, port_id.
When there is a change in vlan_id or vni, then vlan
data is configured in Nexus device.
Otherwise we check if there is a change in port_id
where we configure the port with vlan trunk config.
Called during switch replay event.
"""
prev_vlan = -1
prev_vni = -1
prev_port = None
prev_native_vlan = 0
starttime = time.time()
port_bindings.sort(key=lambda x: (x.port_id, x.vlan_id, x.vni))
self.driver.capture_and_print_timeshot(
starttime, "replay_t2_aft_sort",
switch=switch_ip)
# Let's make these lists a set to exclude duplicates
vlans = set()
pvlans = set()
interface_count = 0
duplicate_port = 0
vlan_count = 0
for port in port_bindings:
if nxos_db.is_reserved_binding(port):
continue
auto_create, auto_trunk = self._gather_config_parms(
nxos_db.is_provider_vlan(port.vlan_id), port.vlan_id)
if port.port_id == prev_port:
if port.vlan_id == prev_vlan and port.vni == prev_vni:
# Same port/Same Vlan - skip duplicate
duplicate_port += 1
continue
else:
# Same port/different Vlan - track it
vlan_count += 1
if auto_create:
vlans.add((port.vlan_id, port.vni))
if auto_trunk:
pvlans.add(port.vlan_id)
if port.is_native:
prev_native_vlan = port.vlan_id
else:
# Different port - write out interface trunk on previous port
if prev_port:
interface_count += 1
LOG.debug("Switch %s port %s replay summary: unique vlan "
"count %d, duplicate port entries %d",
switch_ip, prev_port, vlan_count, duplicate_port)
duplicate_port = 0
vlan_count = 0
if pvlans:
self._restore_port_binding(
switch_ip, pvlans, prev_port, prev_native_vlan)
pvlans.clear()
prev_native_vlan = 0
# Start tracking new port
if auto_create:
vlans.add((port.vlan_id, port.vni))
if auto_trunk:
pvlans.add(port.vlan_id)
prev_port = port.port_id
if port.is_native:
prev_native_vlan = port.vlan_id
if pvlans:
LOG.debug("Switch %s port %s replay summary: unique vlan "
"count %d, duplicate port entries %d",
switch_ip, port.port_id, vlan_count, duplicate_port)
self._restore_port_binding(
switch_ip, pvlans, prev_port, prev_native_vlan)
LOG.debug("Replayed total %d ports for Switch %s",
interface_count + 1, switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "replay_part_1",
switch=switch_ip)
vlans = list(vlans)
if vlans:
vlans.sort()
vlan, vni = vlans[0]
if vni == 0:
self._save_switch_vlan_range(switch_ip, vlans)
else:
self._save_switch_vxlan_range(switch_ip, vlans)
self.set_switch_ip_and_active_state(
switch_ip, const.SWITCH_RESTORE_S2)
self.configure_next_batch_of_vlans(switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "replay_part_2",
switch=switch_ip) | python | def configure_switch_entries(self, switch_ip, port_bindings):
"""Create a nexus switch entry in Nexus.
The port_bindings is sorted by vlan_id, vni, port_id.
When there is a change in vlan_id or vni, then vlan
data is configured in Nexus device.
Otherwise we check if there is a change in port_id
where we configure the port with vlan trunk config.
Called during switch replay event.
"""
prev_vlan = -1
prev_vni = -1
prev_port = None
prev_native_vlan = 0
starttime = time.time()
port_bindings.sort(key=lambda x: (x.port_id, x.vlan_id, x.vni))
self.driver.capture_and_print_timeshot(
starttime, "replay_t2_aft_sort",
switch=switch_ip)
# Let's make these lists a set to exclude duplicates
vlans = set()
pvlans = set()
interface_count = 0
duplicate_port = 0
vlan_count = 0
for port in port_bindings:
if nxos_db.is_reserved_binding(port):
continue
auto_create, auto_trunk = self._gather_config_parms(
nxos_db.is_provider_vlan(port.vlan_id), port.vlan_id)
if port.port_id == prev_port:
if port.vlan_id == prev_vlan and port.vni == prev_vni:
# Same port/Same Vlan - skip duplicate
duplicate_port += 1
continue
else:
# Same port/different Vlan - track it
vlan_count += 1
if auto_create:
vlans.add((port.vlan_id, port.vni))
if auto_trunk:
pvlans.add(port.vlan_id)
if port.is_native:
prev_native_vlan = port.vlan_id
else:
# Different port - write out interface trunk on previous port
if prev_port:
interface_count += 1
LOG.debug("Switch %s port %s replay summary: unique vlan "
"count %d, duplicate port entries %d",
switch_ip, prev_port, vlan_count, duplicate_port)
duplicate_port = 0
vlan_count = 0
if pvlans:
self._restore_port_binding(
switch_ip, pvlans, prev_port, prev_native_vlan)
pvlans.clear()
prev_native_vlan = 0
# Start tracking new port
if auto_create:
vlans.add((port.vlan_id, port.vni))
if auto_trunk:
pvlans.add(port.vlan_id)
prev_port = port.port_id
if port.is_native:
prev_native_vlan = port.vlan_id
if pvlans:
LOG.debug("Switch %s port %s replay summary: unique vlan "
"count %d, duplicate port entries %d",
switch_ip, port.port_id, vlan_count, duplicate_port)
self._restore_port_binding(
switch_ip, pvlans, prev_port, prev_native_vlan)
LOG.debug("Replayed total %d ports for Switch %s",
interface_count + 1, switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "replay_part_1",
switch=switch_ip)
vlans = list(vlans)
if vlans:
vlans.sort()
vlan, vni = vlans[0]
if vni == 0:
self._save_switch_vlan_range(switch_ip, vlans)
else:
self._save_switch_vxlan_range(switch_ip, vlans)
self.set_switch_ip_and_active_state(
switch_ip, const.SWITCH_RESTORE_S2)
self.configure_next_batch_of_vlans(switch_ip)
self.driver.capture_and_print_timeshot(
starttime, "replay_part_2",
switch=switch_ip) | [
"def",
"configure_switch_entries",
"(",
"self",
",",
"switch_ip",
",",
"port_bindings",
")",
":",
"prev_vlan",
"=",
"-",
"1",
"prev_vni",
"=",
"-",
"1",
"prev_port",
"=",
"None",
"prev_native_vlan",
"=",
"0",
"starttime",
"=",
"time",
".",
"time",
"(",
")"... | Create a nexus switch entry in Nexus.
The port_bindings is sorted by vlan_id, vni, port_id.
When there is a change in vlan_id or vni, then vlan
data is configured in Nexus device.
Otherwise we check if there is a change in port_id
where we configure the port with vlan trunk config.
Called during switch replay event. | [
"Create",
"a",
"nexus",
"switch",
"entry",
"in",
"Nexus",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1338-L1436 | train | 37,616 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._delete_nxos_db | def _delete_nxos_db(self, unused, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Delete the nexus database entry.
Called during delete precommit port event.
"""
try:
rows = nxos_db.get_nexusvm_bindings(vlan_id, device_id)
for row in rows:
nxos_db.remove_nexusport_binding(row.port_id, row.vlan_id,
row.vni, row.switch_ip, row.instance_id)
except excep.NexusPortBindingNotFound:
return | python | def _delete_nxos_db(self, unused, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Delete the nexus database entry.
Called during delete precommit port event.
"""
try:
rows = nxos_db.get_nexusvm_bindings(vlan_id, device_id)
for row in rows:
nxos_db.remove_nexusport_binding(row.port_id, row.vlan_id,
row.vni, row.switch_ip, row.instance_id)
except excep.NexusPortBindingNotFound:
return | [
"def",
"_delete_nxos_db",
"(",
"self",
",",
"unused",
",",
"vlan_id",
",",
"device_id",
",",
"host_id",
",",
"vni",
",",
"is_provider_vlan",
")",
":",
"try",
":",
"rows",
"=",
"nxos_db",
".",
"get_nexusvm_bindings",
"(",
"vlan_id",
",",
"device_id",
")",
"... | Delete the nexus database entry.
Called during delete precommit port event. | [
"Delete",
"the",
"nexus",
"database",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1438-L1450 | train | 37,617 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._delete_port_channel_resources | def _delete_port_channel_resources(self, host_id, switch_ip,
intf_type, nexus_port, port_id):
'''This determines if port channel id needs to be freed.'''
# if this connection is not a port-channel, nothing to do.
if intf_type != 'port-channel':
return
# Check if this driver created it and its no longer needed.
try:
vpc = nxos_db.get_switch_vpc_alloc(
switch_ip, nexus_port)
except excep.NexusVPCAllocNotFound:
# This can occur for non-baremetal configured
# port-channels. Nothing more to do.
LOG.debug("Switch %s portchannel %s vpc entry not "
"found in vpcid alloc table.",
switch_ip, nexus_port)
return
# if this isn't one which was allocated or learned,
# don't do any further processing.
if not vpc.active:
LOG.debug("Switch %s portchannel %s vpc entry not "
"active.",
switch_ip, nexus_port)
return
# Is this port-channel still in use?
# If so, nothing more to do.
try:
nxos_db.get_nexus_switchport_binding(port_id, switch_ip)
LOG.debug("Switch %s portchannel %s port entries "
"in use. Skipping port-channel clean-up.",
switch_ip, nexus_port)
return
except excep.NexusPortBindingNotFound:
pass
# need to get ethernet interface name
try:
mapping = nxos_db.get_switch_and_host_mappings(
host_id, switch_ip)
eth_type, eth_port = nexus_help.split_interface_name(
mapping[0].if_id)
except excep.NexusHostMappingNotFound:
LOG.warning("Switch %s hostid %s host_mapping not "
"found. Skipping port-channel clean-up.",
switch_ip, host_id)
return
# Remove the channel group from ethernet interface
# and remove port channel from this switch.
if not vpc.learned:
self.driver.delete_ch_grp_to_interface(
switch_ip, eth_type, eth_port,
nexus_port)
self.driver.delete_port_channel(switch_ip,
nexus_port)
try:
nxos_db.free_vpcid_for_switch(nexus_port, switch_ip)
LOG.info("Released portchannel %s resources for "
"switch %s",
nexus_port, switch_ip)
except excep.NexusVPCAllocNotFound:
# Not all learned port channels will be in this db when
# they're outside the configured vpc_pool so
# this exception may be possible.
LOG.warning("Failed to free vpcid %s for switch %s "
"since it did not exist in table.",
nexus_port, switch_ip) | python | def _delete_port_channel_resources(self, host_id, switch_ip,
intf_type, nexus_port, port_id):
'''This determines if port channel id needs to be freed.'''
# if this connection is not a port-channel, nothing to do.
if intf_type != 'port-channel':
return
# Check if this driver created it and its no longer needed.
try:
vpc = nxos_db.get_switch_vpc_alloc(
switch_ip, nexus_port)
except excep.NexusVPCAllocNotFound:
# This can occur for non-baremetal configured
# port-channels. Nothing more to do.
LOG.debug("Switch %s portchannel %s vpc entry not "
"found in vpcid alloc table.",
switch_ip, nexus_port)
return
# if this isn't one which was allocated or learned,
# don't do any further processing.
if not vpc.active:
LOG.debug("Switch %s portchannel %s vpc entry not "
"active.",
switch_ip, nexus_port)
return
# Is this port-channel still in use?
# If so, nothing more to do.
try:
nxos_db.get_nexus_switchport_binding(port_id, switch_ip)
LOG.debug("Switch %s portchannel %s port entries "
"in use. Skipping port-channel clean-up.",
switch_ip, nexus_port)
return
except excep.NexusPortBindingNotFound:
pass
# need to get ethernet interface name
try:
mapping = nxos_db.get_switch_and_host_mappings(
host_id, switch_ip)
eth_type, eth_port = nexus_help.split_interface_name(
mapping[0].if_id)
except excep.NexusHostMappingNotFound:
LOG.warning("Switch %s hostid %s host_mapping not "
"found. Skipping port-channel clean-up.",
switch_ip, host_id)
return
# Remove the channel group from ethernet interface
# and remove port channel from this switch.
if not vpc.learned:
self.driver.delete_ch_grp_to_interface(
switch_ip, eth_type, eth_port,
nexus_port)
self.driver.delete_port_channel(switch_ip,
nexus_port)
try:
nxos_db.free_vpcid_for_switch(nexus_port, switch_ip)
LOG.info("Released portchannel %s resources for "
"switch %s",
nexus_port, switch_ip)
except excep.NexusVPCAllocNotFound:
# Not all learned port channels will be in this db when
# they're outside the configured vpc_pool so
# this exception may be possible.
LOG.warning("Failed to free vpcid %s for switch %s "
"since it did not exist in table.",
nexus_port, switch_ip) | [
"def",
"_delete_port_channel_resources",
"(",
"self",
",",
"host_id",
",",
"switch_ip",
",",
"intf_type",
",",
"nexus_port",
",",
"port_id",
")",
":",
"# if this connection is not a port-channel, nothing to do.",
"if",
"intf_type",
"!=",
"'port-channel'",
":",
"return",
... | This determines if port channel id needs to be freed. | [
"This",
"determines",
"if",
"port",
"channel",
"id",
"needs",
"to",
"be",
"freed",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1452-L1522 | train | 37,618 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver._delete_switch_entry | def _delete_switch_entry(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Delete the nexus switch entry.
By accessing the current db entries determine if switch
configuration can be removed.
Called during delete postcommit port event.
"""
connections = self._get_active_port_connections(port, host_id)
# (nexus_port,switch_ip) will be unique in each iteration.
# But switch_ip will repeat if host has >1 connection to same switch.
# So track which switch_ips already have vlan removed in this loop.
vlan_already_removed = []
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
# if there are no remaining db entries using this vlan on this
# nexus switch port then remove vlan from the switchport trunk.
port_id = nexus_help.format_interface_name(intf_type, nexus_port)
auto_create = True
auto_trunk = True
if is_provider_vlan:
auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create
auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk
try:
nxos_db.get_port_vlan_switch_binding(port_id, vlan_id,
switch_ip)
except excep.NexusPortBindingNotFound:
pass
else:
continue
if auto_trunk:
self.driver.disable_vlan_on_trunk_int(
switch_ip, vlan_id, intf_type, nexus_port,
is_native)
# if there are no remaining db entries using this vlan on this
# nexus switch then remove the vlan.
if auto_create:
try:
nxos_db.get_nexusvlan_binding(vlan_id, switch_ip)
except excep.NexusPortBindingNotFound:
# Do not perform a second time on same switch
if switch_ip not in vlan_already_removed:
self.driver.delete_vlan(switch_ip, vlan_id)
vlan_already_removed.append(switch_ip)
self._delete_port_channel_resources(
host_id, switch_ip, intf_type, nexus_port, port_id)
if nexus_help.is_baremetal(port):
connections = self._get_baremetal_connections(
port, False, True)
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
if_id = nexus_help.format_interface_name(
intf_type, nexus_port)
try:
mapping = nxos_db.get_switch_if_host_mappings(
switch_ip, if_id)
ch_grp = mapping[0].ch_grp
except excep.NexusHostMappingNotFound:
ch_grp = 0
bind_port_id = nexus_help.format_interface_name(
intf_type, nexus_port, ch_grp)
binding = nxos_db.get_port_switch_bindings(
bind_port_id,
switch_ip)
if not binding:
nxos_db.remove_host_mapping(if_id, switch_ip) | python | def _delete_switch_entry(self, port, vlan_id, device_id, host_id, vni,
is_provider_vlan):
"""Delete the nexus switch entry.
By accessing the current db entries determine if switch
configuration can be removed.
Called during delete postcommit port event.
"""
connections = self._get_active_port_connections(port, host_id)
# (nexus_port,switch_ip) will be unique in each iteration.
# But switch_ip will repeat if host has >1 connection to same switch.
# So track which switch_ips already have vlan removed in this loop.
vlan_already_removed = []
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
# if there are no remaining db entries using this vlan on this
# nexus switch port then remove vlan from the switchport trunk.
port_id = nexus_help.format_interface_name(intf_type, nexus_port)
auto_create = True
auto_trunk = True
if is_provider_vlan:
auto_create = cfg.CONF.ml2_cisco.provider_vlan_auto_create
auto_trunk = cfg.CONF.ml2_cisco.provider_vlan_auto_trunk
try:
nxos_db.get_port_vlan_switch_binding(port_id, vlan_id,
switch_ip)
except excep.NexusPortBindingNotFound:
pass
else:
continue
if auto_trunk:
self.driver.disable_vlan_on_trunk_int(
switch_ip, vlan_id, intf_type, nexus_port,
is_native)
# if there are no remaining db entries using this vlan on this
# nexus switch then remove the vlan.
if auto_create:
try:
nxos_db.get_nexusvlan_binding(vlan_id, switch_ip)
except excep.NexusPortBindingNotFound:
# Do not perform a second time on same switch
if switch_ip not in vlan_already_removed:
self.driver.delete_vlan(switch_ip, vlan_id)
vlan_already_removed.append(switch_ip)
self._delete_port_channel_resources(
host_id, switch_ip, intf_type, nexus_port, port_id)
if nexus_help.is_baremetal(port):
connections = self._get_baremetal_connections(
port, False, True)
for switch_ip, intf_type, nexus_port, is_native, _ in connections:
if_id = nexus_help.format_interface_name(
intf_type, nexus_port)
try:
mapping = nxos_db.get_switch_if_host_mappings(
switch_ip, if_id)
ch_grp = mapping[0].ch_grp
except excep.NexusHostMappingNotFound:
ch_grp = 0
bind_port_id = nexus_help.format_interface_name(
intf_type, nexus_port, ch_grp)
binding = nxos_db.get_port_switch_bindings(
bind_port_id,
switch_ip)
if not binding:
nxos_db.remove_host_mapping(if_id, switch_ip) | [
"def",
"_delete_switch_entry",
"(",
"self",
",",
"port",
",",
"vlan_id",
",",
"device_id",
",",
"host_id",
",",
"vni",
",",
"is_provider_vlan",
")",
":",
"connections",
"=",
"self",
".",
"_get_active_port_connections",
"(",
"port",
",",
"host_id",
")",
"# (nex... | Delete the nexus switch entry.
By accessing the current db entries determine if switch
configuration can be removed.
Called during delete postcommit port event. | [
"Delete",
"the",
"nexus",
"switch",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1524-L1596 | train | 37,619 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.create_port_postcommit | def create_port_postcommit(self, context):
"""Create port non-database commit event."""
# No new events are handled until replay
# thread has put the switch in active state.
# If a switch is in active state, verify
# the switch is still in active state
# before accepting this new event.
#
# If create_port_postcommit fails, it causes
# other openstack dbs to be cleared and
# retries for new VMs will stop. Subnet
# transactions will continue to be retried.
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
# Verify segment.
if not self._is_valid_segment(vlan_segment):
return
port = context.current
if self._is_supported_deviceowner(port):
if nexus_help.is_baremetal(context.current):
all_switches, active_switches = (
self._get_baremetal_switches(context.current))
else:
host_id = context.current.get(bc.portbindings.HOST_ID)
all_switches, active_switches = (
self._get_host_switches(host_id))
# Verify switch is still up before replay
# thread checks.
verified_active_switches = []
for switch_ip in active_switches:
try:
self.driver.get_nexus_type(switch_ip)
verified_active_switches.append(switch_ip)
except Exception as e:
LOG.error("Failed to ping "
"switch ip %(switch_ip)s error %(exp_err)s",
{'switch_ip': switch_ip, 'exp_err': e})
LOG.debug("Create Stats: thread %(thid)d, "
"all_switches %(all)d, "
"active %(active)d, verified %(verify)d",
{'thid': threading.current_thread().ident,
'all': len(all_switches),
'active': len(active_switches),
'verify': len(verified_active_switches)})
# if host_id is valid and there is no active
# switches remaining
if all_switches and not verified_active_switches:
raise excep.NexusConnectFailed(
nexus_host=all_switches[0], config="None",
exc="Create Failed: Port event can not "
"be processed at this time.") | python | def create_port_postcommit(self, context):
"""Create port non-database commit event."""
# No new events are handled until replay
# thread has put the switch in active state.
# If a switch is in active state, verify
# the switch is still in active state
# before accepting this new event.
#
# If create_port_postcommit fails, it causes
# other openstack dbs to be cleared and
# retries for new VMs will stop. Subnet
# transactions will continue to be retried.
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
# Verify segment.
if not self._is_valid_segment(vlan_segment):
return
port = context.current
if self._is_supported_deviceowner(port):
if nexus_help.is_baremetal(context.current):
all_switches, active_switches = (
self._get_baremetal_switches(context.current))
else:
host_id = context.current.get(bc.portbindings.HOST_ID)
all_switches, active_switches = (
self._get_host_switches(host_id))
# Verify switch is still up before replay
# thread checks.
verified_active_switches = []
for switch_ip in active_switches:
try:
self.driver.get_nexus_type(switch_ip)
verified_active_switches.append(switch_ip)
except Exception as e:
LOG.error("Failed to ping "
"switch ip %(switch_ip)s error %(exp_err)s",
{'switch_ip': switch_ip, 'exp_err': e})
LOG.debug("Create Stats: thread %(thid)d, "
"all_switches %(all)d, "
"active %(active)d, verified %(verify)d",
{'thid': threading.current_thread().ident,
'all': len(all_switches),
'active': len(active_switches),
'verify': len(verified_active_switches)})
# if host_id is valid and there is no active
# switches remaining
if all_switches and not verified_active_switches:
raise excep.NexusConnectFailed(
nexus_host=all_switches[0], config="None",
exc="Create Failed: Port event can not "
"be processed at this time.") | [
"def",
"create_port_postcommit",
"(",
"self",
",",
"context",
")",
":",
"# No new events are handled until replay",
"# thread has put the switch in active state.",
"# If a switch is in active state, verify",
"# the switch is still in active state",
"# before accepting this new event.",
"#"... | Create port non-database commit event. | [
"Create",
"port",
"non",
"-",
"database",
"commit",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1700-L1757 | train | 37,620 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.update_port_precommit | def update_port_precommit(self, context):
"""Update port pre-database transaction commit event."""
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment, context.bottom_bound_segment)
orig_vlan_segment, orig_vxlan_segment = self._get_segments(
context.original_top_bound_segment,
context.original_bottom_bound_segment)
if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
self._is_status_down(context.current)):
vni = (self._port_action_vxlan(
context.original, orig_vxlan_segment, self._delete_nve_db)
if orig_vxlan_segment else 0)
self._port_action_vlan(context.original, orig_vlan_segment,
self._delete_nxos_db, vni)
elif self._is_supported_deviceowner(context.current):
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._configure_nve_db) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._configure_nxos_db, vni) | python | def update_port_precommit(self, context):
"""Update port pre-database transaction commit event."""
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment, context.bottom_bound_segment)
orig_vlan_segment, orig_vxlan_segment = self._get_segments(
context.original_top_bound_segment,
context.original_bottom_bound_segment)
if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
self._is_status_down(context.current)):
vni = (self._port_action_vxlan(
context.original, orig_vxlan_segment, self._delete_nve_db)
if orig_vxlan_segment else 0)
self._port_action_vlan(context.original, orig_vlan_segment,
self._delete_nxos_db, vni)
elif self._is_supported_deviceowner(context.current):
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._configure_nve_db) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._configure_nxos_db, vni) | [
"def",
"update_port_precommit",
"(",
"self",
",",
"context",
")",
":",
"vlan_segment",
",",
"vxlan_segment",
"=",
"self",
".",
"_get_segments",
"(",
"context",
".",
"top_bound_segment",
",",
"context",
".",
"bottom_bound_segment",
")",
"orig_vlan_segment",
",",
"o... | Update port pre-database transaction commit event. | [
"Update",
"port",
"pre",
"-",
"database",
"transaction",
"commit",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1760-L1779 | train | 37,621 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.update_port_postcommit | def update_port_postcommit(self, context):
"""Update port non-database commit event."""
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment, context.bottom_bound_segment)
orig_vlan_segment, orig_vxlan_segment = self._get_segments(
context.original_top_bound_segment,
context.original_bottom_bound_segment)
if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
self._is_status_down(context.current)):
vni = (self._port_action_vxlan(
context.original, orig_vxlan_segment,
self._delete_nve_member) if orig_vxlan_segment else 0)
self._port_action_vlan(context.original, orig_vlan_segment,
self._delete_switch_entry, vni)
elif self._is_supported_deviceowner(context.current):
if nexus_help.is_baremetal(context.current):
all_switches, active_switches = (
self._get_baremetal_switches(context.current))
else:
host_id = context.current.get(bc.portbindings.HOST_ID)
all_switches, active_switches = (
self._get_host_switches(host_id))
# if switches not active but host_id is valid
if not active_switches and all_switches:
raise excep.NexusConnectFailed(
nexus_host=all_switches[0], config="None",
exc="Update Port Failed: Nexus Switch "
"is down or replay in progress")
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._configure_nve_member) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._configure_port_entries, vni) | python | def update_port_postcommit(self, context):
"""Update port non-database commit event."""
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment, context.bottom_bound_segment)
orig_vlan_segment, orig_vxlan_segment = self._get_segments(
context.original_top_bound_segment,
context.original_bottom_bound_segment)
if (self._is_vm_migrating(context, vlan_segment, orig_vlan_segment) or
self._is_status_down(context.current)):
vni = (self._port_action_vxlan(
context.original, orig_vxlan_segment,
self._delete_nve_member) if orig_vxlan_segment else 0)
self._port_action_vlan(context.original, orig_vlan_segment,
self._delete_switch_entry, vni)
elif self._is_supported_deviceowner(context.current):
if nexus_help.is_baremetal(context.current):
all_switches, active_switches = (
self._get_baremetal_switches(context.current))
else:
host_id = context.current.get(bc.portbindings.HOST_ID)
all_switches, active_switches = (
self._get_host_switches(host_id))
# if switches not active but host_id is valid
if not active_switches and all_switches:
raise excep.NexusConnectFailed(
nexus_host=all_switches[0], config="None",
exc="Update Port Failed: Nexus Switch "
"is down or replay in progress")
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._configure_nve_member) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._configure_port_entries, vni) | [
"def",
"update_port_postcommit",
"(",
"self",
",",
"context",
")",
":",
"vlan_segment",
",",
"vxlan_segment",
"=",
"self",
".",
"_get_segments",
"(",
"context",
".",
"top_bound_segment",
",",
"context",
".",
"bottom_bound_segment",
")",
"orig_vlan_segment",
",",
"... | Update port non-database commit event. | [
"Update",
"port",
"non",
"-",
"database",
"commit",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1782-L1815 | train | 37,622 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.delete_port_precommit | def delete_port_precommit(self, context):
"""Delete port pre-database commit event."""
if self._is_supported_deviceowner(context.current):
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._delete_nve_db) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._delete_nxos_db, vni) | python | def delete_port_precommit(self, context):
"""Delete port pre-database commit event."""
if self._is_supported_deviceowner(context.current):
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._delete_nve_db) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._delete_nxos_db, vni) | [
"def",
"delete_port_precommit",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"_is_supported_deviceowner",
"(",
"context",
".",
"current",
")",
":",
"vlan_segment",
",",
"vxlan_segment",
"=",
"self",
".",
"_get_segments",
"(",
"context",
".",
"top_... | Delete port pre-database commit event. | [
"Delete",
"port",
"pre",
"-",
"database",
"commit",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1818-L1827 | train | 37,623 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py | CiscoNexusMechanismDriver.delete_port_postcommit | def delete_port_postcommit(self, context):
"""Delete port non-database commit event."""
if self._is_supported_deviceowner(context.current):
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._delete_nve_member) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._delete_switch_entry, vni) | python | def delete_port_postcommit(self, context):
"""Delete port non-database commit event."""
if self._is_supported_deviceowner(context.current):
vlan_segment, vxlan_segment = self._get_segments(
context.top_bound_segment,
context.bottom_bound_segment)
vni = self._port_action_vxlan(context.current, vxlan_segment,
self._delete_nve_member) if vxlan_segment else 0
self._port_action_vlan(context.current, vlan_segment,
self._delete_switch_entry, vni) | [
"def",
"delete_port_postcommit",
"(",
"self",
",",
"context",
")",
":",
"if",
"self",
".",
"_is_supported_deviceowner",
"(",
"context",
".",
"current",
")",
":",
"vlan_segment",
",",
"vxlan_segment",
"=",
"self",
".",
"_get_segments",
"(",
"context",
".",
"top... | Delete port non-database commit event. | [
"Delete",
"port",
"non",
"-",
"database",
"commit",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/mech_cisco_nexus.py#L1830-L1839 | train | 37,624 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._detect_iplus | def _detect_iplus(self):
"""Check the DCNM version and determine if it's for iplus"""
ver_expr = "([0-9]+)\.([0-9]+)\((.*)\)"
re.compile(ver_expr)
v1 = re.match(ver_expr, self._cur_ver)
v2 = re.match(ver_expr, self._base_ver)
if int(v1.group(1)) > int(v2.group(1)):
self._is_iplus = True
elif int(v1.group(1)) == int(v2.group(1)):
if int(v1.group(2)) > int(v2.group(2)):
self._is_iplus = True
elif int(v1.group(2)) == int(v2.group(2)):
self._is_iplus = v1.group(3) >= v2.group(3)
LOG.info("DCNM version: %(cur_ver)s, iplus: %(is_iplus)s",
{'cur_ver': self._cur_ver, 'is_iplus': self._is_iplus}) | python | def _detect_iplus(self):
"""Check the DCNM version and determine if it's for iplus"""
ver_expr = "([0-9]+)\.([0-9]+)\((.*)\)"
re.compile(ver_expr)
v1 = re.match(ver_expr, self._cur_ver)
v2 = re.match(ver_expr, self._base_ver)
if int(v1.group(1)) > int(v2.group(1)):
self._is_iplus = True
elif int(v1.group(1)) == int(v2.group(1)):
if int(v1.group(2)) > int(v2.group(2)):
self._is_iplus = True
elif int(v1.group(2)) == int(v2.group(2)):
self._is_iplus = v1.group(3) >= v2.group(3)
LOG.info("DCNM version: %(cur_ver)s, iplus: %(is_iplus)s",
{'cur_ver': self._cur_ver, 'is_iplus': self._is_iplus}) | [
"def",
"_detect_iplus",
"(",
"self",
")",
":",
"ver_expr",
"=",
"\"([0-9]+)\\.([0-9]+)\\((.*)\\)\"",
"re",
".",
"compile",
"(",
"ver_expr",
")",
"v1",
"=",
"re",
".",
"match",
"(",
"ver_expr",
",",
"self",
".",
"_cur_ver",
")",
"v2",
"=",
"re",
".",
"mat... | Check the DCNM version and determine if it's for iplus | [
"Check",
"the",
"DCNM",
"version",
"and",
"determine",
"if",
"it",
"s",
"for",
"iplus"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L75-L92 | train | 37,625 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_segmentid_range | def get_segmentid_range(self, orchestrator_id):
"""Get segment id range from DCNM. """
url = "%s/%s" % (self._segmentid_ranges_url, orchestrator_id)
res = self._send_request('GET', url, None, 'segment-id range')
if res and res.status_code in self._resp_ok:
return res.json() | python | def get_segmentid_range(self, orchestrator_id):
"""Get segment id range from DCNM. """
url = "%s/%s" % (self._segmentid_ranges_url, orchestrator_id)
res = self._send_request('GET', url, None, 'segment-id range')
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"get_segmentid_range",
"(",
"self",
",",
"orchestrator_id",
")",
":",
"url",
"=",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"_segmentid_ranges_url",
",",
"orchestrator_id",
")",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"url",
",",
"None"... | Get segment id range from DCNM. | [
"Get",
"segment",
"id",
"range",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L97-L104 | train | 37,626 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.set_segmentid_range | def set_segmentid_range(self, orchestrator_id, segid_min, segid_max):
"""set segment id range in DCNM. """
url = self._segmentid_ranges_url
payload = {'orchestratorId': orchestrator_id,
'segmentIdRanges': "%s-%s" % (segid_min, segid_max)}
res = self._send_request('POST', url, payload, 'segment-id range')
if not (res and res.status_code in self._resp_ok):
LOG.error("Failed to set segment id range for orchestrator "
"%(orch)s on DCNM: %(text)s",
{'orch': orchestrator_id, 'text': res.text})
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | python | def set_segmentid_range(self, orchestrator_id, segid_min, segid_max):
"""set segment id range in DCNM. """
url = self._segmentid_ranges_url
payload = {'orchestratorId': orchestrator_id,
'segmentIdRanges': "%s-%s" % (segid_min, segid_max)}
res = self._send_request('POST', url, payload, 'segment-id range')
if not (res and res.status_code in self._resp_ok):
LOG.error("Failed to set segment id range for orchestrator "
"%(orch)s on DCNM: %(text)s",
{'orch': orchestrator_id, 'text': res.text})
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | [
"def",
"set_segmentid_range",
"(",
"self",
",",
"orchestrator_id",
",",
"segid_min",
",",
"segid_max",
")",
":",
"url",
"=",
"self",
".",
"_segmentid_ranges_url",
"payload",
"=",
"{",
"'orchestratorId'",
":",
"orchestrator_id",
",",
"'segmentIdRanges'",
":",
"\"%s... | set segment id range in DCNM. | [
"set",
"segment",
"id",
"range",
"in",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L106-L119 | train | 37,627 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._set_default_cfg_profile | def _set_default_cfg_profile(self):
"""Set default network config profile.
Check whether the default_cfg_profile value exist in the current
version of DCNM. If not, set it to new default value which is supported
by latest version.
"""
try:
cfgplist = self.config_profile_list()
if self.default_cfg_profile not in cfgplist:
self.default_cfg_profile = ('defaultNetworkUniversalEfProfile'
if self._is_iplus else
'defaultNetworkIpv4EfProfile')
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.")
self.default_cfg_profile = 'defaultNetworkIpv4EfProfile' | python | def _set_default_cfg_profile(self):
"""Set default network config profile.
Check whether the default_cfg_profile value exist in the current
version of DCNM. If not, set it to new default value which is supported
by latest version.
"""
try:
cfgplist = self.config_profile_list()
if self.default_cfg_profile not in cfgplist:
self.default_cfg_profile = ('defaultNetworkUniversalEfProfile'
if self._is_iplus else
'defaultNetworkIpv4EfProfile')
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.")
self.default_cfg_profile = 'defaultNetworkIpv4EfProfile' | [
"def",
"_set_default_cfg_profile",
"(",
"self",
")",
":",
"try",
":",
"cfgplist",
"=",
"self",
".",
"config_profile_list",
"(",
")",
"if",
"self",
".",
"default_cfg_profile",
"not",
"in",
"cfgplist",
":",
"self",
".",
"default_cfg_profile",
"=",
"(",
"'default... | Set default network config profile.
Check whether the default_cfg_profile value exist in the current
version of DCNM. If not, set it to new default value which is supported
by latest version. | [
"Set",
"default",
"network",
"config",
"profile",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L135-L150 | train | 37,628 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._create_network | def _create_network(self, network_info):
"""Send create network request to DCNM.
:param network_info: network parameters to be created on DCNM
"""
url = self._create_network_url % (network_info['organizationName'],
network_info['partitionName'])
payload = network_info
LOG.info('url %(url)s payload %(payload)s',
{'url': url, 'payload': payload})
return self._send_request('POST', url, payload, 'network') | python | def _create_network(self, network_info):
"""Send create network request to DCNM.
:param network_info: network parameters to be created on DCNM
"""
url = self._create_network_url % (network_info['organizationName'],
network_info['partitionName'])
payload = network_info
LOG.info('url %(url)s payload %(payload)s',
{'url': url, 'payload': payload})
return self._send_request('POST', url, payload, 'network') | [
"def",
"_create_network",
"(",
"self",
",",
"network_info",
")",
":",
"url",
"=",
"self",
".",
"_create_network_url",
"%",
"(",
"network_info",
"[",
"'organizationName'",
"]",
",",
"network_info",
"[",
"'partitionName'",
"]",
")",
"payload",
"=",
"network_info",... | Send create network request to DCNM.
:param network_info: network parameters to be created on DCNM | [
"Send",
"create",
"network",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L152-L163 | train | 37,629 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._config_profile_get | def _config_profile_get(self, thisprofile):
"""Get information of a config profile from DCNM.
:param thisprofile: network config profile in request
"""
url = self._cfg_profile_get_url % (thisprofile)
payload = {}
res = self._send_request('GET', url, payload, 'config-profile')
if res and res.status_code in self._resp_ok:
return res.json() | python | def _config_profile_get(self, thisprofile):
"""Get information of a config profile from DCNM.
:param thisprofile: network config profile in request
"""
url = self._cfg_profile_get_url % (thisprofile)
payload = {}
res = self._send_request('GET', url, payload, 'config-profile')
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"_config_profile_get",
"(",
"self",
",",
"thisprofile",
")",
":",
"url",
"=",
"self",
".",
"_cfg_profile_get_url",
"%",
"(",
"thisprofile",
")",
"payload",
"=",
"{",
"}",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"url",
",",
"pa... | Get information of a config profile from DCNM.
:param thisprofile: network config profile in request | [
"Get",
"information",
"of",
"a",
"config",
"profile",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L165-L175 | train | 37,630 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._config_profile_list | def _config_profile_list(self):
"""Get list of supported config profile from DCNM."""
url = self._cfg_profile_list_url
payload = {}
try:
res = self._send_request('GET', url, payload, 'config-profile')
if res and res.status_code in self._resp_ok:
return res.json()
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.") | python | def _config_profile_list(self):
"""Get list of supported config profile from DCNM."""
url = self._cfg_profile_list_url
payload = {}
try:
res = self._send_request('GET', url, payload, 'config-profile')
if res and res.status_code in self._resp_ok:
return res.json()
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.") | [
"def",
"_config_profile_list",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_cfg_profile_list_url",
"payload",
"=",
"{",
"}",
"try",
":",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"url",
",",
"payload",
",",
"'config-profile'",
")",
... | Get list of supported config profile from DCNM. | [
"Get",
"list",
"of",
"supported",
"config",
"profile",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L177-L187 | train | 37,631 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._get_settings | def _get_settings(self):
"""Get global mobility domain from DCNM."""
url = self._global_settings_url
payload = {}
res = self._send_request('GET', url, payload, 'settings')
if res and res.status_code in self._resp_ok:
return res.json() | python | def _get_settings(self):
"""Get global mobility domain from DCNM."""
url = self._global_settings_url
payload = {}
res = self._send_request('GET', url, payload, 'settings')
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"_get_settings",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"_global_settings_url",
"payload",
"=",
"{",
"}",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"url",
",",
"payload",
",",
"'settings'",
")",
"if",
"res",
"and",
"r... | Get global mobility domain from DCNM. | [
"Get",
"global",
"mobility",
"domain",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L189-L195 | train | 37,632 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._create_org | def _create_org(self, orch_id, name, desc):
"""Create organization on the DCNM.
:param orch_id: orchestrator ID
:param name: Name of organization
:param desc: Description of organization
"""
url = self._org_url
payload = {
"organizationName": name,
"description": name if len(desc) == 0 else desc,
"orchestrationSource": orch_id}
return self._send_request('POST', url, payload, 'organization') | python | def _create_org(self, orch_id, name, desc):
"""Create organization on the DCNM.
:param orch_id: orchestrator ID
:param name: Name of organization
:param desc: Description of organization
"""
url = self._org_url
payload = {
"organizationName": name,
"description": name if len(desc) == 0 else desc,
"orchestrationSource": orch_id}
return self._send_request('POST', url, payload, 'organization') | [
"def",
"_create_org",
"(",
"self",
",",
"orch_id",
",",
"name",
",",
"desc",
")",
":",
"url",
"=",
"self",
".",
"_org_url",
"payload",
"=",
"{",
"\"organizationName\"",
":",
"name",
",",
"\"description\"",
":",
"name",
"if",
"len",
"(",
"desc",
")",
"=... | Create organization on the DCNM.
:param orch_id: orchestrator ID
:param name: Name of organization
:param desc: Description of organization | [
"Create",
"organization",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L208-L221 | train | 37,633 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._create_or_update_partition | def _create_or_update_partition(self, org_name, part_name, desc,
dci_id=UNKNOWN_DCI_ID, vrf_prof=None,
service_node_ip=UNKNOWN_SRVN_NODE_IP,
operation='POST'):
"""Send create or update partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
:param desc: description of partition
:dci_id: DCI ID for inter-DC
:vrf_prof: VRF Profile Name
:service_node_ip: Service Node's Address
"""
if part_name is None:
part_name = self._part_name
if vrf_prof is None or dci_id == UNKNOWN_DCI_ID or (
service_node_ip == UNKNOWN_SRVN_NODE_IP):
part_info = self._get_partition(org_name, part_name)
if vrf_prof is None:
vrf_prof = self.get_partition_vrfProf(org_name, part_name,
part_info=part_info)
if dci_id == UNKNOWN_DCI_ID:
dci_id = self.get_partition_dciId(org_name, part_name,
part_info=part_info)
if service_node_ip == UNKNOWN_SRVN_NODE_IP:
service_node_ip = self.get_partition_serviceNodeIp(
org_name, part_name, part_info=part_info)
url = ((self._create_part_url % (org_name)) if operation == 'POST' else
self._update_part_url % (org_name, part_name))
payload = {
"partitionName": part_name,
"description": part_name if len(desc) == 0 else desc,
"serviceNodeIpAddress": service_node_ip,
"organizationName": org_name}
# Check the DCNM version and find out whether it is need to have
# extra payload for the new version when creating/updating a partition.
if self._is_iplus:
# Need to add extra payload for the new version.
enable_dci = "true" if dci_id and int(dci_id) != 0 else "false"
extra_payload = {
"vrfProfileName": vrf_prof,
"vrfName": ':'.join((org_name, part_name)),
"dciId": dci_id,
"enableDCIExtension": enable_dci}
payload.update(extra_payload)
return self._send_request(operation, url, payload, 'partition') | python | def _create_or_update_partition(self, org_name, part_name, desc,
dci_id=UNKNOWN_DCI_ID, vrf_prof=None,
service_node_ip=UNKNOWN_SRVN_NODE_IP,
operation='POST'):
"""Send create or update partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
:param desc: description of partition
:dci_id: DCI ID for inter-DC
:vrf_prof: VRF Profile Name
:service_node_ip: Service Node's Address
"""
if part_name is None:
part_name = self._part_name
if vrf_prof is None or dci_id == UNKNOWN_DCI_ID or (
service_node_ip == UNKNOWN_SRVN_NODE_IP):
part_info = self._get_partition(org_name, part_name)
if vrf_prof is None:
vrf_prof = self.get_partition_vrfProf(org_name, part_name,
part_info=part_info)
if dci_id == UNKNOWN_DCI_ID:
dci_id = self.get_partition_dciId(org_name, part_name,
part_info=part_info)
if service_node_ip == UNKNOWN_SRVN_NODE_IP:
service_node_ip = self.get_partition_serviceNodeIp(
org_name, part_name, part_info=part_info)
url = ((self._create_part_url % (org_name)) if operation == 'POST' else
self._update_part_url % (org_name, part_name))
payload = {
"partitionName": part_name,
"description": part_name if len(desc) == 0 else desc,
"serviceNodeIpAddress": service_node_ip,
"organizationName": org_name}
# Check the DCNM version and find out whether it is need to have
# extra payload for the new version when creating/updating a partition.
if self._is_iplus:
# Need to add extra payload for the new version.
enable_dci = "true" if dci_id and int(dci_id) != 0 else "false"
extra_payload = {
"vrfProfileName": vrf_prof,
"vrfName": ':'.join((org_name, part_name)),
"dciId": dci_id,
"enableDCIExtension": enable_dci}
payload.update(extra_payload)
return self._send_request(operation, url, payload, 'partition') | [
"def",
"_create_or_update_partition",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"desc",
",",
"dci_id",
"=",
"UNKNOWN_DCI_ID",
",",
"vrf_prof",
"=",
"None",
",",
"service_node_ip",
"=",
"UNKNOWN_SRVN_NODE_IP",
",",
"operation",
"=",
"'POST'",
")",
":",... | Send create or update partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
:param desc: description of partition
:dci_id: DCI ID for inter-DC
:vrf_prof: VRF Profile Name
:service_node_ip: Service Node's Address | [
"Send",
"create",
"or",
"update",
"partition",
"request",
"to",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L223-L271 | train | 37,634 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._get_partition | def _get_partition(self, org_name, part_name=None):
"""send get partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
"""
if part_name is None:
part_name = self._part_name
url = self._update_part_url % (org_name, part_name)
res = self._send_request("GET", url, '', 'partition')
if res and res.status_code in self._resp_ok:
return res.json() | python | def _get_partition(self, org_name, part_name=None):
"""send get partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition
"""
if part_name is None:
part_name = self._part_name
url = self._update_part_url % (org_name, part_name)
res = self._send_request("GET", url, '', 'partition')
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"_get_partition",
"(",
"self",
",",
"org_name",
",",
"part_name",
"=",
"None",
")",
":",
"if",
"part_name",
"is",
"None",
":",
"part_name",
"=",
"self",
".",
"_part_name",
"url",
"=",
"self",
".",
"_update_part_url",
"%",
"(",
"org_name",
",",
"pa... | send get partition request to the DCNM.
:param org_name: name of organization
:param part_name: name of partition | [
"send",
"get",
"partition",
"request",
"to",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L273-L284 | train | 37,635 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.update_partition_static_route | def update_partition_static_route(self, org_name, part_name,
static_ip_list, vrf_prof=None,
service_node_ip=None):
"""Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service Node IP address
"""
if part_name is None:
part_name = self._part_name
if vrf_prof is None:
vrf_prof = self.default_vrf_profile
operation = 'PUT'
url = (self._update_part_url % (org_name, part_name))
ip_str = ''
ip_cnt = 0
for ip in static_ip_list:
ip_sub = "$n0" + str(ip_cnt) + "=" + str(ip) + ";"
ip_str = ip_str + ip_sub
ip_cnt = ip_cnt + 1
cfg_args = {
"$vrfName=" + org_name + ':' + part_name + ";"
"$include_serviceNodeIpAddress=" + service_node_ip + ";" + ip_str
}
cfg_args = ';'.join(cfg_args)
payload = {
"partitionName": part_name,
"organizationName": org_name,
"dciExtensionStatus": "Not configured",
"vrfProfileName": vrf_prof,
"vrfName": ':'.join((org_name, part_name)),
"configArg": cfg_args}
res = self._send_request(operation, url, payload, 'partition')
return (res is not None and res.status_code in self._resp_ok) | python | def update_partition_static_route(self, org_name, part_name,
static_ip_list, vrf_prof=None,
service_node_ip=None):
"""Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service Node IP address
"""
if part_name is None:
part_name = self._part_name
if vrf_prof is None:
vrf_prof = self.default_vrf_profile
operation = 'PUT'
url = (self._update_part_url % (org_name, part_name))
ip_str = ''
ip_cnt = 0
for ip in static_ip_list:
ip_sub = "$n0" + str(ip_cnt) + "=" + str(ip) + ";"
ip_str = ip_str + ip_sub
ip_cnt = ip_cnt + 1
cfg_args = {
"$vrfName=" + org_name + ':' + part_name + ";"
"$include_serviceNodeIpAddress=" + service_node_ip + ";" + ip_str
}
cfg_args = ';'.join(cfg_args)
payload = {
"partitionName": part_name,
"organizationName": org_name,
"dciExtensionStatus": "Not configured",
"vrfProfileName": vrf_prof,
"vrfName": ':'.join((org_name, part_name)),
"configArg": cfg_args}
res = self._send_request(operation, url, payload, 'partition')
return (res is not None and res.status_code in self._resp_ok) | [
"def",
"update_partition_static_route",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"static_ip_list",
",",
"vrf_prof",
"=",
"None",
",",
"service_node_ip",
"=",
"None",
")",
":",
"if",
"part_name",
"is",
"None",
":",
"part_name",
"=",
"self",
".",
"... | Send static route update requests to DCNM.
:param org_name: name of organization
:param part_name: name of partition
:static_ip_list: List of static IP addresses
:vrf_prof: VRF Profile
:service_node_ip: Service Node IP address | [
"Send",
"static",
"route",
"update",
"requests",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L286-L323 | train | 37,636 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._delete_org | def _delete_org(self, org_name):
"""Send organization delete request to DCNM.
:param org_name: name of organization to be deleted
"""
url = self._del_org_url % (org_name)
return self._send_request('DELETE', url, '', 'organization') | python | def _delete_org(self, org_name):
"""Send organization delete request to DCNM.
:param org_name: name of organization to be deleted
"""
url = self._del_org_url % (org_name)
return self._send_request('DELETE', url, '', 'organization') | [
"def",
"_delete_org",
"(",
"self",
",",
"org_name",
")",
":",
"url",
"=",
"self",
".",
"_del_org_url",
"%",
"(",
"org_name",
")",
"return",
"self",
".",
"_send_request",
"(",
"'DELETE'",
",",
"url",
",",
"''",
",",
"'organization'",
")"
] | Send organization delete request to DCNM.
:param org_name: name of organization to be deleted | [
"Send",
"organization",
"delete",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L325-L331 | train | 37,637 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._delete_network | def _delete_network(self, network_info):
"""Send network delete request to DCNM.
:param network_info: contains network info to be deleted.
"""
org_name = network_info.get('organizationName', '')
part_name = network_info.get('partitionName', '')
segment_id = network_info['segmentId']
if 'mobDomainName' in network_info:
vlan_id = network_info['vlanId']
mob_dom_name = network_info['mobDomainName']
url = self._network_mob_url % (org_name, part_name, vlan_id,
mob_dom_name)
else:
url = self._network_url % (org_name, part_name, segment_id)
return self._send_request('DELETE', url, '', 'network') | python | def _delete_network(self, network_info):
"""Send network delete request to DCNM.
:param network_info: contains network info to be deleted.
"""
org_name = network_info.get('organizationName', '')
part_name = network_info.get('partitionName', '')
segment_id = network_info['segmentId']
if 'mobDomainName' in network_info:
vlan_id = network_info['vlanId']
mob_dom_name = network_info['mobDomainName']
url = self._network_mob_url % (org_name, part_name, vlan_id,
mob_dom_name)
else:
url = self._network_url % (org_name, part_name, segment_id)
return self._send_request('DELETE', url, '', 'network') | [
"def",
"_delete_network",
"(",
"self",
",",
"network_info",
")",
":",
"org_name",
"=",
"network_info",
".",
"get",
"(",
"'organizationName'",
",",
"''",
")",
"part_name",
"=",
"network_info",
".",
"get",
"(",
"'partitionName'",
",",
"''",
")",
"segment_id",
... | Send network delete request to DCNM.
:param network_info: contains network info to be deleted. | [
"Send",
"network",
"delete",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L342-L357 | train | 37,638 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._get_network | def _get_network(self, network_info):
"""Send network get request to DCNM.
:param network_info: contains network info to query.
"""
org_name = network_info.get('organizationName', '')
part_name = network_info.get('partitionName', '')
segment_id = network_info['segmentId']
url = self._network_url % (org_name, part_name, segment_id)
return self._send_request('GET', url, '', 'network') | python | def _get_network(self, network_info):
"""Send network get request to DCNM.
:param network_info: contains network info to query.
"""
org_name = network_info.get('organizationName', '')
part_name = network_info.get('partitionName', '')
segment_id = network_info['segmentId']
url = self._network_url % (org_name, part_name, segment_id)
return self._send_request('GET', url, '', 'network') | [
"def",
"_get_network",
"(",
"self",
",",
"network_info",
")",
":",
"org_name",
"=",
"network_info",
".",
"get",
"(",
"'organizationName'",
",",
"''",
")",
"part_name",
"=",
"network_info",
".",
"get",
"(",
"'partitionName'",
",",
"''",
")",
"segment_id",
"="... | Send network get request to DCNM.
:param network_info: contains network info to query. | [
"Send",
"network",
"get",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L359-L368 | train | 37,639 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._login_request | def _login_request(self, url_login):
"""Internal function to send login request. """
expiration_time = self._exp_time
payload = {'expirationTime': expiration_time}
# TODO(padkrish), after testing with certificates, make the
# verify option configurable.
res = requests.post(url_login,
data=jsonutils.dumps(payload),
headers=self._req_headers,
auth=(self._user, self._pwd),
timeout=self.timeout_resp, verify=False)
session_id = ''
if res and res.status_code in self._resp_ok:
session_id = res.json().get('Dcnm-Token')
self._req_headers.update({'Dcnm-Token': session_id}) | python | def _login_request(self, url_login):
"""Internal function to send login request. """
expiration_time = self._exp_time
payload = {'expirationTime': expiration_time}
# TODO(padkrish), after testing with certificates, make the
# verify option configurable.
res = requests.post(url_login,
data=jsonutils.dumps(payload),
headers=self._req_headers,
auth=(self._user, self._pwd),
timeout=self.timeout_resp, verify=False)
session_id = ''
if res and res.status_code in self._resp_ok:
session_id = res.json().get('Dcnm-Token')
self._req_headers.update({'Dcnm-Token': session_id}) | [
"def",
"_login_request",
"(",
"self",
",",
"url_login",
")",
":",
"expiration_time",
"=",
"self",
".",
"_exp_time",
"payload",
"=",
"{",
"'expirationTime'",
":",
"expiration_time",
"}",
"# TODO(padkrish), after testing with certificates, make the",
"# verify option configur... | Internal function to send login request. | [
"Internal",
"function",
"to",
"send",
"login",
"request",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L370-L385 | train | 37,640 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._logout_request | def _logout_request(self, url_logout):
"""Internal logout request to DCNM. """
requests.post(url_logout,
headers=self._req_headers,
timeout=self.timeout_resp, verify=False) | python | def _logout_request(self, url_logout):
"""Internal logout request to DCNM. """
requests.post(url_logout,
headers=self._req_headers,
timeout=self.timeout_resp, verify=False) | [
"def",
"_logout_request",
"(",
"self",
",",
"url_logout",
")",
":",
"requests",
".",
"post",
"(",
"url_logout",
",",
"headers",
"=",
"self",
".",
"_req_headers",
",",
"timeout",
"=",
"self",
".",
"timeout_resp",
",",
"verify",
"=",
"False",
")"
] | Internal logout request to DCNM. | [
"Internal",
"logout",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L392-L397 | train | 37,641 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient._send_request | def _send_request(self, operation, url, payload, desc):
"""Send request to DCNM."""
res = None
try:
payload_json = None
if payload and payload != '':
payload_json = jsonutils.dumps(payload)
self._login()
desc_lookup = {'POST': ' creation', 'PUT': ' update',
'DELETE': ' deletion', 'GET': ' get'}
res = requests.request(operation, url, data=payload_json,
headers=self._req_headers,
timeout=self.timeout_resp, verify=False)
desc += desc_lookup.get(operation, operation.lower())
LOG.info("DCNM-send_request: %(desc)s %(url)s %(pld)s",
{'desc': desc, 'url': url, 'pld': payload})
self._logout()
except (requests.HTTPError, requests.Timeout,
requests.ConnectionError) as exc:
LOG.exception('Error during request: %s', exc)
raise dexc.DfaClientRequestFailed(reason=exc)
return res | python | def _send_request(self, operation, url, payload, desc):
"""Send request to DCNM."""
res = None
try:
payload_json = None
if payload and payload != '':
payload_json = jsonutils.dumps(payload)
self._login()
desc_lookup = {'POST': ' creation', 'PUT': ' update',
'DELETE': ' deletion', 'GET': ' get'}
res = requests.request(operation, url, data=payload_json,
headers=self._req_headers,
timeout=self.timeout_resp, verify=False)
desc += desc_lookup.get(operation, operation.lower())
LOG.info("DCNM-send_request: %(desc)s %(url)s %(pld)s",
{'desc': desc, 'url': url, 'pld': payload})
self._logout()
except (requests.HTTPError, requests.Timeout,
requests.ConnectionError) as exc:
LOG.exception('Error during request: %s', exc)
raise dexc.DfaClientRequestFailed(reason=exc)
return res | [
"def",
"_send_request",
"(",
"self",
",",
"operation",
",",
"url",
",",
"payload",
",",
"desc",
")",
":",
"res",
"=",
"None",
"try",
":",
"payload_json",
"=",
"None",
"if",
"payload",
"and",
"payload",
"!=",
"''",
":",
"payload_json",
"=",
"jsonutils",
... | Send request to DCNM. | [
"Send",
"request",
"to",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L404-L429 | train | 37,642 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.config_profile_list | def config_profile_list(self):
"""Return config profile list from DCNM."""
these_profiles = self._config_profile_list() or []
profile_list = [q for p in these_profiles for q in
[p.get('profileName')]]
return profile_list | python | def config_profile_list(self):
"""Return config profile list from DCNM."""
these_profiles = self._config_profile_list() or []
profile_list = [q for p in these_profiles for q in
[p.get('profileName')]]
return profile_list | [
"def",
"config_profile_list",
"(",
"self",
")",
":",
"these_profiles",
"=",
"self",
".",
"_config_profile_list",
"(",
")",
"or",
"[",
"]",
"profile_list",
"=",
"[",
"q",
"for",
"p",
"in",
"these_profiles",
"for",
"q",
"in",
"[",
"p",
".",
"get",
"(",
"... | Return config profile list from DCNM. | [
"Return",
"config",
"profile",
"list",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L431-L437 | train | 37,643 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.config_profile_fwding_mode_get | def config_profile_fwding_mode_get(self, profile_name):
"""Return forwarding mode of given config profile."""
profile_params = self._config_profile_get(profile_name)
fwd_cli = 'fabric forwarding mode proxy-gateway'
if profile_params and fwd_cli in profile_params['configCommands']:
return 'proxy-gateway'
else:
return 'anycast-gateway' | python | def config_profile_fwding_mode_get(self, profile_name):
"""Return forwarding mode of given config profile."""
profile_params = self._config_profile_get(profile_name)
fwd_cli = 'fabric forwarding mode proxy-gateway'
if profile_params and fwd_cli in profile_params['configCommands']:
return 'proxy-gateway'
else:
return 'anycast-gateway' | [
"def",
"config_profile_fwding_mode_get",
"(",
"self",
",",
"profile_name",
")",
":",
"profile_params",
"=",
"self",
".",
"_config_profile_get",
"(",
"profile_name",
")",
"fwd_cli",
"=",
"'fabric forwarding mode proxy-gateway'",
"if",
"profile_params",
"and",
"fwd_cli",
... | Return forwarding mode of given config profile. | [
"Return",
"forwarding",
"mode",
"of",
"given",
"config",
"profile",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L439-L447 | train | 37,644 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_config_profile_for_network | def get_config_profile_for_network(self, net_name):
"""Get the list of profiles."""
cfgplist = self.config_profile_list()
cfgname = net_name.partition(':')[2]
cfgtuple = set()
for cfg_prof in cfgplist:
if cfg_prof.startswith('defaultNetwork'):
cfg_alias = (cfg_prof.split('defaultNetwork')[1].
split('Profile')[0])
elif cfg_prof.endswith('Profile'):
cfg_alias = cfg_prof.split('Profile')[0]
else:
cfg_alias = cfg_prof
cfgtuple.update([(cfg_prof, cfg_alias)])
cfgp = [a for a, b in cfgtuple if cfgname == b]
prof = cfgp[0] if cfgp else self.default_cfg_profile
fwd_mod = self.config_profile_fwding_mode_get(prof)
return (prof, fwd_mod) | python | def get_config_profile_for_network(self, net_name):
"""Get the list of profiles."""
cfgplist = self.config_profile_list()
cfgname = net_name.partition(':')[2]
cfgtuple = set()
for cfg_prof in cfgplist:
if cfg_prof.startswith('defaultNetwork'):
cfg_alias = (cfg_prof.split('defaultNetwork')[1].
split('Profile')[0])
elif cfg_prof.endswith('Profile'):
cfg_alias = cfg_prof.split('Profile')[0]
else:
cfg_alias = cfg_prof
cfgtuple.update([(cfg_prof, cfg_alias)])
cfgp = [a for a, b in cfgtuple if cfgname == b]
prof = cfgp[0] if cfgp else self.default_cfg_profile
fwd_mod = self.config_profile_fwding_mode_get(prof)
return (prof, fwd_mod) | [
"def",
"get_config_profile_for_network",
"(",
"self",
",",
"net_name",
")",
":",
"cfgplist",
"=",
"self",
".",
"config_profile_list",
"(",
")",
"cfgname",
"=",
"net_name",
".",
"partition",
"(",
"':'",
")",
"[",
"2",
"]",
"cfgtuple",
"=",
"set",
"(",
")",
... | Get the list of profiles. | [
"Get",
"the",
"list",
"of",
"profiles",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L449-L468 | train | 37,645 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.delete_network | def delete_network(self, tenant_name, network):
"""Delete network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters
"""
seg_id = network.segmentation_id
network_info = {
'organizationName': tenant_name,
'partitionName': self._part_name,
'segmentId': seg_id,
}
LOG.debug("Deleting %s network in DCNM.", network_info)
res = self._delete_network(network_info)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s network in DCNM.", network_info)
else:
LOG.error("Failed to delete %s network in DCNM.",
network_info)
raise dexc.DfaClientRequestFailed(reason=res) | python | def delete_network(self, tenant_name, network):
"""Delete network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters
"""
seg_id = network.segmentation_id
network_info = {
'organizationName': tenant_name,
'partitionName': self._part_name,
'segmentId': seg_id,
}
LOG.debug("Deleting %s network in DCNM.", network_info)
res = self._delete_network(network_info)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s network in DCNM.", network_info)
else:
LOG.error("Failed to delete %s network in DCNM.",
network_info)
raise dexc.DfaClientRequestFailed(reason=res) | [
"def",
"delete_network",
"(",
"self",
",",
"tenant_name",
",",
"network",
")",
":",
"seg_id",
"=",
"network",
".",
"segmentation_id",
"network_info",
"=",
"{",
"'organizationName'",
":",
"tenant_name",
",",
"'partitionName'",
":",
"self",
".",
"_part_name",
",",... | Delete network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters | [
"Delete",
"network",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L615-L635 | train | 37,646 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.delete_service_network | def delete_service_network(self, tenant_name, network):
"""Delete service network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters
"""
network_info = {}
part_name = network.part_name
if not part_name:
part_name = self._part_name
seg_id = str(network.segmentation_id)
if network.vlan:
vlan_id = str(network.vlan)
if network.mob_domain_name is not None:
mob_domain_name = network.mob_domain_name
else:
# The current way will not work since _default_md is obtained
# during create_service_network. It's preferrable to get it
# during init TODO(padkrish)
if self._default_md is None:
self._set_default_mobility_domain()
mob_domain_name = self._default_md
network_info = {
'organizationName': tenant_name,
'partitionName': part_name,
'mobDomainName': mob_domain_name,
'vlanId': vlan_id,
'segmentId': seg_id,
}
else:
network_info = {
'organizationName': tenant_name,
'partitionName': part_name,
'segmentId': seg_id,
}
LOG.debug("Deleting %s network in DCNM.", network_info)
res = self._delete_network(network_info)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s network in DCNM.", network_info)
else:
LOG.error("Failed to delete %s network in DCNM.",
network_info)
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | python | def delete_service_network(self, tenant_name, network):
"""Delete service network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters
"""
network_info = {}
part_name = network.part_name
if not part_name:
part_name = self._part_name
seg_id = str(network.segmentation_id)
if network.vlan:
vlan_id = str(network.vlan)
if network.mob_domain_name is not None:
mob_domain_name = network.mob_domain_name
else:
# The current way will not work since _default_md is obtained
# during create_service_network. It's preferrable to get it
# during init TODO(padkrish)
if self._default_md is None:
self._set_default_mobility_domain()
mob_domain_name = self._default_md
network_info = {
'organizationName': tenant_name,
'partitionName': part_name,
'mobDomainName': mob_domain_name,
'vlanId': vlan_id,
'segmentId': seg_id,
}
else:
network_info = {
'organizationName': tenant_name,
'partitionName': part_name,
'segmentId': seg_id,
}
LOG.debug("Deleting %s network in DCNM.", network_info)
res = self._delete_network(network_info)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s network in DCNM.", network_info)
else:
LOG.error("Failed to delete %s network in DCNM.",
network_info)
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | [
"def",
"delete_service_network",
"(",
"self",
",",
"tenant_name",
",",
"network",
")",
":",
"network_info",
"=",
"{",
"}",
"part_name",
"=",
"network",
".",
"part_name",
"if",
"not",
"part_name",
":",
"part_name",
"=",
"self",
".",
"_part_name",
"seg_id",
"=... | Delete service network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: object that contains network parameters | [
"Delete",
"service",
"network",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L637-L681 | train | 37,647 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.delete_project | def delete_project(self, tenant_name, part_name):
"""Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition.
"""
res = self._delete_partition(tenant_name, part_name)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s partition in DCNM.", part_name)
else:
LOG.error("Failed to delete %(part)s partition in DCNM."
"Response: %(res)s", {'part': part_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res)
res = self._delete_org(tenant_name)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s organization in DCNM.", tenant_name)
else:
LOG.error("Failed to delete %(org)s organization in DCNM."
"Response: %(res)s", {'org': tenant_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res) | python | def delete_project(self, tenant_name, part_name):
"""Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition.
"""
res = self._delete_partition(tenant_name, part_name)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s partition in DCNM.", part_name)
else:
LOG.error("Failed to delete %(part)s partition in DCNM."
"Response: %(res)s", {'part': part_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res)
res = self._delete_org(tenant_name)
if res and res.status_code in self._resp_ok:
LOG.debug("Deleted %s organization in DCNM.", tenant_name)
else:
LOG.error("Failed to delete %(org)s organization in DCNM."
"Response: %(res)s", {'org': tenant_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res) | [
"def",
"delete_project",
"(",
"self",
",",
"tenant_name",
",",
"part_name",
")",
":",
"res",
"=",
"self",
".",
"_delete_partition",
"(",
"tenant_name",
",",
"part_name",
")",
"if",
"res",
"and",
"res",
".",
"status_code",
"in",
"self",
".",
"_resp_ok",
":"... | Delete project on the DCNM.
:param tenant_name: name of project.
:param part_name: name of partition. | [
"Delete",
"project",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L683-L703 | train | 37,648 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.create_project | def create_project(self, orch_id, org_name, part_name, dci_id, desc=None):
"""Create project on the DCNM.
:param orch_id: orchestrator ID
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project.
"""
desc = desc or org_name
res = self._create_org(orch_id, org_name, desc)
if res and res.status_code in self._resp_ok:
LOG.debug("Created %s organization in DCNM.", org_name)
else:
LOG.error("Failed to create %(org)s organization in DCNM."
"Response: %(res)s", {'org': org_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res)
self.create_partition(org_name, part_name, dci_id,
self.default_vrf_profile, desc=desc) | python | def create_project(self, orch_id, org_name, part_name, dci_id, desc=None):
"""Create project on the DCNM.
:param orch_id: orchestrator ID
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project.
"""
desc = desc or org_name
res = self._create_org(orch_id, org_name, desc)
if res and res.status_code in self._resp_ok:
LOG.debug("Created %s organization in DCNM.", org_name)
else:
LOG.error("Failed to create %(org)s organization in DCNM."
"Response: %(res)s", {'org': org_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res)
self.create_partition(org_name, part_name, dci_id,
self.default_vrf_profile, desc=desc) | [
"def",
"create_project",
"(",
"self",
",",
"orch_id",
",",
"org_name",
",",
"part_name",
",",
"dci_id",
",",
"desc",
"=",
"None",
")",
":",
"desc",
"=",
"desc",
"or",
"org_name",
"res",
"=",
"self",
".",
"_create_org",
"(",
"orch_id",
",",
"org_name",
... | Create project on the DCNM.
:param orch_id: orchestrator ID
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project. | [
"Create",
"project",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L719-L738 | train | 37,649 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.update_project | def update_project(self, org_name, part_name, dci_id=UNKNOWN_DCI_ID,
service_node_ip=UNKNOWN_SRVN_NODE_IP,
vrf_prof=None, desc=None):
"""Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project.
"""
desc = desc or org_name
res = self._create_or_update_partition(org_name, part_name, desc,
dci_id=dci_id,
service_node_ip=service_node_ip,
vrf_prof=vrf_prof,
operation='PUT')
if res and res.status_code in self._resp_ok:
LOG.debug("Update %s partition in DCNM.", part_name)
else:
LOG.error("Failed to update %(part)s partition in DCNM."
"Response: %(res)s", {'part': part_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res) | python | def update_project(self, org_name, part_name, dci_id=UNKNOWN_DCI_ID,
service_node_ip=UNKNOWN_SRVN_NODE_IP,
vrf_prof=None, desc=None):
"""Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project.
"""
desc = desc or org_name
res = self._create_or_update_partition(org_name, part_name, desc,
dci_id=dci_id,
service_node_ip=service_node_ip,
vrf_prof=vrf_prof,
operation='PUT')
if res and res.status_code in self._resp_ok:
LOG.debug("Update %s partition in DCNM.", part_name)
else:
LOG.error("Failed to update %(part)s partition in DCNM."
"Response: %(res)s", {'part': part_name, 'res': res})
raise dexc.DfaClientRequestFailed(reason=res) | [
"def",
"update_project",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"dci_id",
"=",
"UNKNOWN_DCI_ID",
",",
"service_node_ip",
"=",
"UNKNOWN_SRVN_NODE_IP",
",",
"vrf_prof",
"=",
"None",
",",
"desc",
"=",
"None",
")",
":",
"desc",
"=",
"desc",
"or",
... | Update project on the DCNM.
:param org_name: name of organization.
:param part_name: name of partition.
:param dci_id: Data Center interconnect id.
:param desc: description of project. | [
"Update",
"project",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L740-L761 | train | 37,650 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.create_partition | def create_partition(self, org_name, part_name, dci_id, vrf_prof,
service_node_ip=None, desc=None):
"""Create partition on the DCNM.
:param org_name: name of organization to be created
:param part_name: name of partition to be created
:param dci_id: DCI ID
:vrf_prof: VRF profile for the partition
:param service_node_ip: Specifies the Default route IP address.
:param desc: string that describes organization
"""
desc = desc or org_name
res = self._create_or_update_partition(org_name, part_name,
desc, dci_id=dci_id,
service_node_ip=service_node_ip,
vrf_prof=vrf_prof)
if res and res.status_code in self._resp_ok:
LOG.debug("Created %s partition in DCNM.", part_name)
else:
LOG.error("Failed to create %(part)s partition in DCNM."
"Response: %(res)s", ({'part': part_name, 'res': res}))
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | python | def create_partition(self, org_name, part_name, dci_id, vrf_prof,
service_node_ip=None, desc=None):
"""Create partition on the DCNM.
:param org_name: name of organization to be created
:param part_name: name of partition to be created
:param dci_id: DCI ID
:vrf_prof: VRF profile for the partition
:param service_node_ip: Specifies the Default route IP address.
:param desc: string that describes organization
"""
desc = desc or org_name
res = self._create_or_update_partition(org_name, part_name,
desc, dci_id=dci_id,
service_node_ip=service_node_ip,
vrf_prof=vrf_prof)
if res and res.status_code in self._resp_ok:
LOG.debug("Created %s partition in DCNM.", part_name)
else:
LOG.error("Failed to create %(part)s partition in DCNM."
"Response: %(res)s", ({'part': part_name, 'res': res}))
raise dexc.DfaClientRequestFailed(reason=self._failure_msg(res)) | [
"def",
"create_partition",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"dci_id",
",",
"vrf_prof",
",",
"service_node_ip",
"=",
"None",
",",
"desc",
"=",
"None",
")",
":",
"desc",
"=",
"desc",
"or",
"org_name",
"res",
"=",
"self",
".",
"_create_o... | Create partition on the DCNM.
:param org_name: name of organization to be created
:param part_name: name of partition to be created
:param dci_id: DCI ID
:vrf_prof: VRF profile for the partition
:param service_node_ip: Specifies the Default route IP address.
:param desc: string that describes organization | [
"Create",
"partition",
"on",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L763-L784 | train | 37,651 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_partition_vrfProf | def get_partition_vrfProf(self, org_name, part_name=None, part_info=None):
"""get VRF Profile for the partition from the DCNM.
:param org_name: name of organization
:param part_name: name of partition
"""
vrf_profile = None
if part_info is None:
part_info = self._get_partition(org_name, part_name)
LOG.info("query result from dcnm for partition info is %s",
part_info)
if ("vrfProfileName" in part_info):
vrf_profile = part_info.get("vrfProfileName")
return vrf_profile | python | def get_partition_vrfProf(self, org_name, part_name=None, part_info=None):
"""get VRF Profile for the partition from the DCNM.
:param org_name: name of organization
:param part_name: name of partition
"""
vrf_profile = None
if part_info is None:
part_info = self._get_partition(org_name, part_name)
LOG.info("query result from dcnm for partition info is %s",
part_info)
if ("vrfProfileName" in part_info):
vrf_profile = part_info.get("vrfProfileName")
return vrf_profile | [
"def",
"get_partition_vrfProf",
"(",
"self",
",",
"org_name",
",",
"part_name",
"=",
"None",
",",
"part_info",
"=",
"None",
")",
":",
"vrf_profile",
"=",
"None",
"if",
"part_info",
"is",
"None",
":",
"part_info",
"=",
"self",
".",
"_get_partition",
"(",
"o... | get VRF Profile for the partition from the DCNM.
:param org_name: name of organization
:param part_name: name of partition | [
"get",
"VRF",
"Profile",
"for",
"the",
"partition",
"from",
"the",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L786-L799 | train | 37,652 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_partition_dciId | def get_partition_dciId(self, org_name, part_name, part_info=None):
"""get DCI ID for the partition.
:param org_name: name of organization
:param part_name: name of partition
"""
if part_info is None:
part_info = self._get_partition(org_name, part_name)
LOG.info("query result from dcnm for partition info is %s",
part_info)
if part_info is not None and "dciId" in part_info:
return part_info.get("dciId") | python | def get_partition_dciId(self, org_name, part_name, part_info=None):
"""get DCI ID for the partition.
:param org_name: name of organization
:param part_name: name of partition
"""
if part_info is None:
part_info = self._get_partition(org_name, part_name)
LOG.info("query result from dcnm for partition info is %s",
part_info)
if part_info is not None and "dciId" in part_info:
return part_info.get("dciId") | [
"def",
"get_partition_dciId",
"(",
"self",
",",
"org_name",
",",
"part_name",
",",
"part_info",
"=",
"None",
")",
":",
"if",
"part_info",
"is",
"None",
":",
"part_info",
"=",
"self",
".",
"_get_partition",
"(",
"org_name",
",",
"part_name",
")",
"LOG",
"."... | get DCI ID for the partition.
:param org_name: name of organization
:param part_name: name of partition | [
"get",
"DCI",
"ID",
"for",
"the",
"partition",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L801-L812 | train | 37,653 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.list_networks | def list_networks(self, org, part):
"""Return list of networks from DCNM.
:param org: name of organization.
:param part: name of partition.
"""
if org and part:
list_url = self._del_part + '/networks'
list_url = list_url % (org, part)
res = self._send_request('GET', list_url, '', 'networks')
if res and res.status_code in self._resp_ok:
return res.json() | python | def list_networks(self, org, part):
"""Return list of networks from DCNM.
:param org: name of organization.
:param part: name of partition.
"""
if org and part:
list_url = self._del_part + '/networks'
list_url = list_url % (org, part)
res = self._send_request('GET', list_url, '', 'networks')
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"list_networks",
"(",
"self",
",",
"org",
",",
"part",
")",
":",
"if",
"org",
"and",
"part",
":",
"list_url",
"=",
"self",
".",
"_del_part",
"+",
"'/networks'",
"list_url",
"=",
"list_url",
"%",
"(",
"org",
",",
"part",
")",
"res",
"=",
"self"... | Return list of networks from DCNM.
:param org: name of organization.
:param part: name of partition. | [
"Return",
"list",
"of",
"networks",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L840-L851 | train | 37,654 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.list_organizations | def list_organizations(self):
"""Return list of organizations from DCNM."""
try:
res = self._send_request('GET', self._org_url, '', 'organizations')
if res and res.status_code in self._resp_ok:
return res.json()
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.") | python | def list_organizations(self):
"""Return list of organizations from DCNM."""
try:
res = self._send_request('GET', self._org_url, '', 'organizations')
if res and res.status_code in self._resp_ok:
return res.json()
except dexc.DfaClientRequestFailed:
LOG.error("Failed to send request to DCNM.") | [
"def",
"list_organizations",
"(",
"self",
")",
":",
"try",
":",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
",",
"self",
".",
"_org_url",
",",
"''",
",",
"'organizations'",
")",
"if",
"res",
"and",
"res",
".",
"status_code",
"in",
"self",
"... | Return list of organizations from DCNM. | [
"Return",
"list",
"of",
"organizations",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L853-L861 | train | 37,655 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_network | def get_network(self, org, segid):
"""Return given network from DCNM.
:param org: name of organization.
:param segid: segmentation id of the network.
"""
network_info = {
'organizationName': org,
'partitionName': self._part_name,
'segmentId': segid,
}
res = self._get_network(network_info)
if res and res.status_code in self._resp_ok:
return res.json() | python | def get_network(self, org, segid):
"""Return given network from DCNM.
:param org: name of organization.
:param segid: segmentation id of the network.
"""
network_info = {
'organizationName': org,
'partitionName': self._part_name,
'segmentId': segid,
}
res = self._get_network(network_info)
if res and res.status_code in self._resp_ok:
return res.json() | [
"def",
"get_network",
"(",
"self",
",",
"org",
",",
"segid",
")",
":",
"network_info",
"=",
"{",
"'organizationName'",
":",
"org",
",",
"'partitionName'",
":",
"self",
".",
"_part_name",
",",
"'segmentId'",
":",
"segid",
",",
"}",
"res",
"=",
"self",
"."... | Return given network from DCNM.
:param org: name of organization.
:param segid: segmentation id of the network. | [
"Return",
"given",
"network",
"from",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L863-L876 | train | 37,656 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.get_version | def get_version(self):
"""Get the DCNM version."""
url = '%s://%s/rest/dcnm-version' % (self.dcnm_protocol, self._ip)
payload = {}
try:
res = self._send_request('GET', url, payload, 'dcnm-version')
if res and res.status_code in self._resp_ok:
return res.json().get('Dcnm-Version')
except dexc.DfaClientRequestFailed as exc:
LOG.error("Failed to get DCNM version.")
sys.exit("ERROR: Failed to connect to DCNM: %s", exc) | python | def get_version(self):
"""Get the DCNM version."""
url = '%s://%s/rest/dcnm-version' % (self.dcnm_protocol, self._ip)
payload = {}
try:
res = self._send_request('GET', url, payload, 'dcnm-version')
if res and res.status_code in self._resp_ok:
return res.json().get('Dcnm-Version')
except dexc.DfaClientRequestFailed as exc:
LOG.error("Failed to get DCNM version.")
sys.exit("ERROR: Failed to connect to DCNM: %s", exc) | [
"def",
"get_version",
"(",
"self",
")",
":",
"url",
"=",
"'%s://%s/rest/dcnm-version'",
"%",
"(",
"self",
".",
"dcnm_protocol",
",",
"self",
".",
"_ip",
")",
"payload",
"=",
"{",
"}",
"try",
":",
"res",
"=",
"self",
".",
"_send_request",
"(",
"'GET'",
... | Get the DCNM version. | [
"Get",
"the",
"DCNM",
"version",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L878-L890 | train | 37,657 |
openstack/networking-cisco | networking_cisco/apps/saf/server/cisco_dfa_rest.py | DFARESTClient.fill_urls | def fill_urls(self):
"""This assigns the URL's based on the protocol. """
protocol = self.dcnm_protocol
self._org_url = '%s://%s/rest/auto-config/organizations' % (
(protocol, self._ip))
self._create_network_url = ('%s://%s/' % (protocol, self._ip) +
'rest/auto-config/organizations'
'/%s/partitions/%s/networks')
self.host_protocol_url = '%s://%s/' % (protocol, self._ip)
self._create_network_url = self._build_url(
'rest/auto-config/organizations'
'/%s/partitions/%s/networks')
self._cfg_profile_list_url = '%s://%s/rest/auto-config/profiles' % (
(protocol, self._ip))
self._cfg_profile_get_url = self._cfg_profile_list_url + '/%s'
self._global_settings_url = self._build_url(
'rest/auto-config/settings')
self._create_part_url = self._build_url(
'rest/auto-config/organizations/%s/partitions')
self._update_part_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/%s')
self._del_org_url = self._build_url(
'rest/auto-config/organizations/%s')
self._del_part = self._build_url(
'rest/auto-config/organizations/%s/partitions/%s')
self._network_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/'
'%s/networks/segment/%s')
self._network_mob_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/'
'%s/networks/vlan/%s/mobility-domain/%s')
self._segmentid_ranges_url = self._build_url(
'rest/settings/segmentid-ranges')
self._login_url = self._build_url('rest/logon')
self._logout_url = self._build_url('rest/logout') | python | def fill_urls(self):
"""This assigns the URL's based on the protocol. """
protocol = self.dcnm_protocol
self._org_url = '%s://%s/rest/auto-config/organizations' % (
(protocol, self._ip))
self._create_network_url = ('%s://%s/' % (protocol, self._ip) +
'rest/auto-config/organizations'
'/%s/partitions/%s/networks')
self.host_protocol_url = '%s://%s/' % (protocol, self._ip)
self._create_network_url = self._build_url(
'rest/auto-config/organizations'
'/%s/partitions/%s/networks')
self._cfg_profile_list_url = '%s://%s/rest/auto-config/profiles' % (
(protocol, self._ip))
self._cfg_profile_get_url = self._cfg_profile_list_url + '/%s'
self._global_settings_url = self._build_url(
'rest/auto-config/settings')
self._create_part_url = self._build_url(
'rest/auto-config/organizations/%s/partitions')
self._update_part_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/%s')
self._del_org_url = self._build_url(
'rest/auto-config/organizations/%s')
self._del_part = self._build_url(
'rest/auto-config/organizations/%s/partitions/%s')
self._network_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/'
'%s/networks/segment/%s')
self._network_mob_url = self._build_url(
'rest/auto-config/organizations/%s/partitions/'
'%s/networks/vlan/%s/mobility-domain/%s')
self._segmentid_ranges_url = self._build_url(
'rest/settings/segmentid-ranges')
self._login_url = self._build_url('rest/logon')
self._logout_url = self._build_url('rest/logout') | [
"def",
"fill_urls",
"(",
"self",
")",
":",
"protocol",
"=",
"self",
".",
"dcnm_protocol",
"self",
".",
"_org_url",
"=",
"'%s://%s/rest/auto-config/organizations'",
"%",
"(",
"(",
"protocol",
",",
"self",
".",
"_ip",
")",
")",
"self",
".",
"_create_network_url"... | This assigns the URL's based on the protocol. | [
"This",
"assigns",
"the",
"URL",
"s",
"based",
"on",
"the",
"protocol",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/cisco_dfa_rest.py#L923-L958 | train | 37,658 |
openstack/networking-cisco | networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/9148d96f9b39_rename_tenantid_to_projectid.py | contract_creation_exceptions | def contract_creation_exceptions():
"""Special migration for the blueprint to support Keystone V3.
We drop all tenant_id columns and create project_id columns instead.
"""
return {
sa.Column: ['.'.join([table, 'project_id']) for table in get_tables()],
sa.Index: get_tables()
} | python | def contract_creation_exceptions():
"""Special migration for the blueprint to support Keystone V3.
We drop all tenant_id columns and create project_id columns instead.
"""
return {
sa.Column: ['.'.join([table, 'project_id']) for table in get_tables()],
sa.Index: get_tables()
} | [
"def",
"contract_creation_exceptions",
"(",
")",
":",
"return",
"{",
"sa",
".",
"Column",
":",
"[",
"'.'",
".",
"join",
"(",
"[",
"table",
",",
"'project_id'",
"]",
")",
"for",
"table",
"in",
"get_tables",
"(",
")",
"]",
",",
"sa",
".",
"Index",
":",... | Special migration for the blueprint to support Keystone V3.
We drop all tenant_id columns and create project_id columns instead. | [
"Special",
"migration",
"for",
"the",
"blueprint",
"to",
"support",
"Keystone",
"V3",
".",
"We",
"drop",
"all",
"tenant_id",
"columns",
"and",
"create",
"project_id",
"columns",
"instead",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/db/migration/alembic_migrations/versions/mitaka/expand/9148d96f9b39_rename_tenantid_to_projectid.py#L133-L140 | train | 37,659 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI._agent_notification_bulk | def _agent_notification_bulk(self, context, method, routers,
hosting_device, operation):
"""Notify the Cisco cfg agent handling a particular hosting_device.
A single notification can contain multiple routers.
"""
admin_context = context.is_admin and context or context.elevated()
dmplugin = bc.get_plugin(cisco_constants.DEVICE_MANAGER)
if (hosting_device is not None and extensions.is_extension_supported(
dmplugin, CFGAGENT_SCHED)):
agents = dmplugin.get_cfg_agents_for_hosting_devices(
admin_context, [hosting_device['id']], admin_state_up=True,
schedule=True)
if agents:
agent = agents[0]
LOG.debug('Notify %(agent_type)s at %(topic)s.%(host)s the '
'message %(method)s [BULK]',
{'agent_type': agent.agent_type,
'topic': CFG_AGENT_L3_ROUTING,
'host': agent.host,
'method': method})
cctxt = self.client.prepare(server=agent.host,
version='1.1')
cctxt.cast(context, method, routers=routers) | python | def _agent_notification_bulk(self, context, method, routers,
hosting_device, operation):
"""Notify the Cisco cfg agent handling a particular hosting_device.
A single notification can contain multiple routers.
"""
admin_context = context.is_admin and context or context.elevated()
dmplugin = bc.get_plugin(cisco_constants.DEVICE_MANAGER)
if (hosting_device is not None and extensions.is_extension_supported(
dmplugin, CFGAGENT_SCHED)):
agents = dmplugin.get_cfg_agents_for_hosting_devices(
admin_context, [hosting_device['id']], admin_state_up=True,
schedule=True)
if agents:
agent = agents[0]
LOG.debug('Notify %(agent_type)s at %(topic)s.%(host)s the '
'message %(method)s [BULK]',
{'agent_type': agent.agent_type,
'topic': CFG_AGENT_L3_ROUTING,
'host': agent.host,
'method': method})
cctxt = self.client.prepare(server=agent.host,
version='1.1')
cctxt.cast(context, method, routers=routers) | [
"def",
"_agent_notification_bulk",
"(",
"self",
",",
"context",
",",
"method",
",",
"routers",
",",
"hosting_device",
",",
"operation",
")",
":",
"admin_context",
"=",
"context",
".",
"is_admin",
"and",
"context",
"or",
"context",
".",
"elevated",
"(",
")",
... | Notify the Cisco cfg agent handling a particular hosting_device.
A single notification can contain multiple routers. | [
"Notify",
"the",
"Cisco",
"cfg",
"agent",
"handling",
"a",
"particular",
"hosting_device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L43-L66 | train | 37,660 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI._notification | def _notification(self, context, method, routers, operation,
shuffle_agents):
"""Notify all or individual Cisco cfg agents."""
if extensions.is_extension_supported(self._l3plugin, L3AGENT_SCHED):
adm_context = (context.is_admin and context or context.elevated())
# This is where hosting device gets scheduled to Cisco cfg agent
self._l3plugin.schedule_routers(adm_context, routers)
self._agent_notification(
context, method, routers, operation, shuffle_agents)
else:
cctxt = self.client.prepare(topics=topics.L3_AGENT, fanout=True)
cctxt.cast(context, method, routers=[r['id'] for r in routers]) | python | def _notification(self, context, method, routers, operation,
shuffle_agents):
"""Notify all or individual Cisco cfg agents."""
if extensions.is_extension_supported(self._l3plugin, L3AGENT_SCHED):
adm_context = (context.is_admin and context or context.elevated())
# This is where hosting device gets scheduled to Cisco cfg agent
self._l3plugin.schedule_routers(adm_context, routers)
self._agent_notification(
context, method, routers, operation, shuffle_agents)
else:
cctxt = self.client.prepare(topics=topics.L3_AGENT, fanout=True)
cctxt.cast(context, method, routers=[r['id'] for r in routers]) | [
"def",
"_notification",
"(",
"self",
",",
"context",
",",
"method",
",",
"routers",
",",
"operation",
",",
"shuffle_agents",
")",
":",
"if",
"extensions",
".",
"is_extension_supported",
"(",
"self",
".",
"_l3plugin",
",",
"L3AGENT_SCHED",
")",
":",
"adm_contex... | Notify all or individual Cisco cfg agents. | [
"Notify",
"all",
"or",
"individual",
"Cisco",
"cfg",
"agents",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L92-L103 | train | 37,661 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI.routers_updated | def routers_updated(self, context, routers, operation=None, data=None,
shuffle_agents=False):
"""Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed.
"""
if routers:
self._notification(context, 'routers_updated', routers, operation,
shuffle_agents) | python | def routers_updated(self, context, routers, operation=None, data=None,
shuffle_agents=False):
"""Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed.
"""
if routers:
self._notification(context, 'routers_updated', routers, operation,
shuffle_agents) | [
"def",
"routers_updated",
"(",
"self",
",",
"context",
",",
"routers",
",",
"operation",
"=",
"None",
",",
"data",
"=",
"None",
",",
"shuffle_agents",
"=",
"False",
")",
":",
"if",
"routers",
":",
"self",
".",
"_notification",
"(",
"context",
",",
"'rout... | Notify cfg agents about configuration changes to routers.
This includes operations performed on the router like when a
router interface is added or removed. | [
"Notify",
"cfg",
"agents",
"about",
"configuration",
"changes",
"to",
"routers",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L110-L119 | train | 37,662 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI.router_removed_from_hosting_device | def router_removed_from_hosting_device(self, context, router):
"""Notify cfg agent about router removed from hosting device."""
self._notification(context, 'router_removed_from_hosting_device',
[router], operation=None, shuffle_agents=False) | python | def router_removed_from_hosting_device(self, context, router):
"""Notify cfg agent about router removed from hosting device."""
self._notification(context, 'router_removed_from_hosting_device',
[router], operation=None, shuffle_agents=False) | [
"def",
"router_removed_from_hosting_device",
"(",
"self",
",",
"context",
",",
"router",
")",
":",
"self",
".",
"_notification",
"(",
"context",
",",
"'router_removed_from_hosting_device'",
",",
"[",
"router",
"]",
",",
"operation",
"=",
"None",
",",
"shuffle_agen... | Notify cfg agent about router removed from hosting device. | [
"Notify",
"cfg",
"agent",
"about",
"router",
"removed",
"from",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L121-L124 | train | 37,663 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI.router_added_to_hosting_device | def router_added_to_hosting_device(self, context, router):
"""Notify cfg agent about router added to hosting device."""
self._notification(context, 'router_added_to_hosting_device',
[router], operation=None, shuffle_agents=False) | python | def router_added_to_hosting_device(self, context, router):
"""Notify cfg agent about router added to hosting device."""
self._notification(context, 'router_added_to_hosting_device',
[router], operation=None, shuffle_agents=False) | [
"def",
"router_added_to_hosting_device",
"(",
"self",
",",
"context",
",",
"router",
")",
":",
"self",
".",
"_notification",
"(",
"context",
",",
"'router_added_to_hosting_device'",
",",
"[",
"router",
"]",
",",
"operation",
"=",
"None",
",",
"shuffle_agents",
"... | Notify cfg agent about router added to hosting device. | [
"Notify",
"cfg",
"agent",
"about",
"router",
"added",
"to",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L126-L129 | train | 37,664 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py | L3RouterCfgAgentNotifyAPI.routers_removed_from_hosting_device | def routers_removed_from_hosting_device(self, context, router_ids,
hosting_device):
"""Notify cfg agent that routers have been removed from hosting device.
@param: context - information about tenant, user etc
@param: router-ids - list of ids
@param: hosting_device - device hosting the routers
"""
self._agent_notification_bulk(
context, 'router_removed_from_hosting_device', router_ids,
hosting_device, operation=None) | python | def routers_removed_from_hosting_device(self, context, router_ids,
hosting_device):
"""Notify cfg agent that routers have been removed from hosting device.
@param: context - information about tenant, user etc
@param: router-ids - list of ids
@param: hosting_device - device hosting the routers
"""
self._agent_notification_bulk(
context, 'router_removed_from_hosting_device', router_ids,
hosting_device, operation=None) | [
"def",
"routers_removed_from_hosting_device",
"(",
"self",
",",
"context",
",",
"router_ids",
",",
"hosting_device",
")",
":",
"self",
".",
"_agent_notification_bulk",
"(",
"context",
",",
"'router_removed_from_hosting_device'",
",",
"router_ids",
",",
"hosting_device",
... | Notify cfg agent that routers have been removed from hosting device.
@param: context - information about tenant, user etc
@param: router-ids - list of ids
@param: hosting_device - device hosting the routers | [
"Notify",
"cfg",
"agent",
"that",
"routers",
"have",
"been",
"removed",
"from",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/rpc/l3_router_rpc_cfg_agent_api.py#L131-L140 | train | 37,665 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_listen_dcnm.py | DCNMListener.process_amqp_msgs | def process_amqp_msgs(self):
"""Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue.
"""
LOG.info('Starting process_amqp_msgs...')
while True:
(mtd_fr, hdr_fr, body) = (None, None, None)
try:
if self.consume_channel:
(mtd_fr, hdr_fr, body) = self.consume_channel.basic_get(
self._dcnm_queue_name)
if mtd_fr:
# Queue has messages.
LOG.info('RX message: %s', body)
self._cb_dcnm_msg(mtd_fr, body)
self.consume_channel.basic_ack(mtd_fr.delivery_tag)
else:
# Queue is empty.
try:
self._conn.sleep(1)
except AttributeError:
time.sleep(1)
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()
tb_str = traceback.format_exception(exc_type,
exc_value, exc_tb)
LOG.exception("Failed to read from queue: %(queue)s "
"%(exc_type)s, %(exc_value)s, %(exc_tb)s.", {
'queue': self._dcnm_queue_name,
'exc_type': exc_type,
'exc_value': exc_value,
'exc_tb': tb_str}) | python | def process_amqp_msgs(self):
"""Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue.
"""
LOG.info('Starting process_amqp_msgs...')
while True:
(mtd_fr, hdr_fr, body) = (None, None, None)
try:
if self.consume_channel:
(mtd_fr, hdr_fr, body) = self.consume_channel.basic_get(
self._dcnm_queue_name)
if mtd_fr:
# Queue has messages.
LOG.info('RX message: %s', body)
self._cb_dcnm_msg(mtd_fr, body)
self.consume_channel.basic_ack(mtd_fr.delivery_tag)
else:
# Queue is empty.
try:
self._conn.sleep(1)
except AttributeError:
time.sleep(1)
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()
tb_str = traceback.format_exception(exc_type,
exc_value, exc_tb)
LOG.exception("Failed to read from queue: %(queue)s "
"%(exc_type)s, %(exc_value)s, %(exc_tb)s.", {
'queue': self._dcnm_queue_name,
'exc_type': exc_type,
'exc_value': exc_value,
'exc_tb': tb_str}) | [
"def",
"process_amqp_msgs",
"(",
"self",
")",
":",
"LOG",
".",
"info",
"(",
"'Starting process_amqp_msgs...'",
")",
"while",
"True",
":",
"(",
"mtd_fr",
",",
"hdr_fr",
",",
"body",
")",
"=",
"(",
"None",
",",
"None",
",",
"None",
")",
"try",
":",
"if",... | Process AMQP queue messages.
It connects to AMQP server and calls callbacks to process DCNM events,
i.e. routing key containing '.cisco.dcnm.', once they arrive in the
queue. | [
"Process",
"AMQP",
"queue",
"messages",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_listen_dcnm.py#L149-L184 | train | 37,666 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_status.py | _is_pingable | def _is_pingable(ip):
"""Checks whether an IP address is reachable by pinging.
Use linux utils to execute the ping (ICMP ECHO) command.
Sends 5 packets with an interval of 0.2 seconds and timeout of 1
seconds. Runtime error implies unreachability else IP is pingable.
:param ip: IP to check
:return: bool - True or False depending on pingability.
"""
ping_cmd = ['ping',
'-c', '5',
'-W', '1',
'-i', '0.2',
ip]
try:
linux_utils.execute(ping_cmd, check_exit_code=True)
return True
except RuntimeError:
LOG.warning("Cannot ping ip address: %s", ip)
return False | python | def _is_pingable(ip):
"""Checks whether an IP address is reachable by pinging.
Use linux utils to execute the ping (ICMP ECHO) command.
Sends 5 packets with an interval of 0.2 seconds and timeout of 1
seconds. Runtime error implies unreachability else IP is pingable.
:param ip: IP to check
:return: bool - True or False depending on pingability.
"""
ping_cmd = ['ping',
'-c', '5',
'-W', '1',
'-i', '0.2',
ip]
try:
linux_utils.execute(ping_cmd, check_exit_code=True)
return True
except RuntimeError:
LOG.warning("Cannot ping ip address: %s", ip)
return False | [
"def",
"_is_pingable",
"(",
"ip",
")",
":",
"ping_cmd",
"=",
"[",
"'ping'",
",",
"'-c'",
",",
"'5'",
",",
"'-W'",
",",
"'1'",
",",
"'-i'",
",",
"'0.2'",
",",
"ip",
"]",
"try",
":",
"linux_utils",
".",
"execute",
"(",
"ping_cmd",
",",
"check_exit_code... | Checks whether an IP address is reachable by pinging.
Use linux utils to execute the ping (ICMP ECHO) command.
Sends 5 packets with an interval of 0.2 seconds and timeout of 1
seconds. Runtime error implies unreachability else IP is pingable.
:param ip: IP to check
:return: bool - True or False depending on pingability. | [
"Checks",
"whether",
"an",
"IP",
"address",
"is",
"reachable",
"by",
"pinging",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_status.py#L46-L65 | train | 37,667 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_status.py | _can_connect | def _can_connect(ip, port):
"""Checks if a TCP port at IP address is possible to connect to"""
cs = socket.socket()
try:
cs.connect((ip, port))
cs.close()
return True
except socket.error:
return False | python | def _can_connect(ip, port):
"""Checks if a TCP port at IP address is possible to connect to"""
cs = socket.socket()
try:
cs.connect((ip, port))
cs.close()
return True
except socket.error:
return False | [
"def",
"_can_connect",
"(",
"ip",
",",
"port",
")",
":",
"cs",
"=",
"socket",
".",
"socket",
"(",
")",
"try",
":",
"cs",
".",
"connect",
"(",
"(",
"ip",
",",
"port",
")",
")",
"cs",
".",
"close",
"(",
")",
"return",
"True",
"except",
"socket",
... | Checks if a TCP port at IP address is possible to connect to | [
"Checks",
"if",
"a",
"TCP",
"port",
"at",
"IP",
"address",
"is",
"possible",
"to",
"connect",
"to"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_status.py#L68-L76 | train | 37,668 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_status.py | DeviceStatus.get_monitored_hosting_devices_info | def get_monitored_hosting_devices_info(self, hd_state_filter=None):
"""
This function returns a list of all hosting devices monitored
by this agent
"""
wait_time = datetime.timedelta(
seconds=cfg.CONF.cfg_agent.hosting_device_dead_timeout)
resp = []
for hd_id in self.hosting_devices_backlog:
hd = self.hosting_devices_backlog[hd_id]['hd']
display_hd = True
if hd_state_filter is not None:
if hd['hd_state'] == hd_state_filter:
display_hd = True
else:
display_hd = False
if display_hd:
created_time = hd['created_at']
boottime = datetime.timedelta(seconds=hd['booting_time'])
backlogged_at = hd['backlog_insertion_ts']
booted_at = created_time + boottime
dead_at = backlogged_at + wait_time
resp.append({'host id': hd['id'],
'hd_state': hd['hd_state'],
'created at': str(created_time),
'backlogged at': str(backlogged_at),
'estimate booted at': str(booted_at),
'considered dead at': str(dead_at)})
else:
continue
return resp | python | def get_monitored_hosting_devices_info(self, hd_state_filter=None):
"""
This function returns a list of all hosting devices monitored
by this agent
"""
wait_time = datetime.timedelta(
seconds=cfg.CONF.cfg_agent.hosting_device_dead_timeout)
resp = []
for hd_id in self.hosting_devices_backlog:
hd = self.hosting_devices_backlog[hd_id]['hd']
display_hd = True
if hd_state_filter is not None:
if hd['hd_state'] == hd_state_filter:
display_hd = True
else:
display_hd = False
if display_hd:
created_time = hd['created_at']
boottime = datetime.timedelta(seconds=hd['booting_time'])
backlogged_at = hd['backlog_insertion_ts']
booted_at = created_time + boottime
dead_at = backlogged_at + wait_time
resp.append({'host id': hd['id'],
'hd_state': hd['hd_state'],
'created at': str(created_time),
'backlogged at': str(backlogged_at),
'estimate booted at': str(booted_at),
'considered dead at': str(dead_at)})
else:
continue
return resp | [
"def",
"get_monitored_hosting_devices_info",
"(",
"self",
",",
"hd_state_filter",
"=",
"None",
")",
":",
"wait_time",
"=",
"datetime",
".",
"timedelta",
"(",
"seconds",
"=",
"cfg",
".",
"CONF",
".",
"cfg_agent",
".",
"hosting_device_dead_timeout",
")",
"resp",
"... | This function returns a list of all hosting devices monitored
by this agent | [
"This",
"function",
"returns",
"a",
"list",
"of",
"all",
"hosting",
"devices",
"monitored",
"by",
"this",
"agent"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_status.py#L134-L167 | train | 37,669 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_status.py | DeviceStatus.is_hosting_device_reachable | def is_hosting_device_reachable(self, hosting_device):
"""Check the hosting device which hosts this resource is reachable.
If the resource is not reachable, it is added to the backlog.
* heartbeat revision
We want to enqueue all hosting-devices into the backlog for
monitoring purposes
adds key/value pairs to hd (aka hosting_device dictionary)
_is_pingable : if it returns true,
hd['hd_state']='Active'
_is_pingable : if it returns false,
hd['hd_state']='Unknown'
:param hosting_device : dict of the hosting device
:returns: True if device is reachable, else None
"""
ret_val = False
hd = hosting_device
hd_id = hosting_device['id']
hd_mgmt_ip = hosting_device['management_ip_address']
dead_hd_list = self.get_dead_hosting_devices_info()
if hd_id in dead_hd_list:
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is already marked as"
" Dead. It is assigned as non-reachable",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
return False
# Modifying the 'created_at' to a date time object if it is not
if not isinstance(hd['created_at'], datetime.datetime):
hd['created_at'] = datetime.datetime.strptime(hd['created_at'],
'%Y-%m-%d %H:%M:%S')
if _is_pingable(hd_mgmt_ip):
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is reachable.",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
hd['hd_state'] = cc.HD_ACTIVE
ret_val = True
else:
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is NOT reachable.",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
hd['hd_state'] = cc.HD_NOT_RESPONDING
ret_val = False
if self.enable_heartbeat is True or ret_val is False:
self.backlog_hosting_device(hd)
return ret_val | python | def is_hosting_device_reachable(self, hosting_device):
"""Check the hosting device which hosts this resource is reachable.
If the resource is not reachable, it is added to the backlog.
* heartbeat revision
We want to enqueue all hosting-devices into the backlog for
monitoring purposes
adds key/value pairs to hd (aka hosting_device dictionary)
_is_pingable : if it returns true,
hd['hd_state']='Active'
_is_pingable : if it returns false,
hd['hd_state']='Unknown'
:param hosting_device : dict of the hosting device
:returns: True if device is reachable, else None
"""
ret_val = False
hd = hosting_device
hd_id = hosting_device['id']
hd_mgmt_ip = hosting_device['management_ip_address']
dead_hd_list = self.get_dead_hosting_devices_info()
if hd_id in dead_hd_list:
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is already marked as"
" Dead. It is assigned as non-reachable",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
return False
# Modifying the 'created_at' to a date time object if it is not
if not isinstance(hd['created_at'], datetime.datetime):
hd['created_at'] = datetime.datetime.strptime(hd['created_at'],
'%Y-%m-%d %H:%M:%S')
if _is_pingable(hd_mgmt_ip):
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is reachable.",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
hd['hd_state'] = cc.HD_ACTIVE
ret_val = True
else:
LOG.debug("Hosting device: %(hd_id)s@%(ip)s is NOT reachable.",
{'hd_id': hd_id, 'ip': hd_mgmt_ip})
hd['hd_state'] = cc.HD_NOT_RESPONDING
ret_val = False
if self.enable_heartbeat is True or ret_val is False:
self.backlog_hosting_device(hd)
return ret_val | [
"def",
"is_hosting_device_reachable",
"(",
"self",
",",
"hosting_device",
")",
":",
"ret_val",
"=",
"False",
"hd",
"=",
"hosting_device",
"hd_id",
"=",
"hosting_device",
"[",
"'id'",
"]",
"hd_mgmt_ip",
"=",
"hosting_device",
"[",
"'management_ip_address'",
"]",
"d... | Check the hosting device which hosts this resource is reachable.
If the resource is not reachable, it is added to the backlog.
* heartbeat revision
We want to enqueue all hosting-devices into the backlog for
monitoring purposes
adds key/value pairs to hd (aka hosting_device dictionary)
_is_pingable : if it returns true,
hd['hd_state']='Active'
_is_pingable : if it returns false,
hd['hd_state']='Unknown'
:param hosting_device : dict of the hosting device
:returns: True if device is reachable, else None | [
"Check",
"the",
"hosting",
"device",
"which",
"hosts",
"this",
"resource",
"is",
"reachable",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_status.py#L169-L221 | train | 37,670 |
openstack/networking-cisco | networking_cisco/plugins/cisco/service_plugins/cisco_router_plugin.py | CiscoRouterPlugin.create_floatingip | def create_floatingip(self, context, floatingip):
"""Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously creates floating IPs
leveraging the l3 agent and l3 cfg agent, the initial status for the
floating IP object will be DOWN.
"""
return super(CiscoRouterPlugin, self).create_floatingip(
context, floatingip,
initial_status=bc.constants.FLOATINGIP_STATUS_DOWN) | python | def create_floatingip(self, context, floatingip):
"""Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously creates floating IPs
leveraging the l3 agent and l3 cfg agent, the initial status for the
floating IP object will be DOWN.
"""
return super(CiscoRouterPlugin, self).create_floatingip(
context, floatingip,
initial_status=bc.constants.FLOATINGIP_STATUS_DOWN) | [
"def",
"create_floatingip",
"(",
"self",
",",
"context",
",",
"floatingip",
")",
":",
"return",
"super",
"(",
"CiscoRouterPlugin",
",",
"self",
")",
".",
"create_floatingip",
"(",
"context",
",",
"floatingip",
",",
"initial_status",
"=",
"bc",
".",
"constants"... | Create floating IP.
:param context: Neutron request context
:param floatingip: data for the floating IP being created
:returns: A floating IP object on success
As the l3 router plugin asynchronously creates floating IPs
leveraging the l3 agent and l3 cfg agent, the initial status for the
floating IP object will be DOWN. | [
"Create",
"floating",
"IP",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/service_plugins/cisco_router_plugin.py#L109-L122 | train | 37,671 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.attach_intf_router | def attach_intf_router(self, tenant_id, tenant_name, router_id):
"""Routine to attach the interface to the router. """
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
# Modify Hard coded Name fixme
subnet_lst = set()
subnet_lst.add(in_sub)
subnet_lst.add(out_sub)
ret = self.os_helper.add_intf_router(router_id, tenant_id, subnet_lst)
return ret, in_sub, out_sub | python | def attach_intf_router(self, tenant_id, tenant_name, router_id):
"""Routine to attach the interface to the router. """
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
# Modify Hard coded Name fixme
subnet_lst = set()
subnet_lst.add(in_sub)
subnet_lst.add(out_sub)
ret = self.os_helper.add_intf_router(router_id, tenant_id, subnet_lst)
return ret, in_sub, out_sub | [
"def",
"attach_intf_router",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"router_id",
")",
":",
"in_sub",
"=",
"self",
".",
"get_in_subnet_id",
"(",
"tenant_id",
")",
"out_sub",
"=",
"self",
".",
"get_out_subnet_id",
"(",
"tenant_id",
")",
"# Modif... | Routine to attach the interface to the router. | [
"Routine",
"to",
"attach",
"the",
"interface",
"to",
"the",
"router",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L82-L91 | train | 37,672 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.get_router_id | def get_router_id(self, tenant_id, tenant_name):
"""Retrieve the router ID. """
router_id = None
if tenant_id in self.tenant_dict:
router_id = self.tenant_dict.get(tenant_id).get('router_id')
if not router_id:
router_list = self.os_helper.get_rtr_by_name(
'FW_RTR_' + tenant_name)
if len(router_list) > 0:
router_id = router_list[0].get('id')
return router_id | python | def get_router_id(self, tenant_id, tenant_name):
"""Retrieve the router ID. """
router_id = None
if tenant_id in self.tenant_dict:
router_id = self.tenant_dict.get(tenant_id).get('router_id')
if not router_id:
router_list = self.os_helper.get_rtr_by_name(
'FW_RTR_' + tenant_name)
if len(router_list) > 0:
router_id = router_list[0].get('id')
return router_id | [
"def",
"get_router_id",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
")",
":",
"router_id",
"=",
"None",
"if",
"tenant_id",
"in",
"self",
".",
"tenant_dict",
":",
"router_id",
"=",
"self",
".",
"tenant_dict",
".",
"get",
"(",
"tenant_id",
")",
".",
... | Retrieve the router ID. | [
"Retrieve",
"the",
"router",
"ID",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L93-L103 | train | 37,673 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.delete_intf_router | def delete_intf_router(self, tenant_id, tenant_name, router_id):
"""Routine to delete the router. """
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
subnet_lst = set()
subnet_lst.add(in_sub)
subnet_lst.add(out_sub)
router_id = self.get_router_id(tenant_id, tenant_name)
if router_id:
ret = self.os_helper.delete_intf_router(tenant_name, tenant_id,
router_id, subnet_lst)
if not ret:
LOG.error("Failed to delete router intf id %(rtr)s, "
"tenant %(tenant)s",
{'rtr': router_id, 'tenant': tenant_id})
return ret
LOG.error("Invalid router ID, can't delete interface from "
"router") | python | def delete_intf_router(self, tenant_id, tenant_name, router_id):
"""Routine to delete the router. """
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
subnet_lst = set()
subnet_lst.add(in_sub)
subnet_lst.add(out_sub)
router_id = self.get_router_id(tenant_id, tenant_name)
if router_id:
ret = self.os_helper.delete_intf_router(tenant_name, tenant_id,
router_id, subnet_lst)
if not ret:
LOG.error("Failed to delete router intf id %(rtr)s, "
"tenant %(tenant)s",
{'rtr': router_id, 'tenant': tenant_id})
return ret
LOG.error("Invalid router ID, can't delete interface from "
"router") | [
"def",
"delete_intf_router",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"router_id",
")",
":",
"in_sub",
"=",
"self",
".",
"get_in_subnet_id",
"(",
"tenant_id",
")",
"out_sub",
"=",
"self",
".",
"get_out_subnet_id",
"(",
"tenant_id",
")",
"subnet_... | Routine to delete the router. | [
"Routine",
"to",
"delete",
"the",
"router",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L105-L122 | train | 37,674 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.prepare_router_vm_msg | def prepare_router_vm_msg(self, tenant_id, tenant_name, router_id, net_id,
subnet_id, seg, status):
"""Prepare the message to be sent to Event queue for VDP trigger.
This is actually called for a subnet add to a router. This function
prepares a VM's VNIC create/delete message.
"""
max_get_router_info_retry = True
attempt = 0
while max_get_router_info_retry:
port_data = self.os_helper.get_router_port_subnet(subnet_id)
if port_data is None:
LOG.error("Unable to get router port data")
return None
if port_data.get('binding:host_id') == '':
time.sleep(3)
attempt += 1
if attempt > 3:
max_get_router_info_retry = False
LOG.error("Unable to get router binding host data, "
"Max attempts reached")
else:
max_get_router_info_retry = False
if status is 'up':
event_type = 'service.vnic.create'
else:
event_type = 'service.vnic.delete'
vnic_data = {'status': status, 'mac': port_data.get('mac_address'),
'segid': seg, 'host': port_data.get('binding:host_id')}
if vnic_data['host'] == '':
LOG.error("Null host for seg %(seg)s subnet %(subnet)s",
{'seg': seg, 'subnet': subnet_id})
if self.tenant_dict.get(tenant_id).get('host') is None:
LOG.error("Null host for tenant %(tenant)s seg %(seg)s "
"subnet %(subnet)s",
{'tenant': tenant_id, 'seg': seg,
'subnet': subnet_id})
return None
else:
vnic_data['host'] = self.tenant_dict.get(tenant_id).get('host')
else:
self.tenant_dict[tenant_id]['host'] = vnic_data['host']
vm_ip = port_data.get('fixed_ips')[0].get('ip_address')
vnic_data.update({'port_id': port_data.get('id'), 'network_id': net_id,
'vm_name': 'FW_SRVC_RTR_' + tenant_name,
'vm_ip': vm_ip, 'vm_uuid': router_id, 'gw_mac': None,
'fwd_mod': 'anycast_gateway'})
payload = {'service': vnic_data}
data = (event_type, payload)
return data | python | def prepare_router_vm_msg(self, tenant_id, tenant_name, router_id, net_id,
subnet_id, seg, status):
"""Prepare the message to be sent to Event queue for VDP trigger.
This is actually called for a subnet add to a router. This function
prepares a VM's VNIC create/delete message.
"""
max_get_router_info_retry = True
attempt = 0
while max_get_router_info_retry:
port_data = self.os_helper.get_router_port_subnet(subnet_id)
if port_data is None:
LOG.error("Unable to get router port data")
return None
if port_data.get('binding:host_id') == '':
time.sleep(3)
attempt += 1
if attempt > 3:
max_get_router_info_retry = False
LOG.error("Unable to get router binding host data, "
"Max attempts reached")
else:
max_get_router_info_retry = False
if status is 'up':
event_type = 'service.vnic.create'
else:
event_type = 'service.vnic.delete'
vnic_data = {'status': status, 'mac': port_data.get('mac_address'),
'segid': seg, 'host': port_data.get('binding:host_id')}
if vnic_data['host'] == '':
LOG.error("Null host for seg %(seg)s subnet %(subnet)s",
{'seg': seg, 'subnet': subnet_id})
if self.tenant_dict.get(tenant_id).get('host') is None:
LOG.error("Null host for tenant %(tenant)s seg %(seg)s "
"subnet %(subnet)s",
{'tenant': tenant_id, 'seg': seg,
'subnet': subnet_id})
return None
else:
vnic_data['host'] = self.tenant_dict.get(tenant_id).get('host')
else:
self.tenant_dict[tenant_id]['host'] = vnic_data['host']
vm_ip = port_data.get('fixed_ips')[0].get('ip_address')
vnic_data.update({'port_id': port_data.get('id'), 'network_id': net_id,
'vm_name': 'FW_SRVC_RTR_' + tenant_name,
'vm_ip': vm_ip, 'vm_uuid': router_id, 'gw_mac': None,
'fwd_mod': 'anycast_gateway'})
payload = {'service': vnic_data}
data = (event_type, payload)
return data | [
"def",
"prepare_router_vm_msg",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"router_id",
",",
"net_id",
",",
"subnet_id",
",",
"seg",
",",
"status",
")",
":",
"max_get_router_info_retry",
"=",
"True",
"attempt",
"=",
"0",
"while",
"max_get_router_inf... | Prepare the message to be sent to Event queue for VDP trigger.
This is actually called for a subnet add to a router. This function
prepares a VM's VNIC create/delete message. | [
"Prepare",
"the",
"message",
"to",
"be",
"sent",
"to",
"Event",
"queue",
"for",
"VDP",
"trigger",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L124-L173 | train | 37,675 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.send_router_port_msg | def send_router_port_msg(self, tenant_id, tenant_name, router_id, net_id,
subnet_id, seg, status):
"""Sends the router port message to the queue. """
data = self.prepare_router_vm_msg(tenant_id, tenant_name, router_id,
net_id, subnet_id, seg, status)
if data is None:
return False
timestamp = time.ctime()
pri = Q_PRIORITY
LOG.info("Sending native FW data into queue %(data)s",
{'data': data})
self.que_obj.put((pri, timestamp, data))
return True | python | def send_router_port_msg(self, tenant_id, tenant_name, router_id, net_id,
subnet_id, seg, status):
"""Sends the router port message to the queue. """
data = self.prepare_router_vm_msg(tenant_id, tenant_name, router_id,
net_id, subnet_id, seg, status)
if data is None:
return False
timestamp = time.ctime()
pri = Q_PRIORITY
LOG.info("Sending native FW data into queue %(data)s",
{'data': data})
self.que_obj.put((pri, timestamp, data))
return True | [
"def",
"send_router_port_msg",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"router_id",
",",
"net_id",
",",
"subnet_id",
",",
"seg",
",",
"status",
")",
":",
"data",
"=",
"self",
".",
"prepare_router_vm_msg",
"(",
"tenant_id",
",",
"tenant_name",
... | Sends the router port message to the queue. | [
"Sends",
"the",
"router",
"port",
"message",
"to",
"the",
"queue",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L175-L187 | train | 37,676 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.update_dcnm_partition_static_route | def update_dcnm_partition_static_route(self, tenant_id, arg_dict):
"""Add static route in DCNM's partition.
This gets pushed to the relevant leaf switches.
"""
ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,
arg_dict.get('excl_list'))
srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
ret = self.dcnm_obj.update_partition_static_route(
arg_dict.get('tenant_name'), fw_const.SERV_PART_NAME, ip_list,
vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
service_node_ip=srvc_node_ip)
if not ret:
LOG.error("Unable to update DCNM ext profile with static "
"route %s", arg_dict.get('router_id'))
self.delete_intf_router(tenant_id, arg_dict.get('tenant_name'),
arg_dict.get('router_id'))
return False
return True | python | def update_dcnm_partition_static_route(self, tenant_id, arg_dict):
"""Add static route in DCNM's partition.
This gets pushed to the relevant leaf switches.
"""
ip_list = self.os_helper.get_subnet_nwk_excl(tenant_id,
arg_dict.get('excl_list'))
srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
ret = self.dcnm_obj.update_partition_static_route(
arg_dict.get('tenant_name'), fw_const.SERV_PART_NAME, ip_list,
vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
service_node_ip=srvc_node_ip)
if not ret:
LOG.error("Unable to update DCNM ext profile with static "
"route %s", arg_dict.get('router_id'))
self.delete_intf_router(tenant_id, arg_dict.get('tenant_name'),
arg_dict.get('router_id'))
return False
return True | [
"def",
"update_dcnm_partition_static_route",
"(",
"self",
",",
"tenant_id",
",",
"arg_dict",
")",
":",
"ip_list",
"=",
"self",
".",
"os_helper",
".",
"get_subnet_nwk_excl",
"(",
"tenant_id",
",",
"arg_dict",
".",
"get",
"(",
"'excl_list'",
")",
")",
"srvc_node_i... | Add static route in DCNM's partition.
This gets pushed to the relevant leaf switches. | [
"Add",
"static",
"route",
"in",
"DCNM",
"s",
"partition",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L275-L293 | train | 37,677 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall._create_arg_dict | def _create_arg_dict(self, tenant_id, data, in_sub, out_sub):
"""Create the argument dictionary. """
in_seg, in_vlan = self.get_in_seg_vlan(tenant_id)
out_seg, out_vlan = self.get_out_seg_vlan(tenant_id)
in_ip_dict = self.get_in_ip_addr(tenant_id)
out_ip_dict = self.get_out_ip_addr(tenant_id)
excl_list = [in_ip_dict.get('subnet'), out_ip_dict.get('subnet')]
arg_dict = {'tenant_id': tenant_id,
'tenant_name': data.get('tenant_name'),
'in_seg': in_seg, 'in_vlan': in_vlan,
'out_seg': out_seg, 'out_vlan': out_vlan,
'router_id': data.get('router_id'),
'in_sub': in_sub, 'out_sub': out_sub,
'in_gw': in_ip_dict.get('gateway'),
'out_gw': out_ip_dict.get('gateway'),
'excl_list': excl_list}
return arg_dict | python | def _create_arg_dict(self, tenant_id, data, in_sub, out_sub):
"""Create the argument dictionary. """
in_seg, in_vlan = self.get_in_seg_vlan(tenant_id)
out_seg, out_vlan = self.get_out_seg_vlan(tenant_id)
in_ip_dict = self.get_in_ip_addr(tenant_id)
out_ip_dict = self.get_out_ip_addr(tenant_id)
excl_list = [in_ip_dict.get('subnet'), out_ip_dict.get('subnet')]
arg_dict = {'tenant_id': tenant_id,
'tenant_name': data.get('tenant_name'),
'in_seg': in_seg, 'in_vlan': in_vlan,
'out_seg': out_seg, 'out_vlan': out_vlan,
'router_id': data.get('router_id'),
'in_sub': in_sub, 'out_sub': out_sub,
'in_gw': in_ip_dict.get('gateway'),
'out_gw': out_ip_dict.get('gateway'),
'excl_list': excl_list}
return arg_dict | [
"def",
"_create_arg_dict",
"(",
"self",
",",
"tenant_id",
",",
"data",
",",
"in_sub",
",",
"out_sub",
")",
":",
"in_seg",
",",
"in_vlan",
"=",
"self",
".",
"get_in_seg_vlan",
"(",
"tenant_id",
")",
"out_seg",
",",
"out_vlan",
"=",
"self",
".",
"get_out_seg... | Create the argument dictionary. | [
"Create",
"the",
"argument",
"dictionary",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L295-L312 | train | 37,678 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall._create_fw | def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug("In creating Native FW data is %s", data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a special DB
ret, in_sub, out_sub = self.attach_intf_router(tenant_id,
data.get('tenant_name'),
data.get('router_id'))
if not ret:
LOG.error("Native FW: Attach intf router failed for tenant "
"%s", tenant_id)
return False
self.create_tenant_dict(tenant_id, data.get('router_id'))
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
# Program DCNM to update profile's static IP address on OUT part
ret = self.update_dcnm_partition_static_route(tenant_id, arg_dict)
if not ret:
return False
# Program the default GW in router namespace
ret = self.program_default_gw(tenant_id, arg_dict)
if not ret:
return False
# Program router namespace to have all tenant networks to be routed
# to IN service network
ret = self.program_next_hop(tenant_id, arg_dict)
if not ret:
return False
# Send message for router port auto config for in service nwk
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'up')
if not ret:
return False
# Send message for router port auto config for out service nwk
return self.send_out_router_port_msg(tenant_id, arg_dict, 'up') | python | def _create_fw(self, tenant_id, data):
"""Internal routine that gets called when a FW is created. """
LOG.debug("In creating Native FW data is %s", data)
# TODO(padkrish):
# Check if router is already added and only then add, needed for
# restart cases since native doesn't have a special DB
ret, in_sub, out_sub = self.attach_intf_router(tenant_id,
data.get('tenant_name'),
data.get('router_id'))
if not ret:
LOG.error("Native FW: Attach intf router failed for tenant "
"%s", tenant_id)
return False
self.create_tenant_dict(tenant_id, data.get('router_id'))
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
# Program DCNM to update profile's static IP address on OUT part
ret = self.update_dcnm_partition_static_route(tenant_id, arg_dict)
if not ret:
return False
# Program the default GW in router namespace
ret = self.program_default_gw(tenant_id, arg_dict)
if not ret:
return False
# Program router namespace to have all tenant networks to be routed
# to IN service network
ret = self.program_next_hop(tenant_id, arg_dict)
if not ret:
return False
# Send message for router port auto config for in service nwk
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'up')
if not ret:
return False
# Send message for router port auto config for out service nwk
return self.send_out_router_port_msg(tenant_id, arg_dict, 'up') | [
"def",
"_create_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"LOG",
".",
"debug",
"(",
"\"In creating Native FW data is %s\"",
",",
"data",
")",
"# TODO(padkrish):",
"# Check if router is already added and only then add, needed for",
"# restart cases since nativ... | Internal routine that gets called when a FW is created. | [
"Internal",
"routine",
"that",
"gets",
"called",
"when",
"a",
"FW",
"is",
"created",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L314-L352 | train | 37,679 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.create_fw | def create_fw(self, tenant_id, data):
"""Top level routine called when a FW is created. """
try:
return self._create_fw(tenant_id, data)
except Exception as exc:
LOG.error("Failed to create FW for device native, tenant "
"%(tenant)s data %(data)s Exc %(exc)s",
{'tenant': tenant_id, 'data': data, 'exc': exc})
return False | python | def create_fw(self, tenant_id, data):
"""Top level routine called when a FW is created. """
try:
return self._create_fw(tenant_id, data)
except Exception as exc:
LOG.error("Failed to create FW for device native, tenant "
"%(tenant)s data %(data)s Exc %(exc)s",
{'tenant': tenant_id, 'data': data, 'exc': exc})
return False | [
"def",
"create_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"try",
":",
"return",
"self",
".",
"_create_fw",
"(",
"tenant_id",
",",
"data",
")",
"except",
"Exception",
"as",
"exc",
":",
"LOG",
".",
"error",
"(",
"\"Failed to create FW for dev... | Top level routine called when a FW is created. | [
"Top",
"level",
"routine",
"called",
"when",
"a",
"FW",
"is",
"created",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L354-L362 | train | 37,680 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall._delete_fw | def _delete_fw(self, tenant_id, data):
"""Internal routine called when a FW is deleted. """
LOG.debug("In Delete fw data is %s", data)
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
if arg_dict.get('router_id') is None:
LOG.error("Router ID unknown for tenant %s", tenant_id)
return False
if tenant_id not in self.tenant_dict:
self.create_tenant_dict(tenant_id, arg_dict.get('router_id'))
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'down')
if not ret:
return False
ret = self.send_out_router_port_msg(tenant_id, arg_dict, 'down')
if not ret:
return False
# Usually sending message to queue doesn't fail!!!
router_ret = self.delete_intf_router(tenant_id,
arg_dict.get('tenant_name'),
arg_dict.get('router_id'))
if not router_ret:
LOG.error("Unable to delete router for tenant %s, error case",
tenant_id)
return router_ret
del self.tenant_dict[tenant_id]
return router_ret | python | def _delete_fw(self, tenant_id, data):
"""Internal routine called when a FW is deleted. """
LOG.debug("In Delete fw data is %s", data)
in_sub = self.get_in_subnet_id(tenant_id)
out_sub = self.get_out_subnet_id(tenant_id)
arg_dict = self._create_arg_dict(tenant_id, data, in_sub, out_sub)
if arg_dict.get('router_id') is None:
LOG.error("Router ID unknown for tenant %s", tenant_id)
return False
if tenant_id not in self.tenant_dict:
self.create_tenant_dict(tenant_id, arg_dict.get('router_id'))
ret = self.send_in_router_port_msg(tenant_id, arg_dict, 'down')
if not ret:
return False
ret = self.send_out_router_port_msg(tenant_id, arg_dict, 'down')
if not ret:
return False
# Usually sending message to queue doesn't fail!!!
router_ret = self.delete_intf_router(tenant_id,
arg_dict.get('tenant_name'),
arg_dict.get('router_id'))
if not router_ret:
LOG.error("Unable to delete router for tenant %s, error case",
tenant_id)
return router_ret
del self.tenant_dict[tenant_id]
return router_ret | [
"def",
"_delete_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"LOG",
".",
"debug",
"(",
"\"In Delete fw data is %s\"",
",",
"data",
")",
"in_sub",
"=",
"self",
".",
"get_in_subnet_id",
"(",
"tenant_id",
")",
"out_sub",
"=",
"self",
".",
"get_o... | Internal routine called when a FW is deleted. | [
"Internal",
"routine",
"called",
"when",
"a",
"FW",
"is",
"deleted",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L364-L393 | train | 37,681 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.delete_fw | def delete_fw(self, tenant_id, data):
"""Top level routine called when a FW is deleted. """
try:
ret = self._delete_fw(tenant_id, data)
return ret
except Exception as exc:
LOG.error("Failed to delete FW for device native, tenant "
"%(tenant)s data %(data)s Exc %(exc)s",
{'tenant': tenant_id, 'data': data, 'exc': exc})
return False | python | def delete_fw(self, tenant_id, data):
"""Top level routine called when a FW is deleted. """
try:
ret = self._delete_fw(tenant_id, data)
return ret
except Exception as exc:
LOG.error("Failed to delete FW for device native, tenant "
"%(tenant)s data %(data)s Exc %(exc)s",
{'tenant': tenant_id, 'data': data, 'exc': exc})
return False | [
"def",
"delete_fw",
"(",
"self",
",",
"tenant_id",
",",
"data",
")",
":",
"try",
":",
"ret",
"=",
"self",
".",
"_delete_fw",
"(",
"tenant_id",
",",
"data",
")",
"return",
"ret",
"except",
"Exception",
"as",
"exc",
":",
"LOG",
".",
"error",
"(",
"\"Fa... | Top level routine called when a FW is deleted. | [
"Top",
"level",
"routine",
"called",
"when",
"a",
"FW",
"is",
"deleted",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L395-L404 | train | 37,682 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall._program_dcnm_static_route | def _program_dcnm_static_route(self, tenant_id, tenant_name):
"""Program DCNM Static Route. """
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
in_ip = in_ip_dict.get('subnet')
if in_gw is None:
LOG.error("No FW service GW present")
return False
out_ip_dict = self.get_out_ip_addr(tenant_id)
out_ip = out_ip_dict.get('subnet')
# Program DCNM to update profile's static IP address on OUT part
excl_list = []
excl_list.append(in_ip)
excl_list.append(out_ip)
subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
excl_part=True)
# This count is for telling DCNM to insert the static route in a
# particular position. Total networks created - exclusive list as
# above - the network that just got created.
srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
ret = self.dcnm_obj.update_partition_static_route(
tenant_name, fw_const.SERV_PART_NAME, subnet_lst,
vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
service_node_ip=srvc_node_ip)
if not ret:
LOG.error("Unable to update DCNM ext profile with static "
"route")
return False
return True | python | def _program_dcnm_static_route(self, tenant_id, tenant_name):
"""Program DCNM Static Route. """
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
in_ip = in_ip_dict.get('subnet')
if in_gw is None:
LOG.error("No FW service GW present")
return False
out_ip_dict = self.get_out_ip_addr(tenant_id)
out_ip = out_ip_dict.get('subnet')
# Program DCNM to update profile's static IP address on OUT part
excl_list = []
excl_list.append(in_ip)
excl_list.append(out_ip)
subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
excl_part=True)
# This count is for telling DCNM to insert the static route in a
# particular position. Total networks created - exclusive list as
# above - the network that just got created.
srvc_node_ip = self.get_out_srvc_node_ip_addr(tenant_id)
ret = self.dcnm_obj.update_partition_static_route(
tenant_name, fw_const.SERV_PART_NAME, subnet_lst,
vrf_prof=self.cfg.firewall.fw_service_part_vrf_profile,
service_node_ip=srvc_node_ip)
if not ret:
LOG.error("Unable to update DCNM ext profile with static "
"route")
return False
return True | [
"def",
"_program_dcnm_static_route",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
")",
":",
"in_ip_dict",
"=",
"self",
".",
"get_in_ip_addr",
"(",
"tenant_id",
")",
"in_gw",
"=",
"in_ip_dict",
".",
"get",
"(",
"'gateway'",
")",
"in_ip",
"=",
"in_ip_dict"... | Program DCNM Static Route. | [
"Program",
"DCNM",
"Static",
"Route",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L414-L443 | train | 37,683 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.network_create_notif | def network_create_notif(self, tenant_id, tenant_name, cidr):
"""Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if not router_id:
LOG.error("Rout ID not present for tenant")
return False
ret = self._program_dcnm_static_route(tenant_id, tenant_name)
if not ret:
LOG.error("Program DCNM with static routes failed "
"for router %s", router_id)
return False
# Program router namespace to have this network to be routed
# to IN service network
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
if in_gw is None:
LOG.error("No FW service GW present")
return False
ret = self.os_helper.program_rtr_nwk_next_hop(router_id, in_gw, cidr)
if not ret:
LOG.error("Unable to program default router next hop %s",
router_id)
return False
return True | python | def network_create_notif(self, tenant_id, tenant_name, cidr):
"""Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if not router_id:
LOG.error("Rout ID not present for tenant")
return False
ret = self._program_dcnm_static_route(tenant_id, tenant_name)
if not ret:
LOG.error("Program DCNM with static routes failed "
"for router %s", router_id)
return False
# Program router namespace to have this network to be routed
# to IN service network
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
if in_gw is None:
LOG.error("No FW service GW present")
return False
ret = self.os_helper.program_rtr_nwk_next_hop(router_id, in_gw, cidr)
if not ret:
LOG.error("Unable to program default router next hop %s",
router_id)
return False
return True | [
"def",
"network_create_notif",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"cidr",
")",
":",
"router_id",
"=",
"self",
".",
"get_router_id",
"(",
"tenant_id",
",",
"tenant_name",
")",
"if",
"not",
"router_id",
":",
"LOG",
".",
"error",
"(",
"\"... | Tenant Network create Notification.
Restart is not supported currently for this. fixme(padkrish). | [
"Tenant",
"Network",
"create",
"Notification",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L445-L472 | train | 37,684 |
openstack/networking-cisco | networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py | NativeFirewall.network_delete_notif | def network_delete_notif(self, tenant_id, tenant_name, network_id):
"""Tenant Network delete Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if router_id is None:
LOG.error("Rout ID not present for tenant")
return False
ret = self._program_dcnm_static_route(tenant_id, tenant_name)
if not ret:
LOG.error("Program DCNM with static routes failed for "
"router %s", router_id)
return False
# Program router namespace to have this network to be routed
# to IN service network
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
in_ip = in_ip_dict.get('subnet')
if in_gw is None:
LOG.error("No FW service GW present")
return False
out_ip_dict = self.get_out_ip_addr(tenant_id)
out_ip = out_ip_dict.get('subnet')
excl_list = []
excl_list.append(in_ip)
excl_list.append(out_ip)
subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
excl_part=True)
ret = self.os_helper.remove_rtr_nwk_next_hop(router_id, in_gw,
subnet_lst, excl_list)
if not ret:
LOG.error("Unable to program default router next hop %s",
router_id)
return False
return True | python | def network_delete_notif(self, tenant_id, tenant_name, network_id):
"""Tenant Network delete Notification.
Restart is not supported currently for this. fixme(padkrish).
"""
router_id = self.get_router_id(tenant_id, tenant_name)
if router_id is None:
LOG.error("Rout ID not present for tenant")
return False
ret = self._program_dcnm_static_route(tenant_id, tenant_name)
if not ret:
LOG.error("Program DCNM with static routes failed for "
"router %s", router_id)
return False
# Program router namespace to have this network to be routed
# to IN service network
in_ip_dict = self.get_in_ip_addr(tenant_id)
in_gw = in_ip_dict.get('gateway')
in_ip = in_ip_dict.get('subnet')
if in_gw is None:
LOG.error("No FW service GW present")
return False
out_ip_dict = self.get_out_ip_addr(tenant_id)
out_ip = out_ip_dict.get('subnet')
excl_list = []
excl_list.append(in_ip)
excl_list.append(out_ip)
subnet_lst = self.os_helper.get_subnet_nwk_excl(tenant_id, excl_list,
excl_part=True)
ret = self.os_helper.remove_rtr_nwk_next_hop(router_id, in_gw,
subnet_lst, excl_list)
if not ret:
LOG.error("Unable to program default router next hop %s",
router_id)
return False
return True | [
"def",
"network_delete_notif",
"(",
"self",
",",
"tenant_id",
",",
"tenant_name",
",",
"network_id",
")",
":",
"router_id",
"=",
"self",
".",
"get_router_id",
"(",
"tenant_id",
",",
"tenant_name",
")",
"if",
"router_id",
"is",
"None",
":",
"LOG",
".",
"error... | Tenant Network delete Notification.
Restart is not supported currently for this. fixme(padkrish). | [
"Tenant",
"Network",
"delete",
"Notification",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/services/firewall/native/drivers/native.py#L474-L510 | train | 37,685 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.create_hosting_device_resources | def create_hosting_device_resources(self, context, complementary_id,
tenant_id, mgmt_context, max_hosted):
"""Create resources for a hosting device in a plugin specific way."""
mgmt_port = None
if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_id:
# Create port for mgmt interface
p_spec = {'port': {
'tenant_id': tenant_id,
'admin_state_up': True,
'name': 'mgmt',
'network_id': mgmt_context['mgmt_nw_id'],
'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
'fixed_ips': self._mgmt_subnet_spec(context, mgmt_context),
'device_id': "",
# Use device_owner attribute to ensure we can query for these
# ports even before Nova has set device_id attribute.
'device_owner': complementary_id}}
try:
mgmt_port = self._core_plugin.create_port(context, p_spec)
except n_exc.NeutronException as e:
LOG.error('Error %s when creating management port. '
'Cleaning up.', e)
self.delete_hosting_device_resources(
context, tenant_id, mgmt_port)
mgmt_port = None
# We are setting the 'ports' to an empty list as it is expected by
# the callee: device_handling_db._create_svc_vm_hosting_devices()
return {'mgmt_port': mgmt_port, 'ports': []} | python | def create_hosting_device_resources(self, context, complementary_id,
tenant_id, mgmt_context, max_hosted):
"""Create resources for a hosting device in a plugin specific way."""
mgmt_port = None
if mgmt_context and mgmt_context.get('mgmt_nw_id') and tenant_id:
# Create port for mgmt interface
p_spec = {'port': {
'tenant_id': tenant_id,
'admin_state_up': True,
'name': 'mgmt',
'network_id': mgmt_context['mgmt_nw_id'],
'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
'fixed_ips': self._mgmt_subnet_spec(context, mgmt_context),
'device_id': "",
# Use device_owner attribute to ensure we can query for these
# ports even before Nova has set device_id attribute.
'device_owner': complementary_id}}
try:
mgmt_port = self._core_plugin.create_port(context, p_spec)
except n_exc.NeutronException as e:
LOG.error('Error %s when creating management port. '
'Cleaning up.', e)
self.delete_hosting_device_resources(
context, tenant_id, mgmt_port)
mgmt_port = None
# We are setting the 'ports' to an empty list as it is expected by
# the callee: device_handling_db._create_svc_vm_hosting_devices()
return {'mgmt_port': mgmt_port, 'ports': []} | [
"def",
"create_hosting_device_resources",
"(",
"self",
",",
"context",
",",
"complementary_id",
",",
"tenant_id",
",",
"mgmt_context",
",",
"max_hosted",
")",
":",
"mgmt_port",
"=",
"None",
"if",
"mgmt_context",
"and",
"mgmt_context",
".",
"get",
"(",
"'mgmt_nw_id... | Create resources for a hosting device in a plugin specific way. | [
"Create",
"resources",
"for",
"a",
"hosting",
"device",
"in",
"a",
"plugin",
"specific",
"way",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L59-L86 | train | 37,686 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.get_hosting_device_resources | def get_hosting_device_resources(self, context, id, complementary_id,
tenant_id, mgmt_nw_id):
"""Returns information about all resources for a hosting device."""
mgmt_port = None
# Ports for hosting device may not yet have 'device_id' set to
# Nova assigned uuid of VM instance. However, those ports will still
# have 'device_owner' attribute set to complementary_id. Hence, we
# use both attributes in the query to ensure we find all ports.
query = context.session.query(models_v2.Port)
query = query.filter(expr.or_(
models_v2.Port.device_id == id,
models_v2.Port.device_owner == complementary_id))
for port in query:
if port['network_id'] != mgmt_nw_id:
raise Exception
else:
mgmt_port = port
return {'mgmt_port': mgmt_port} | python | def get_hosting_device_resources(self, context, id, complementary_id,
tenant_id, mgmt_nw_id):
"""Returns information about all resources for a hosting device."""
mgmt_port = None
# Ports for hosting device may not yet have 'device_id' set to
# Nova assigned uuid of VM instance. However, those ports will still
# have 'device_owner' attribute set to complementary_id. Hence, we
# use both attributes in the query to ensure we find all ports.
query = context.session.query(models_v2.Port)
query = query.filter(expr.or_(
models_v2.Port.device_id == id,
models_v2.Port.device_owner == complementary_id))
for port in query:
if port['network_id'] != mgmt_nw_id:
raise Exception
else:
mgmt_port = port
return {'mgmt_port': mgmt_port} | [
"def",
"get_hosting_device_resources",
"(",
"self",
",",
"context",
",",
"id",
",",
"complementary_id",
",",
"tenant_id",
",",
"mgmt_nw_id",
")",
":",
"mgmt_port",
"=",
"None",
"# Ports for hosting device may not yet have 'device_id' set to",
"# Nova assigned uuid of VM insta... | Returns information about all resources for a hosting device. | [
"Returns",
"information",
"about",
"all",
"resources",
"for",
"a",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L88-L105 | train | 37,687 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.delete_hosting_device_resources | def delete_hosting_device_resources(self, context, tenant_id, mgmt_port,
**kwargs):
"""Deletes resources for a hosting device in a plugin specific way."""
if mgmt_port is not None:
try:
self._cleanup_hosting_port(context, mgmt_port['id'])
except n_exc.NeutronException as e:
LOG.error("Unable to delete port:%(port)s after %(tries)d"
" attempts due to exception %(exception)s. "
"Skipping it", {'port': mgmt_port['id'],
'tries': DELETION_ATTEMPTS,
'exception': str(e)}) | python | def delete_hosting_device_resources(self, context, tenant_id, mgmt_port,
**kwargs):
"""Deletes resources for a hosting device in a plugin specific way."""
if mgmt_port is not None:
try:
self._cleanup_hosting_port(context, mgmt_port['id'])
except n_exc.NeutronException as e:
LOG.error("Unable to delete port:%(port)s after %(tries)d"
" attempts due to exception %(exception)s. "
"Skipping it", {'port': mgmt_port['id'],
'tries': DELETION_ATTEMPTS,
'exception': str(e)}) | [
"def",
"delete_hosting_device_resources",
"(",
"self",
",",
"context",
",",
"tenant_id",
",",
"mgmt_port",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mgmt_port",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"_cleanup_hosting_port",
"(",
"context",
",",
... | Deletes resources for a hosting device in a plugin specific way. | [
"Deletes",
"resources",
"for",
"a",
"hosting",
"device",
"in",
"a",
"plugin",
"specific",
"way",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L107-L119 | train | 37,688 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.setup_logical_port_connectivity | def setup_logical_port_connectivity(self, context, port_db,
hosting_device_id):
"""Establishes connectivity for a logical port.
This is done by hot plugging the interface(VIF) corresponding to the
port from the VM.
"""
hosting_port = port_db.hosting_info.hosting_port
if hosting_port:
try:
self._dev_mgr.svc_vm_mgr.interface_attach(hosting_device_id,
hosting_port.id)
LOG.debug("Setup logical port completed for port:%s",
port_db.id)
except nova_exc.Conflict as e:
# VM is still in vm_state building
LOG.debug("Failed to attach interface - spawn thread "
"error %(error)s", {'error': str(e)})
self._gt_pool.spawn_n(self._attach_hosting_port,
hosting_device_id, hosting_port.id)
except Exception as e:
LOG.error("Failed to attach interface mapped to port:"
"%(p_id)s on hosting device:%(hd_id)s due to "
"error %(error)s", {'p_id': hosting_port.id,
'hd_id': hosting_device_id,
'error': str(e)}) | python | def setup_logical_port_connectivity(self, context, port_db,
hosting_device_id):
"""Establishes connectivity for a logical port.
This is done by hot plugging the interface(VIF) corresponding to the
port from the VM.
"""
hosting_port = port_db.hosting_info.hosting_port
if hosting_port:
try:
self._dev_mgr.svc_vm_mgr.interface_attach(hosting_device_id,
hosting_port.id)
LOG.debug("Setup logical port completed for port:%s",
port_db.id)
except nova_exc.Conflict as e:
# VM is still in vm_state building
LOG.debug("Failed to attach interface - spawn thread "
"error %(error)s", {'error': str(e)})
self._gt_pool.spawn_n(self._attach_hosting_port,
hosting_device_id, hosting_port.id)
except Exception as e:
LOG.error("Failed to attach interface mapped to port:"
"%(p_id)s on hosting device:%(hd_id)s due to "
"error %(error)s", {'p_id': hosting_port.id,
'hd_id': hosting_device_id,
'error': str(e)}) | [
"def",
"setup_logical_port_connectivity",
"(",
"self",
",",
"context",
",",
"port_db",
",",
"hosting_device_id",
")",
":",
"hosting_port",
"=",
"port_db",
".",
"hosting_info",
".",
"hosting_port",
"if",
"hosting_port",
":",
"try",
":",
"self",
".",
"_dev_mgr",
"... | Establishes connectivity for a logical port.
This is done by hot plugging the interface(VIF) corresponding to the
port from the VM. | [
"Establishes",
"connectivity",
"for",
"a",
"logical",
"port",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L164-L189 | train | 37,689 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.teardown_logical_port_connectivity | def teardown_logical_port_connectivity(self, context, port_db,
hosting_device_id):
"""Removes connectivity for a logical port.
Unplugs the corresponding data interface from the VM.
"""
if port_db is None or port_db.get('id') is None:
LOG.warning("Port id is None! Cannot remove port "
"from hosting_device:%s", hosting_device_id)
return
hosting_port_id = port_db.hosting_info.hosting_port.id
try:
self._dev_mgr.svc_vm_mgr.interface_detach(hosting_device_id,
hosting_port_id)
self._gt_pool.spawn_n(self._cleanup_hosting_port, context,
hosting_port_id)
LOG.debug("Teardown logicalport completed for port:%s", port_db.id)
except Exception as e:
LOG.error("Failed to detach interface corresponding to port:"
"%(p_id)s on hosting device:%(hd_id)s due to "
"error %(error)s", {'p_id': hosting_port_id,
'hd_id': hosting_device_id,
'error': str(e)}) | python | def teardown_logical_port_connectivity(self, context, port_db,
hosting_device_id):
"""Removes connectivity for a logical port.
Unplugs the corresponding data interface from the VM.
"""
if port_db is None or port_db.get('id') is None:
LOG.warning("Port id is None! Cannot remove port "
"from hosting_device:%s", hosting_device_id)
return
hosting_port_id = port_db.hosting_info.hosting_port.id
try:
self._dev_mgr.svc_vm_mgr.interface_detach(hosting_device_id,
hosting_port_id)
self._gt_pool.spawn_n(self._cleanup_hosting_port, context,
hosting_port_id)
LOG.debug("Teardown logicalport completed for port:%s", port_db.id)
except Exception as e:
LOG.error("Failed to detach interface corresponding to port:"
"%(p_id)s on hosting device:%(hd_id)s due to "
"error %(error)s", {'p_id': hosting_port_id,
'hd_id': hosting_device_id,
'error': str(e)}) | [
"def",
"teardown_logical_port_connectivity",
"(",
"self",
",",
"context",
",",
"port_db",
",",
"hosting_device_id",
")",
":",
"if",
"port_db",
"is",
"None",
"or",
"port_db",
".",
"get",
"(",
"'id'",
")",
"is",
"None",
":",
"LOG",
".",
"warning",
"(",
"\"Po... | Removes connectivity for a logical port.
Unplugs the corresponding data interface from the VM. | [
"Removes",
"connectivity",
"for",
"a",
"logical",
"port",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L191-L214 | train | 37,690 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py | VIFHotPlugPluggingDriver.allocate_hosting_port | def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
"""Allocates a hosting port for a logical port.
We create a hosting port for the router port
"""
l3admin_tenant_id = self._dev_mgr.l3_tenant_id()
hostingport_name = 'hostingport_' + port_db['id'][:8]
p_spec = {'port': {
'tenant_id': l3admin_tenant_id,
'admin_state_up': True,
'name': hostingport_name,
'network_id': port_db['network_id'],
'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
'fixed_ips': [],
'device_id': '',
'device_owner': '',
'port_security_enabled': False}}
try:
hosting_port = self._core_plugin.create_port(context, p_spec)
except n_exc.NeutronException as e:
LOG.error('Error %s when creating hosting port'
'Cleaning up.', e)
self.delete_hosting_device_resources(
context, l3admin_tenant_id, hosting_port)
hosting_port = None
finally:
if hosting_port:
return {'allocated_port_id': hosting_port['id'],
'allocated_vlan': None}
else:
return None | python | def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
"""Allocates a hosting port for a logical port.
We create a hosting port for the router port
"""
l3admin_tenant_id = self._dev_mgr.l3_tenant_id()
hostingport_name = 'hostingport_' + port_db['id'][:8]
p_spec = {'port': {
'tenant_id': l3admin_tenant_id,
'admin_state_up': True,
'name': hostingport_name,
'network_id': port_db['network_id'],
'mac_address': bc.constants.ATTR_NOT_SPECIFIED,
'fixed_ips': [],
'device_id': '',
'device_owner': '',
'port_security_enabled': False}}
try:
hosting_port = self._core_plugin.create_port(context, p_spec)
except n_exc.NeutronException as e:
LOG.error('Error %s when creating hosting port'
'Cleaning up.', e)
self.delete_hosting_device_resources(
context, l3admin_tenant_id, hosting_port)
hosting_port = None
finally:
if hosting_port:
return {'allocated_port_id': hosting_port['id'],
'allocated_vlan': None}
else:
return None | [
"def",
"allocate_hosting_port",
"(",
"self",
",",
"context",
",",
"router_id",
",",
"port_db",
",",
"network_type",
",",
"hosting_device_id",
")",
":",
"l3admin_tenant_id",
"=",
"self",
".",
"_dev_mgr",
".",
"l3_tenant_id",
"(",
")",
"hostingport_name",
"=",
"'h... | Allocates a hosting port for a logical port.
We create a hosting port for the router port | [
"Allocates",
"a",
"hosting",
"port",
"for",
"a",
"logical",
"port",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/vif_hotplug_plugging_driver.py#L221-L252 | train | 37,691 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | RemoteServerDriver.disable | def disable(self, retain_port=False):
"""Teardown DHCP.
Disable DHCP for this network by updating the remote server
and then destroying any local device and namespace.
"""
self.update_server(disabled=True)
if retain_port:
return
self.update_device(disabled=True)
if self.conf.dhcp_delete_namespaces and self.network.namespace:
ns_ip = ip_lib.IPWrapper(self.root_helper,
self.network.namespace)
try:
ns_ip.netns.delete(self.network.namespace)
except RuntimeError:
msg = _('Failed trying to delete namespace: %s')
LOG.exception(msg, self.network.namespace) | python | def disable(self, retain_port=False):
"""Teardown DHCP.
Disable DHCP for this network by updating the remote server
and then destroying any local device and namespace.
"""
self.update_server(disabled=True)
if retain_port:
return
self.update_device(disabled=True)
if self.conf.dhcp_delete_namespaces and self.network.namespace:
ns_ip = ip_lib.IPWrapper(self.root_helper,
self.network.namespace)
try:
ns_ip.netns.delete(self.network.namespace)
except RuntimeError:
msg = _('Failed trying to delete namespace: %s')
LOG.exception(msg, self.network.namespace) | [
"def",
"disable",
"(",
"self",
",",
"retain_port",
"=",
"False",
")",
":",
"self",
".",
"update_server",
"(",
"disabled",
"=",
"True",
")",
"if",
"retain_port",
":",
"return",
"self",
".",
"update_device",
"(",
"disabled",
"=",
"True",
")",
"if",
"self",... | Teardown DHCP.
Disable DHCP for this network by updating the remote server
and then destroying any local device and namespace. | [
"Teardown",
"DHCP",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L98-L115 | train | 37,692 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | RemoteServerDriver.recover_devices | def recover_devices(cls):
"""Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system.
"""
if "_devices" in globals():
return
global _devices
confs_dir = os.path.abspath(os.path.normpath(cfg.CONF.dhcp_confs))
for netid in os.listdir(confs_dir):
conf_dir = os.path.join(confs_dir, netid)
intf_filename = os.path.join(conf_dir, 'interface')
try:
with open(intf_filename, 'r') as f:
ifname = f.read()
_devices[netid] = ifname
except IOError:
LOG.error('Unable to read interface file: %s',
intf_filename)
LOG.debug("Recovered device %s for network %s'",
ifname, netid) | python | def recover_devices(cls):
"""Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system.
"""
if "_devices" in globals():
return
global _devices
confs_dir = os.path.abspath(os.path.normpath(cfg.CONF.dhcp_confs))
for netid in os.listdir(confs_dir):
conf_dir = os.path.join(confs_dir, netid)
intf_filename = os.path.join(conf_dir, 'interface')
try:
with open(intf_filename, 'r') as f:
ifname = f.read()
_devices[netid] = ifname
except IOError:
LOG.error('Unable to read interface file: %s',
intf_filename)
LOG.debug("Recovered device %s for network %s'",
ifname, netid) | [
"def",
"recover_devices",
"(",
"cls",
")",
":",
"if",
"\"_devices\"",
"in",
"globals",
"(",
")",
":",
"return",
"global",
"_devices",
"confs_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"cfg",
".",
"CONF",... | Track devices.
Creates global dict to track device names across driver invocations
and populates based on current devices configured on the system. | [
"Track",
"devices",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L160-L183 | train | 37,693 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | SimpleCpnrDriver.check_version | def check_version(cls):
"""Checks server version against minimum required version."""
super(SimpleCpnrDriver, cls).check_version()
model.configure_pnr()
cls.recover_networks()
ver = model.get_version()
if ver < cls.MIN_VERSION:
LOG.warning("CPNR version does not meet minimum requirements, "
"expected: %(ever)f, actual: %(rver)f",
{'ever': cls.MIN_VERSION, 'rver': ver})
return ver | python | def check_version(cls):
"""Checks server version against minimum required version."""
super(SimpleCpnrDriver, cls).check_version()
model.configure_pnr()
cls.recover_networks()
ver = model.get_version()
if ver < cls.MIN_VERSION:
LOG.warning("CPNR version does not meet minimum requirements, "
"expected: %(ever)f, actual: %(rver)f",
{'ever': cls.MIN_VERSION, 'rver': ver})
return ver | [
"def",
"check_version",
"(",
"cls",
")",
":",
"super",
"(",
"SimpleCpnrDriver",
",",
"cls",
")",
".",
"check_version",
"(",
")",
"model",
".",
"configure_pnr",
"(",
")",
"cls",
".",
"recover_networks",
"(",
")",
"ver",
"=",
"model",
".",
"get_version",
"... | Checks server version against minimum required version. | [
"Checks",
"server",
"version",
"against",
"minimum",
"required",
"version",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L263-L273 | train | 37,694 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | SimpleCpnrDriver.existing_dhcp_networks | def existing_dhcp_networks(cls, conf):
"""Return a list of existing networks ids that we have configs for."""
global _networks
sup = super(SimpleCpnrDriver, cls)
superkeys = sup.existing_dhcp_networks(conf)
return set(_networks.keys()) & set(superkeys) | python | def existing_dhcp_networks(cls, conf):
"""Return a list of existing networks ids that we have configs for."""
global _networks
sup = super(SimpleCpnrDriver, cls)
superkeys = sup.existing_dhcp_networks(conf)
return set(_networks.keys()) & set(superkeys) | [
"def",
"existing_dhcp_networks",
"(",
"cls",
",",
"conf",
")",
":",
"global",
"_networks",
"sup",
"=",
"super",
"(",
"SimpleCpnrDriver",
",",
"cls",
")",
"superkeys",
"=",
"sup",
".",
"existing_dhcp_networks",
"(",
"conf",
")",
"return",
"set",
"(",
"_networ... | Return a list of existing networks ids that we have configs for. | [
"Return",
"a",
"list",
"of",
"existing",
"networks",
"ids",
"that",
"we",
"have",
"configs",
"for",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L276-L281 | train | 37,695 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/dhcp_driver.py | SimpleCpnrDriver._unsafe_update_server | def _unsafe_update_server(self, disabled=False):
"""Update server with latest network configuration."""
id = self.network.id
net = model.Network.from_neutron(self.network)
if id not in _networks:
if disabled:
return
_networks[id] = net
_networks[id].create()
elif disabled:
_networks[id].delete()
del _networks[id]
else:
_networks[id].update(net)
_networks[id] = net | python | def _unsafe_update_server(self, disabled=False):
"""Update server with latest network configuration."""
id = self.network.id
net = model.Network.from_neutron(self.network)
if id not in _networks:
if disabled:
return
_networks[id] = net
_networks[id].create()
elif disabled:
_networks[id].delete()
del _networks[id]
else:
_networks[id].update(net)
_networks[id] = net | [
"def",
"_unsafe_update_server",
"(",
"self",
",",
"disabled",
"=",
"False",
")",
":",
"id",
"=",
"self",
".",
"network",
".",
"id",
"net",
"=",
"model",
".",
"Network",
".",
"from_neutron",
"(",
"self",
".",
"network",
")",
"if",
"id",
"not",
"in",
"... | Update server with latest network configuration. | [
"Update",
"server",
"with",
"latest",
"network",
"configuration",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/dhcp_driver.py#L291-L305 | train | 37,696 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_openstack_helper.py | DfaNeutronHelper.create_network | def create_network(self, name, tenant_id, subnet, gw=None):
"""Create the openstack network, including the subnet. """
try:
body = {'network': {'name': name, 'tenant_id': tenant_id,
'admin_state_up': True}}
netw = self.neutronclient.create_network(body=body)
net_dict = netw.get('network')
net_id = net_dict.get('id')
except Exception as exc:
LOG.error("Failed to create network %(name)s, Exc %(exc)s",
{'name': name, 'exc': str(exc)})
return None, None
try:
if gw is None:
body = {'subnet': {'cidr': subnet,
'ip_version': 4,
'network_id': net_id,
'tenant_id': tenant_id,
'enable_dhcp': False}}
else:
body = {'subnet': {'cidr': subnet,
'ip_version': 4,
'network_id': net_id,
'tenant_id': tenant_id,
'enable_dhcp': False,
'gateway_ip': gw}}
subnet_ret = self.neutronclient.create_subnet(body=body)
subnet_dict = subnet_ret.get('subnet')
subnet_id = subnet_dict.get('id')
except Exception as exc:
LOG.error("Failed to create subnet %(sub)s, exc %(exc)s",
{'sub': subnet, 'exc': str(exc)})
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(net)s, exc %(exc)s",
{'net': net_id, 'exc': str(exc)})
return None, None
return net_id, subnet_id | python | def create_network(self, name, tenant_id, subnet, gw=None):
"""Create the openstack network, including the subnet. """
try:
body = {'network': {'name': name, 'tenant_id': tenant_id,
'admin_state_up': True}}
netw = self.neutronclient.create_network(body=body)
net_dict = netw.get('network')
net_id = net_dict.get('id')
except Exception as exc:
LOG.error("Failed to create network %(name)s, Exc %(exc)s",
{'name': name, 'exc': str(exc)})
return None, None
try:
if gw is None:
body = {'subnet': {'cidr': subnet,
'ip_version': 4,
'network_id': net_id,
'tenant_id': tenant_id,
'enable_dhcp': False}}
else:
body = {'subnet': {'cidr': subnet,
'ip_version': 4,
'network_id': net_id,
'tenant_id': tenant_id,
'enable_dhcp': False,
'gateway_ip': gw}}
subnet_ret = self.neutronclient.create_subnet(body=body)
subnet_dict = subnet_ret.get('subnet')
subnet_id = subnet_dict.get('id')
except Exception as exc:
LOG.error("Failed to create subnet %(sub)s, exc %(exc)s",
{'sub': subnet, 'exc': str(exc)})
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(net)s, exc %(exc)s",
{'net': net_id, 'exc': str(exc)})
return None, None
return net_id, subnet_id | [
"def",
"create_network",
"(",
"self",
",",
"name",
",",
"tenant_id",
",",
"subnet",
",",
"gw",
"=",
"None",
")",
":",
"try",
":",
"body",
"=",
"{",
"'network'",
":",
"{",
"'name'",
":",
"name",
",",
"'tenant_id'",
":",
"tenant_id",
",",
"'admin_state_u... | Create the openstack network, including the subnet. | [
"Create",
"the",
"openstack",
"network",
"including",
"the",
"subnet",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_openstack_helper.py#L40-L80 | train | 37,697 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_openstack_helper.py | DfaNeutronHelper.delete_network | def delete_network(self, name, tenant_id, subnet_id, net_id):
"""Delete the openstack subnet and network. """
try:
self.neutronclient.delete_subnet(subnet_id)
except Exception as exc:
LOG.error("Failed to delete subnet %(sub)s exc %(exc)s",
{'sub': subnet_id, 'exc': str(exc)})
return
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(name)s exc %(exc)s",
{'name': name, 'exc': str(exc)}) | python | def delete_network(self, name, tenant_id, subnet_id, net_id):
"""Delete the openstack subnet and network. """
try:
self.neutronclient.delete_subnet(subnet_id)
except Exception as exc:
LOG.error("Failed to delete subnet %(sub)s exc %(exc)s",
{'sub': subnet_id, 'exc': str(exc)})
return
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(name)s exc %(exc)s",
{'name': name, 'exc': str(exc)}) | [
"def",
"delete_network",
"(",
"self",
",",
"name",
",",
"tenant_id",
",",
"subnet_id",
",",
"net_id",
")",
":",
"try",
":",
"self",
".",
"neutronclient",
".",
"delete_subnet",
"(",
"subnet_id",
")",
"except",
"Exception",
"as",
"exc",
":",
"LOG",
".",
"e... | Delete the openstack subnet and network. | [
"Delete",
"the",
"openstack",
"subnet",
"and",
"network",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_openstack_helper.py#L82-L94 | train | 37,698 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_openstack_helper.py | DfaNeutronHelper.delete_network_all_subnets | def delete_network_all_subnets(self, net_id):
"""Delete the openstack network including all its subnets. """
try:
body = {'network_id': net_id}
subnet_list = self.neutronclient.list_subnets(body=body)
subnet_list = subnet_list.get('subnets')
for subnet in subnet_list:
if subnet.get('network_id') == net_id:
subnet_id = subnet.get('id')
self.neutronclient.delete_subnet(subnet_id)
except Exception as exc:
LOG.error("Failed to delete subnet for net %(net)s "
"Exc %(exc)s", {'net': net_id, 'exc': str(exc)})
return False
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(net)s Exc %(exc)s",
{'net': net_id, 'exc': str(exc)})
return False
return True | python | def delete_network_all_subnets(self, net_id):
"""Delete the openstack network including all its subnets. """
try:
body = {'network_id': net_id}
subnet_list = self.neutronclient.list_subnets(body=body)
subnet_list = subnet_list.get('subnets')
for subnet in subnet_list:
if subnet.get('network_id') == net_id:
subnet_id = subnet.get('id')
self.neutronclient.delete_subnet(subnet_id)
except Exception as exc:
LOG.error("Failed to delete subnet for net %(net)s "
"Exc %(exc)s", {'net': net_id, 'exc': str(exc)})
return False
try:
self.neutronclient.delete_network(net_id)
except Exception as exc:
LOG.error("Failed to delete network %(net)s Exc %(exc)s",
{'net': net_id, 'exc': str(exc)})
return False
return True | [
"def",
"delete_network_all_subnets",
"(",
"self",
",",
"net_id",
")",
":",
"try",
":",
"body",
"=",
"{",
"'network_id'",
":",
"net_id",
"}",
"subnet_list",
"=",
"self",
".",
"neutronclient",
".",
"list_subnets",
"(",
"body",
"=",
"body",
")",
"subnet_list",
... | Delete the openstack network including all its subnets. | [
"Delete",
"the",
"openstack",
"network",
"including",
"all",
"its",
"subnets",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_openstack_helper.py#L97-L117 | train | 37,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.