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/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin.l3_tenant_id | def l3_tenant_id(cls):
"""Returns id of tenant owning hosting device resources."""
if cls._l3_tenant_uuid is None:
if hasattr(cfg.CONF.keystone_authtoken, 'project_domain_id'):
# TODO(sridar): hack for now to determing if keystone v3
# API is to be used.
cls._l3_tenant_uuid = cls._get_tenant_id_using_keystone_v3()
else:
cls._l3_tenant_uuid = cls._get_tenant_id_using_keystone_v2()
return cls._l3_tenant_uuid | python | def l3_tenant_id(cls):
"""Returns id of tenant owning hosting device resources."""
if cls._l3_tenant_uuid is None:
if hasattr(cfg.CONF.keystone_authtoken, 'project_domain_id'):
# TODO(sridar): hack for now to determing if keystone v3
# API is to be used.
cls._l3_tenant_uuid = cls._get_tenant_id_using_keystone_v3()
else:
cls._l3_tenant_uuid = cls._get_tenant_id_using_keystone_v2()
return cls._l3_tenant_uuid | [
"def",
"l3_tenant_id",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_l3_tenant_uuid",
"is",
"None",
":",
"if",
"hasattr",
"(",
"cfg",
".",
"CONF",
".",
"keystone_authtoken",
",",
"'project_domain_id'",
")",
":",
"# TODO(sridar): hack for now to determing if keystone v3"... | Returns id of tenant owning hosting device resources. | [
"Returns",
"id",
"of",
"tenant",
"owning",
"hosting",
"device",
"resources",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L192-L201 | train | 37,900 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin.mgmt_nw_id | def mgmt_nw_id(cls):
"""Returns id of the management network."""
if cls._mgmt_nw_uuid is None:
tenant_id = cls.l3_tenant_id()
if not tenant_id:
return
net = bc.get_plugin().get_networks(
bc.context.get_admin_context(),
{'tenant_id': [tenant_id],
'name': [cfg.CONF.general.management_network]},
['id', 'subnets'])
if len(net) == 1:
num_subnets = len(net[0]['subnets'])
if num_subnets == 0:
LOG.error('The management network has no subnet. '
'Please assign one.')
return
elif num_subnets > 1:
LOG.info('The management network has %d subnets. The '
'first one will be used.', num_subnets)
cls._mgmt_nw_uuid = net[0].get('id')
cls._mgmt_subnet_uuid = net[0]['subnets'][0]
elif len(net) > 1:
# Management network must have a unique name.
LOG.error('The management network for does not have '
'unique name. Please ensure that it is.')
else:
# Management network has not been created.
LOG.error('There is no virtual management network. Please '
'create one.')
return cls._mgmt_nw_uuid | python | def mgmt_nw_id(cls):
"""Returns id of the management network."""
if cls._mgmt_nw_uuid is None:
tenant_id = cls.l3_tenant_id()
if not tenant_id:
return
net = bc.get_plugin().get_networks(
bc.context.get_admin_context(),
{'tenant_id': [tenant_id],
'name': [cfg.CONF.general.management_network]},
['id', 'subnets'])
if len(net) == 1:
num_subnets = len(net[0]['subnets'])
if num_subnets == 0:
LOG.error('The management network has no subnet. '
'Please assign one.')
return
elif num_subnets > 1:
LOG.info('The management network has %d subnets. The '
'first one will be used.', num_subnets)
cls._mgmt_nw_uuid = net[0].get('id')
cls._mgmt_subnet_uuid = net[0]['subnets'][0]
elif len(net) > 1:
# Management network must have a unique name.
LOG.error('The management network for does not have '
'unique name. Please ensure that it is.')
else:
# Management network has not been created.
LOG.error('There is no virtual management network. Please '
'create one.')
return cls._mgmt_nw_uuid | [
"def",
"mgmt_nw_id",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_mgmt_nw_uuid",
"is",
"None",
":",
"tenant_id",
"=",
"cls",
".",
"l3_tenant_id",
"(",
")",
"if",
"not",
"tenant_id",
":",
"return",
"net",
"=",
"bc",
".",
"get_plugin",
"(",
")",
".",
"get... | Returns id of the management network. | [
"Returns",
"id",
"of",
"the",
"management",
"network",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L204-L234 | train | 37,901 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin.mgmt_sec_grp_id | def mgmt_sec_grp_id(cls):
"""Returns id of security group used by the management network."""
if not extensions.is_extension_supported(bc.get_plugin(),
"security-group"):
return
if cls._mgmt_sec_grp_id is None:
# Get the id for the _mgmt_security_group_id
tenant_id = cls.l3_tenant_id()
res = bc.get_plugin().get_security_groups(
bc.context.get_admin_context(),
{'tenant_id': [tenant_id],
'name': [cfg.CONF.general.default_security_group]},
['id'])
if len(res) == 1:
sec_grp_id = res[0].get('id', None)
cls._mgmt_sec_grp_id = sec_grp_id
elif len(res) > 1:
# the mgmt sec group must be unique.
LOG.error('The security group for the management network '
'does not have unique name. Please ensure that '
'it is.')
else:
# Service VM Mgmt security group is not present.
LOG.error('There is no security group for the management '
'network. Please create one.')
return cls._mgmt_sec_grp_id | python | def mgmt_sec_grp_id(cls):
"""Returns id of security group used by the management network."""
if not extensions.is_extension_supported(bc.get_plugin(),
"security-group"):
return
if cls._mgmt_sec_grp_id is None:
# Get the id for the _mgmt_security_group_id
tenant_id = cls.l3_tenant_id()
res = bc.get_plugin().get_security_groups(
bc.context.get_admin_context(),
{'tenant_id': [tenant_id],
'name': [cfg.CONF.general.default_security_group]},
['id'])
if len(res) == 1:
sec_grp_id = res[0].get('id', None)
cls._mgmt_sec_grp_id = sec_grp_id
elif len(res) > 1:
# the mgmt sec group must be unique.
LOG.error('The security group for the management network '
'does not have unique name. Please ensure that '
'it is.')
else:
# Service VM Mgmt security group is not present.
LOG.error('There is no security group for the management '
'network. Please create one.')
return cls._mgmt_sec_grp_id | [
"def",
"mgmt_sec_grp_id",
"(",
"cls",
")",
":",
"if",
"not",
"extensions",
".",
"is_extension_supported",
"(",
"bc",
".",
"get_plugin",
"(",
")",
",",
"\"security-group\"",
")",
":",
"return",
"if",
"cls",
".",
"_mgmt_sec_grp_id",
"is",
"None",
":",
"# Get t... | Returns id of security group used by the management network. | [
"Returns",
"id",
"of",
"security",
"group",
"used",
"by",
"the",
"management",
"network",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L243-L268 | train | 37,902 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin.delete_all_hosting_devices | def delete_all_hosting_devices(self, context, force_delete=False):
"""Deletes all hosting devices."""
for item in self._get_collection_query(
context, hd_models.HostingDeviceTemplate):
self.delete_all_hosting_devices_by_template(
context, template=item, force_delete=force_delete) | python | def delete_all_hosting_devices(self, context, force_delete=False):
"""Deletes all hosting devices."""
for item in self._get_collection_query(
context, hd_models.HostingDeviceTemplate):
self.delete_all_hosting_devices_by_template(
context, template=item, force_delete=force_delete) | [
"def",
"delete_all_hosting_devices",
"(",
"self",
",",
"context",
",",
"force_delete",
"=",
"False",
")",
":",
"for",
"item",
"in",
"self",
".",
"_get_collection_query",
"(",
"context",
",",
"hd_models",
".",
"HostingDeviceTemplate",
")",
":",
"self",
".",
"de... | Deletes all hosting devices. | [
"Deletes",
"all",
"hosting",
"devices",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L502-L507 | train | 37,903 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin._process_non_responsive_hosting_device | def _process_non_responsive_hosting_device(self, context, hosting_device):
"""Host type specific processing of non responsive hosting devices.
:param hosting_device: db object for hosting device
:return: True if hosting_device has been deleted, otherwise False
"""
if (hosting_device['template']['host_category'] == VM_CATEGORY and
hosting_device['auto_delete']):
self._delete_dead_service_vm_hosting_device(context,
hosting_device)
return True
return False | python | def _process_non_responsive_hosting_device(self, context, hosting_device):
"""Host type specific processing of non responsive hosting devices.
:param hosting_device: db object for hosting device
:return: True if hosting_device has been deleted, otherwise False
"""
if (hosting_device['template']['host_category'] == VM_CATEGORY and
hosting_device['auto_delete']):
self._delete_dead_service_vm_hosting_device(context,
hosting_device)
return True
return False | [
"def",
"_process_non_responsive_hosting_device",
"(",
"self",
",",
"context",
",",
"hosting_device",
")",
":",
"if",
"(",
"hosting_device",
"[",
"'template'",
"]",
"[",
"'host_category'",
"]",
"==",
"VM_CATEGORY",
"and",
"hosting_device",
"[",
"'auto_delete'",
"]",
... | Host type specific processing of non responsive hosting devices.
:param hosting_device: db object for hosting device
:return: True if hosting_device has been deleted, otherwise False | [
"Host",
"type",
"specific",
"processing",
"of",
"non",
"responsive",
"hosting",
"devices",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L595-L606 | train | 37,904 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin._create_hosting_device_templates_from_config | def _create_hosting_device_templates_from_config(self):
"""To be called late during plugin initialization so that any hosting
device templates defined in the config file is properly inserted in
the DB.
"""
hdt_dict = config.get_specific_config('cisco_hosting_device_template')
attr_info = ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP[
ciscohostingdevicemanager.DEVICE_TEMPLATES]
adm_context = bc.context.get_admin_context()
for hdt_uuid, kv_dict in hdt_dict.items():
# ensure hdt_uuid is properly formatted
hdt_uuid = config.uuidify(hdt_uuid)
try:
self.get_hosting_device_template(adm_context, hdt_uuid)
is_create = False
except ciscohostingdevicemanager.HostingDeviceTemplateNotFound:
is_create = True
kv_dict['id'] = hdt_uuid
kv_dict['tenant_id'] = self.l3_tenant_id()
config.verify_resource_dict(kv_dict, True, attr_info)
hdt = {ciscohostingdevicemanager.DEVICE_TEMPLATE: kv_dict}
try:
if is_create:
self.create_hosting_device_template(adm_context, hdt)
else:
self.update_hosting_device_template(adm_context,
kv_dict['id'], hdt)
except n_exc.NeutronException:
with excutils.save_and_reraise_exception():
LOG.error('Invalid hosting device template definition '
'in configuration file for template = %s',
hdt_uuid) | python | def _create_hosting_device_templates_from_config(self):
"""To be called late during plugin initialization so that any hosting
device templates defined in the config file is properly inserted in
the DB.
"""
hdt_dict = config.get_specific_config('cisco_hosting_device_template')
attr_info = ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP[
ciscohostingdevicemanager.DEVICE_TEMPLATES]
adm_context = bc.context.get_admin_context()
for hdt_uuid, kv_dict in hdt_dict.items():
# ensure hdt_uuid is properly formatted
hdt_uuid = config.uuidify(hdt_uuid)
try:
self.get_hosting_device_template(adm_context, hdt_uuid)
is_create = False
except ciscohostingdevicemanager.HostingDeviceTemplateNotFound:
is_create = True
kv_dict['id'] = hdt_uuid
kv_dict['tenant_id'] = self.l3_tenant_id()
config.verify_resource_dict(kv_dict, True, attr_info)
hdt = {ciscohostingdevicemanager.DEVICE_TEMPLATE: kv_dict}
try:
if is_create:
self.create_hosting_device_template(adm_context, hdt)
else:
self.update_hosting_device_template(adm_context,
kv_dict['id'], hdt)
except n_exc.NeutronException:
with excutils.save_and_reraise_exception():
LOG.error('Invalid hosting device template definition '
'in configuration file for template = %s',
hdt_uuid) | [
"def",
"_create_hosting_device_templates_from_config",
"(",
"self",
")",
":",
"hdt_dict",
"=",
"config",
".",
"get_specific_config",
"(",
"'cisco_hosting_device_template'",
")",
"attr_info",
"=",
"ciscohostingdevicemanager",
".",
"RESOURCE_ATTRIBUTE_MAP",
"[",
"ciscohostingde... | To be called late during plugin initialization so that any hosting
device templates defined in the config file is properly inserted in
the DB. | [
"To",
"be",
"called",
"late",
"during",
"plugin",
"initialization",
"so",
"that",
"any",
"hosting",
"device",
"templates",
"defined",
"in",
"the",
"config",
"file",
"is",
"properly",
"inserted",
"in",
"the",
"DB",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L934-L966 | train | 37,905 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py | HostingDeviceManagerMixin._create_hosting_devices_from_config | def _create_hosting_devices_from_config(self):
"""To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB.
"""
hd_dict = config.get_specific_config('cisco_hosting_device')
attr_info = ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP[
ciscohostingdevicemanager.DEVICES]
adm_context = bc.context.get_admin_context()
for hd_uuid, kv_dict in hd_dict.items():
# ensure hd_uuid is properly formatted
hd_uuid = config.uuidify(hd_uuid)
try:
old_hd = self.get_hosting_device(adm_context, hd_uuid)
is_create = False
except ciscohostingdevicemanager.HostingDeviceNotFound:
old_hd = {}
is_create = True
kv_dict['id'] = hd_uuid
kv_dict['tenant_id'] = self.l3_tenant_id()
# make sure we keep using same config agent if it has been assigned
kv_dict['cfg_agent_id'] = old_hd.get('cfg_agent_id')
# make sure we keep using management port if it exists
kv_dict['management_port_id'] = old_hd.get('management_port_id')
config.verify_resource_dict(kv_dict, True, attr_info)
hd = {ciscohostingdevicemanager.DEVICE: kv_dict}
try:
if is_create:
self.create_hosting_device(adm_context, hd)
else:
self.update_hosting_device(adm_context, kv_dict['id'], hd)
except n_exc.NeutronException:
with excutils.save_and_reraise_exception():
LOG.error('Invalid hosting device specification in '
'configuration file for device = %s',
hd_uuid) | python | def _create_hosting_devices_from_config(self):
"""To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB.
"""
hd_dict = config.get_specific_config('cisco_hosting_device')
attr_info = ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP[
ciscohostingdevicemanager.DEVICES]
adm_context = bc.context.get_admin_context()
for hd_uuid, kv_dict in hd_dict.items():
# ensure hd_uuid is properly formatted
hd_uuid = config.uuidify(hd_uuid)
try:
old_hd = self.get_hosting_device(adm_context, hd_uuid)
is_create = False
except ciscohostingdevicemanager.HostingDeviceNotFound:
old_hd = {}
is_create = True
kv_dict['id'] = hd_uuid
kv_dict['tenant_id'] = self.l3_tenant_id()
# make sure we keep using same config agent if it has been assigned
kv_dict['cfg_agent_id'] = old_hd.get('cfg_agent_id')
# make sure we keep using management port if it exists
kv_dict['management_port_id'] = old_hd.get('management_port_id')
config.verify_resource_dict(kv_dict, True, attr_info)
hd = {ciscohostingdevicemanager.DEVICE: kv_dict}
try:
if is_create:
self.create_hosting_device(adm_context, hd)
else:
self.update_hosting_device(adm_context, kv_dict['id'], hd)
except n_exc.NeutronException:
with excutils.save_and_reraise_exception():
LOG.error('Invalid hosting device specification in '
'configuration file for device = %s',
hd_uuid) | [
"def",
"_create_hosting_devices_from_config",
"(",
"self",
")",
":",
"hd_dict",
"=",
"config",
".",
"get_specific_config",
"(",
"'cisco_hosting_device'",
")",
"attr_info",
"=",
"ciscohostingdevicemanager",
".",
"RESOURCE_ATTRIBUTE_MAP",
"[",
"ciscohostingdevicemanager",
"."... | To be called late during plugin initialization so that any hosting
device specified in the config file is properly inserted in the DB. | [
"To",
"be",
"called",
"late",
"during",
"plugin",
"initialization",
"so",
"that",
"any",
"hosting",
"device",
"specified",
"in",
"the",
"config",
"file",
"is",
"properly",
"inserted",
"in",
"the",
"DB",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/device_manager/hosting_device_manager_db.py#L968-L1003 | train | 37,906 |
openstack/networking-cisco | networking_cisco/neutronclient/routerscheduler.py | AddRouterToHostingDevice.add_router_to_hosting_device | def add_router_to_hosting_device(self, client, hosting_device_id, body):
"""Adds a router to hosting device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.post((res_path + DEVICE_L3_ROUTERS) %
hosting_device_id, body=body) | python | def add_router_to_hosting_device(self, client, hosting_device_id, body):
"""Adds a router to hosting device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.post((res_path + DEVICE_L3_ROUTERS) %
hosting_device_id, body=body) | [
"def",
"add_router_to_hosting_device",
"(",
"self",
",",
"client",
",",
"hosting_device_id",
",",
"body",
")",
":",
"res_path",
"=",
"hostingdevice",
".",
"HostingDevice",
".",
"resource_path",
"return",
"client",
".",
"post",
"(",
"(",
"res_path",
"+",
"DEVICE_... | Adds a router to hosting device. | [
"Adds",
"a",
"router",
"to",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/routerscheduler.py#L72-L76 | train | 37,907 |
openstack/networking-cisco | networking_cisco/neutronclient/routerscheduler.py | RemoveRouterFromHostingDevice.remove_router_from_hosting_device | def remove_router_from_hosting_device(self, client, hosting_device_id,
router_id):
"""Remove a router from hosting_device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + "/%s") % (
hosting_device_id, router_id)) | python | def remove_router_from_hosting_device(self, client, hosting_device_id,
router_id):
"""Remove a router from hosting_device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.delete((res_path + DEVICE_L3_ROUTERS + "/%s") % (
hosting_device_id, router_id)) | [
"def",
"remove_router_from_hosting_device",
"(",
"self",
",",
"client",
",",
"hosting_device_id",
",",
"router_id",
")",
":",
"res_path",
"=",
"hostingdevice",
".",
"HostingDevice",
".",
"resource_path",
"return",
"client",
".",
"delete",
"(",
"(",
"res_path",
"+"... | Remove a router from hosting_device. | [
"Remove",
"a",
"router",
"from",
"hosting_device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/routerscheduler.py#L111-L116 | train | 37,908 |
openstack/networking-cisco | networking_cisco/neutronclient/routerscheduler.py | RoutersOnHostingDeviceList.list_routers_on_hosting_device | def list_routers_on_hosting_device(self, client, hosting_device_id,
**_params):
"""Fetches a list of routers hosted on a hosting device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.get((res_path + DEVICE_L3_ROUTERS) %
hosting_device_id, params=_params) | python | def list_routers_on_hosting_device(self, client, hosting_device_id,
**_params):
"""Fetches a list of routers hosted on a hosting device."""
res_path = hostingdevice.HostingDevice.resource_path
return client.get((res_path + DEVICE_L3_ROUTERS) %
hosting_device_id, params=_params) | [
"def",
"list_routers_on_hosting_device",
"(",
"self",
",",
"client",
",",
"hosting_device_id",
",",
"*",
"*",
"_params",
")",
":",
"res_path",
"=",
"hostingdevice",
".",
"HostingDevice",
".",
"resource_path",
"return",
"client",
".",
"get",
"(",
"(",
"res_path",... | Fetches a list of routers hosted on a hosting device. | [
"Fetches",
"a",
"list",
"of",
"routers",
"hosted",
"on",
"a",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/routerscheduler.py#L141-L146 | train | 37,909 |
openstack/networking-cisco | networking_cisco/neutronclient/routerscheduler.py | HostingDeviceHostingRouterList.list_hosting_devices_hosting_routers | def list_hosting_devices_hosting_routers(self, client, router_id,
**_params):
"""Fetches a list of hosting devices hosting a router."""
return client.get((client.router_path + L3_ROUTER_DEVICES) %
router_id, params=_params) | python | def list_hosting_devices_hosting_routers(self, client, router_id,
**_params):
"""Fetches a list of hosting devices hosting a router."""
return client.get((client.router_path + L3_ROUTER_DEVICES) %
router_id, params=_params) | [
"def",
"list_hosting_devices_hosting_routers",
"(",
"self",
",",
"client",
",",
"router_id",
",",
"*",
"*",
"_params",
")",
":",
"return",
"client",
".",
"get",
"(",
"(",
"client",
".",
"router_path",
"+",
"L3_ROUTER_DEVICES",
")",
"%",
"router_id",
",",
"pa... | Fetches a list of hosting devices hosting a router. | [
"Fetches",
"a",
"list",
"of",
"hosting",
"devices",
"hosting",
"a",
"router",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/routerscheduler.py#L182-L186 | train | 37,910 |
openstack/networking-cisco | networking_cisco/apps/saf/agent/dfa_agent.py | DfaAgent.setup_client_rpc | def setup_client_rpc(self):
"""Setup RPC client for dfa agent."""
# Setup RPC client.
self.clnt = rpc.DfaRpcClient(self._url, constants.DFA_SERVER_QUEUE,
exchange=constants.DFA_EXCHANGE) | python | def setup_client_rpc(self):
"""Setup RPC client for dfa agent."""
# Setup RPC client.
self.clnt = rpc.DfaRpcClient(self._url, constants.DFA_SERVER_QUEUE,
exchange=constants.DFA_EXCHANGE) | [
"def",
"setup_client_rpc",
"(",
"self",
")",
":",
"# Setup RPC client.",
"self",
".",
"clnt",
"=",
"rpc",
".",
"DfaRpcClient",
"(",
"self",
".",
"_url",
",",
"constants",
".",
"DFA_SERVER_QUEUE",
",",
"exchange",
"=",
"constants",
".",
"DFA_EXCHANGE",
")"
] | Setup RPC client for dfa agent. | [
"Setup",
"RPC",
"client",
"for",
"dfa",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/agent/dfa_agent.py#L134-L138 | train | 37,911 |
openstack/networking-cisco | networking_cisco/apps/saf/agent/dfa_agent.py | DfaAgent.setup_rpc | def setup_rpc(self):
"""Setup RPC server for dfa agent."""
endpoints = RpcCallBacks(self._vdpm, self._iptd)
self.server = rpc.DfaRpcServer(self._qn, self._my_host, self._url,
endpoints,
exchange=constants.DFA_EXCHANGE) | python | def setup_rpc(self):
"""Setup RPC server for dfa agent."""
endpoints = RpcCallBacks(self._vdpm, self._iptd)
self.server = rpc.DfaRpcServer(self._qn, self._my_host, self._url,
endpoints,
exchange=constants.DFA_EXCHANGE) | [
"def",
"setup_rpc",
"(",
"self",
")",
":",
"endpoints",
"=",
"RpcCallBacks",
"(",
"self",
".",
"_vdpm",
",",
"self",
".",
"_iptd",
")",
"self",
".",
"server",
"=",
"rpc",
".",
"DfaRpcServer",
"(",
"self",
".",
"_qn",
",",
"self",
".",
"_my_host",
","... | Setup RPC server for dfa agent. | [
"Setup",
"RPC",
"server",
"for",
"dfa",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/agent/dfa_agent.py#L163-L169 | train | 37,912 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py | RoutingServiceHelperAci._add_rid_to_vrf_list | def _add_rid_to_vrf_list(self, ri):
"""Add router ID to a VRF list.
In order to properly manage VRFs in the ASR, their
usage has to be tracked. VRFs are provided with neutron
router objects in their hosting_info fields of the gateway ports.
This means that the VRF is only available when the gateway port
of the router is set. VRFs can span routers, and even OpenStack
tenants, so lists of routers that belong to the same VRF are
kept in a dictionary, with the VRF name as the key.
"""
if ri.ex_gw_port or ri.router.get('gw_port'):
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
if not vrf_name:
return
if not self._router_ids_by_vrf.get(vrf_name):
LOG.debug("++ CREATING VRF %s" % vrf_name)
driver._do_create_vrf(vrf_name)
self._router_ids_by_vrf.setdefault(vrf_name, set()).add(
ri.router['id']) | python | def _add_rid_to_vrf_list(self, ri):
"""Add router ID to a VRF list.
In order to properly manage VRFs in the ASR, their
usage has to be tracked. VRFs are provided with neutron
router objects in their hosting_info fields of the gateway ports.
This means that the VRF is only available when the gateway port
of the router is set. VRFs can span routers, and even OpenStack
tenants, so lists of routers that belong to the same VRF are
kept in a dictionary, with the VRF name as the key.
"""
if ri.ex_gw_port or ri.router.get('gw_port'):
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
if not vrf_name:
return
if not self._router_ids_by_vrf.get(vrf_name):
LOG.debug("++ CREATING VRF %s" % vrf_name)
driver._do_create_vrf(vrf_name)
self._router_ids_by_vrf.setdefault(vrf_name, set()).add(
ri.router['id']) | [
"def",
"_add_rid_to_vrf_list",
"(",
"self",
",",
"ri",
")",
":",
"if",
"ri",
".",
"ex_gw_port",
"or",
"ri",
".",
"router",
".",
"get",
"(",
"'gw_port'",
")",
":",
"driver",
"=",
"self",
".",
"driver_manager",
".",
"get_driver",
"(",
"ri",
".",
"id",
... | Add router ID to a VRF list.
In order to properly manage VRFs in the ASR, their
usage has to be tracked. VRFs are provided with neutron
router objects in their hosting_info fields of the gateway ports.
This means that the VRF is only available when the gateway port
of the router is set. VRFs can span routers, and even OpenStack
tenants, so lists of routers that belong to the same VRF are
kept in a dictionary, with the VRF name as the key. | [
"Add",
"router",
"ID",
"to",
"a",
"VRF",
"list",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py#L127-L147 | train | 37,913 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py | RoutingServiceHelperAci._remove_rid_from_vrf_list | def _remove_rid_from_vrf_list(self, ri):
"""Remove router ID from a VRF list.
This removes a router from the list of routers that's kept
in a map, using a VRF ID as the key. If the VRF exists, the
router is removed from the list if it's present. If the last
router in the list is removed, then the driver's method to
remove the VRF is called and the map entry for that
VRF is deleted.
"""
if ri.ex_gw_port or ri.router.get('gw_port'):
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
if self._router_ids_by_vrf.get(vrf_name) and (
ri.router['id'] in self._router_ids_by_vrf[vrf_name]):
self._router_ids_by_vrf[vrf_name].remove(ri.router['id'])
# If this is the last router in a VRF, then we can safely
# delete the VRF from the router config (handled by the driver)
if not self._router_ids_by_vrf.get(vrf_name):
LOG.debug("++ REMOVING VRF %s" % vrf_name)
driver._remove_vrf(ri)
del self._router_ids_by_vrf[vrf_name] | python | def _remove_rid_from_vrf_list(self, ri):
"""Remove router ID from a VRF list.
This removes a router from the list of routers that's kept
in a map, using a VRF ID as the key. If the VRF exists, the
router is removed from the list if it's present. If the last
router in the list is removed, then the driver's method to
remove the VRF is called and the map entry for that
VRF is deleted.
"""
if ri.ex_gw_port or ri.router.get('gw_port'):
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
if self._router_ids_by_vrf.get(vrf_name) and (
ri.router['id'] in self._router_ids_by_vrf[vrf_name]):
self._router_ids_by_vrf[vrf_name].remove(ri.router['id'])
# If this is the last router in a VRF, then we can safely
# delete the VRF from the router config (handled by the driver)
if not self._router_ids_by_vrf.get(vrf_name):
LOG.debug("++ REMOVING VRF %s" % vrf_name)
driver._remove_vrf(ri)
del self._router_ids_by_vrf[vrf_name] | [
"def",
"_remove_rid_from_vrf_list",
"(",
"self",
",",
"ri",
")",
":",
"if",
"ri",
".",
"ex_gw_port",
"or",
"ri",
".",
"router",
".",
"get",
"(",
"'gw_port'",
")",
":",
"driver",
"=",
"self",
".",
"driver_manager",
".",
"get_driver",
"(",
"ri",
".",
"id... | Remove router ID from a VRF list.
This removes a router from the list of routers that's kept
in a map, using a VRF ID as the key. If the VRF exists, the
router is removed from the list if it's present. If the last
router in the list is removed, then the driver's method to
remove the VRF is called and the map entry for that
VRF is deleted. | [
"Remove",
"router",
"ID",
"from",
"a",
"VRF",
"list",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py#L149-L170 | train | 37,914 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py | RoutingServiceHelperAci._internal_network_removed | def _internal_network_removed(self, ri, port, ex_gw_port):
"""Remove an internal router port
Check to see if this is the last port to be removed for
a given network scoped by a VRF (note: there can be
different mappings between VRFs and networks -- 1-to-1,
1-to-n, n-to-1, n-to-n -- depending on the configuration
and workflow used). If it is the last port, set the flag
indicating that the internal sub-interface for that netowrk
on the ASR should be deleted
"""
itfc_deleted = False
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
network_name = ex_gw_port['hosting_info'].get('network_name')
if self._router_ids_by_vrf_and_ext_net.get(
vrf_name, {}).get(network_name) and (
ri.router['id'] in
self._router_ids_by_vrf_and_ext_net[vrf_name][network_name]):
# If this is the last port for this neutron router,
# then remove this router from the list
if len(ri.internal_ports) == 1 and port in ri.internal_ports:
self._router_ids_by_vrf_and_ext_net[
vrf_name][network_name].remove(ri.router['id'])
# Check if any other routers in this VRF have this network,
# and if not, set the flag to remove the interface
if not self._router_ids_by_vrf_and_ext_net[vrf_name].get(
network_name):
LOG.debug("++ REMOVING NETWORK %s" % network_name)
itfc_deleted = True
del self._router_ids_by_vrf_and_ext_net[
vrf_name][network_name]
if not self._router_ids_by_vrf_and_ext_net.get(vrf_name):
del self._router_ids_by_vrf_and_ext_net[vrf_name]
driver.internal_network_removed(ri, port,
itfc_deleted=itfc_deleted)
if ri.snat_enabled and ex_gw_port:
driver.disable_internal_network_NAT(ri, port, ex_gw_port,
itfc_deleted=itfc_deleted) | python | def _internal_network_removed(self, ri, port, ex_gw_port):
"""Remove an internal router port
Check to see if this is the last port to be removed for
a given network scoped by a VRF (note: there can be
different mappings between VRFs and networks -- 1-to-1,
1-to-n, n-to-1, n-to-n -- depending on the configuration
and workflow used). If it is the last port, set the flag
indicating that the internal sub-interface for that netowrk
on the ASR should be deleted
"""
itfc_deleted = False
driver = self.driver_manager.get_driver(ri.id)
vrf_name = driver._get_vrf_name(ri)
network_name = ex_gw_port['hosting_info'].get('network_name')
if self._router_ids_by_vrf_and_ext_net.get(
vrf_name, {}).get(network_name) and (
ri.router['id'] in
self._router_ids_by_vrf_and_ext_net[vrf_name][network_name]):
# If this is the last port for this neutron router,
# then remove this router from the list
if len(ri.internal_ports) == 1 and port in ri.internal_ports:
self._router_ids_by_vrf_and_ext_net[
vrf_name][network_name].remove(ri.router['id'])
# Check if any other routers in this VRF have this network,
# and if not, set the flag to remove the interface
if not self._router_ids_by_vrf_and_ext_net[vrf_name].get(
network_name):
LOG.debug("++ REMOVING NETWORK %s" % network_name)
itfc_deleted = True
del self._router_ids_by_vrf_and_ext_net[
vrf_name][network_name]
if not self._router_ids_by_vrf_and_ext_net.get(vrf_name):
del self._router_ids_by_vrf_and_ext_net[vrf_name]
driver.internal_network_removed(ri, port,
itfc_deleted=itfc_deleted)
if ri.snat_enabled and ex_gw_port:
driver.disable_internal_network_NAT(ri, port, ex_gw_port,
itfc_deleted=itfc_deleted) | [
"def",
"_internal_network_removed",
"(",
"self",
",",
"ri",
",",
"port",
",",
"ex_gw_port",
")",
":",
"itfc_deleted",
"=",
"False",
"driver",
"=",
"self",
".",
"driver_manager",
".",
"get_driver",
"(",
"ri",
".",
"id",
")",
"vrf_name",
"=",
"driver",
".",
... | Remove an internal router port
Check to see if this is the last port to be removed for
a given network scoped by a VRF (note: there can be
different mappings between VRFs and networks -- 1-to-1,
1-to-n, n-to-1, n-to-n -- depending on the configuration
and workflow used). If it is the last port, set the flag
indicating that the internal sub-interface for that netowrk
on the ASR should be deleted | [
"Remove",
"an",
"internal",
"router",
"port"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/service_helpers/routing_svc_helper_aci.py#L181-L221 | train | 37,915 |
openstack/networking-cisco | networking_cisco/apps/saf/dfa_cli.py | DfaCli.do_list_organizations | def do_list_organizations(self, line):
'''Get list of organization on DCNM.'''
org_list = self.dcnm_client.list_organizations()
if not org_list:
print('No organization found.')
return
org_table = PrettyTable(['Organization Name'])
for org in org_list:
org_table.add_row([org['organizationName']])
print(org_table) | python | def do_list_organizations(self, line):
'''Get list of organization on DCNM.'''
org_list = self.dcnm_client.list_organizations()
if not org_list:
print('No organization found.')
return
org_table = PrettyTable(['Organization Name'])
for org in org_list:
org_table.add_row([org['organizationName']])
print(org_table) | [
"def",
"do_list_organizations",
"(",
"self",
",",
"line",
")",
":",
"org_list",
"=",
"self",
".",
"dcnm_client",
".",
"list_organizations",
"(",
")",
"if",
"not",
"org_list",
":",
"print",
"(",
"'No organization found.'",
")",
"return",
"org_table",
"=",
"Pret... | Get list of organization on DCNM. | [
"Get",
"list",
"of",
"organization",
"on",
"DCNM",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/dfa_cli.py#L161-L173 | train | 37,916 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/l3/routertype_db.py | RoutertypeDbMixin.create_routertype | def create_routertype(self, context, routertype):
"""Creates a router type.
Also binds it to the specified hosting device template.
"""
LOG.debug("create_routertype() called. Contents %s", routertype)
rt = routertype['routertype']
with context.session.begin(subtransactions=True):
routertype_db = l3_models.RouterType(
id=self._get_id(rt),
tenant_id=rt['tenant_id'],
name=rt['name'],
description=rt['description'],
template_id=rt['template_id'],
ha_enabled_by_default=rt['ha_enabled_by_default'],
shared=rt['shared'],
slot_need=rt['slot_need'],
scheduler=rt['scheduler'],
driver=rt['driver'],
cfg_agent_service_helper=rt['cfg_agent_service_helper'],
cfg_agent_driver=rt['cfg_agent_driver'])
context.session.add(routertype_db)
return self._make_routertype_dict(routertype_db) | python | def create_routertype(self, context, routertype):
"""Creates a router type.
Also binds it to the specified hosting device template.
"""
LOG.debug("create_routertype() called. Contents %s", routertype)
rt = routertype['routertype']
with context.session.begin(subtransactions=True):
routertype_db = l3_models.RouterType(
id=self._get_id(rt),
tenant_id=rt['tenant_id'],
name=rt['name'],
description=rt['description'],
template_id=rt['template_id'],
ha_enabled_by_default=rt['ha_enabled_by_default'],
shared=rt['shared'],
slot_need=rt['slot_need'],
scheduler=rt['scheduler'],
driver=rt['driver'],
cfg_agent_service_helper=rt['cfg_agent_service_helper'],
cfg_agent_driver=rt['cfg_agent_driver'])
context.session.add(routertype_db)
return self._make_routertype_dict(routertype_db) | [
"def",
"create_routertype",
"(",
"self",
",",
"context",
",",
"routertype",
")",
":",
"LOG",
".",
"debug",
"(",
"\"create_routertype() called. Contents %s\"",
",",
"routertype",
")",
"rt",
"=",
"routertype",
"[",
"'routertype'",
"]",
"with",
"context",
".",
"ses... | Creates a router type.
Also binds it to the specified hosting device template. | [
"Creates",
"a",
"router",
"type",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/l3/routertype_db.py#L32-L54 | train | 37,917 |
openstack/networking-cisco | networking_cisco/neutronclient/hostingdevicescheduler.py | HostingDeviceAssociateWithConfigAgent.associate_hosting_device_with_config_agent | def associate_hosting_device_with_config_agent(
self, client, config_agent_id, body):
"""Associates a hosting_device with a config agent."""
return client.post((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES) % config_agent_id,
body=body) | python | def associate_hosting_device_with_config_agent(
self, client, config_agent_id, body):
"""Associates a hosting_device with a config agent."""
return client.post((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES) % config_agent_id,
body=body) | [
"def",
"associate_hosting_device_with_config_agent",
"(",
"self",
",",
"client",
",",
"config_agent_id",
",",
"body",
")",
":",
"return",
"client",
".",
"post",
"(",
"(",
"ConfigAgentHandlingHostingDevice",
".",
"resource_path",
"+",
"CFG_AGENT_HOSTING_DEVICES",
")",
... | Associates a hosting_device with a config agent. | [
"Associates",
"a",
"hosting_device",
"with",
"a",
"config",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/hostingdevicescheduler.py#L70-L75 | train | 37,918 |
openstack/networking-cisco | networking_cisco/neutronclient/hostingdevicescheduler.py | HostingDeviceDisassociateFromConfigAgent.disassociate_hosting_device_with_config_agent | def disassociate_hosting_device_with_config_agent(
self, client, config_agent_id, hosting_device_id):
"""Disassociates a hosting_device with a config agent."""
return client.delete((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES + "/%s") % (
config_agent_id, hosting_device_id)) | python | def disassociate_hosting_device_with_config_agent(
self, client, config_agent_id, hosting_device_id):
"""Disassociates a hosting_device with a config agent."""
return client.delete((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES + "/%s") % (
config_agent_id, hosting_device_id)) | [
"def",
"disassociate_hosting_device_with_config_agent",
"(",
"self",
",",
"client",
",",
"config_agent_id",
",",
"hosting_device_id",
")",
":",
"return",
"client",
".",
"delete",
"(",
"(",
"ConfigAgentHandlingHostingDevice",
".",
"resource_path",
"+",
"CFG_AGENT_HOSTING_D... | Disassociates a hosting_device with a config agent. | [
"Disassociates",
"a",
"hosting_device",
"with",
"a",
"config",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/hostingdevicescheduler.py#L109-L114 | train | 37,919 |
openstack/networking-cisco | networking_cisco/neutronclient/hostingdevicescheduler.py | HostingDeviceHandledByConfigAgentList.list_hosting_device_handled_by_config_agent | def list_hosting_device_handled_by_config_agent(
self, client, cfg_agent_id, **_params):
"""Fetches a list of hosting devices handled by a config agent."""
return client.get((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES) % cfg_agent_id,
params=_params) | python | def list_hosting_device_handled_by_config_agent(
self, client, cfg_agent_id, **_params):
"""Fetches a list of hosting devices handled by a config agent."""
return client.get((ConfigAgentHandlingHostingDevice.resource_path +
CFG_AGENT_HOSTING_DEVICES) % cfg_agent_id,
params=_params) | [
"def",
"list_hosting_device_handled_by_config_agent",
"(",
"self",
",",
"client",
",",
"cfg_agent_id",
",",
"*",
"*",
"_params",
")",
":",
"return",
"client",
".",
"get",
"(",
"(",
"ConfigAgentHandlingHostingDevice",
".",
"resource_path",
"+",
"CFG_AGENT_HOSTING_DEVIC... | Fetches a list of hosting devices handled by a config agent. | [
"Fetches",
"a",
"list",
"of",
"hosting",
"devices",
"handled",
"by",
"a",
"config",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/hostingdevicescheduler.py#L135-L140 | train | 37,920 |
openstack/networking-cisco | networking_cisco/neutronclient/hostingdevicescheduler.py | ConfigAgentHandlingHostingDeviceList.list_config_agents_handling_hosting_device | def list_config_agents_handling_hosting_device(
self, client, hosting_device_id, **_params):
"""Fetches a list of config agents handling a hosting device."""
resource_path = '/dev_mgr/hosting_devices/%s'
return client.get((resource_path + HOSTING_DEVICE_CFG_AGENTS) %
hosting_device_id, params=_params) | python | def list_config_agents_handling_hosting_device(
self, client, hosting_device_id, **_params):
"""Fetches a list of config agents handling a hosting device."""
resource_path = '/dev_mgr/hosting_devices/%s'
return client.get((resource_path + HOSTING_DEVICE_CFG_AGENTS) %
hosting_device_id, params=_params) | [
"def",
"list_config_agents_handling_hosting_device",
"(",
"self",
",",
"client",
",",
"hosting_device_id",
",",
"*",
"*",
"_params",
")",
":",
"resource_path",
"=",
"'/dev_mgr/hosting_devices/%s'",
"return",
"client",
".",
"get",
"(",
"(",
"resource_path",
"+",
"HOS... | Fetches a list of config agents handling a hosting device. | [
"Fetches",
"a",
"list",
"of",
"config",
"agents",
"handling",
"a",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/neutronclient/hostingdevicescheduler.py#L180-L185 | train | 37,921 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/type_nexus_vxlan.py | NexusVxlanTypeDriver._parse_nexus_vni_range | def _parse_nexus_vni_range(self, tunnel_range):
"""Raise an exception for invalid tunnel range or malformed range."""
for ident in tunnel_range:
if not self._is_valid_nexus_vni(ident):
raise exc.NetworkTunnelRangeError(
tunnel_range=tunnel_range,
error=_("%(id)s is not a valid Nexus VNI value.") %
{'id': ident})
if tunnel_range[1] < tunnel_range[0]:
raise exc.NetworkTunnelRangeError(
tunnel_range=tunnel_range,
error=_("End of tunnel range is less than start of "
"tunnel range.")) | python | def _parse_nexus_vni_range(self, tunnel_range):
"""Raise an exception for invalid tunnel range or malformed range."""
for ident in tunnel_range:
if not self._is_valid_nexus_vni(ident):
raise exc.NetworkTunnelRangeError(
tunnel_range=tunnel_range,
error=_("%(id)s is not a valid Nexus VNI value.") %
{'id': ident})
if tunnel_range[1] < tunnel_range[0]:
raise exc.NetworkTunnelRangeError(
tunnel_range=tunnel_range,
error=_("End of tunnel range is less than start of "
"tunnel range.")) | [
"def",
"_parse_nexus_vni_range",
"(",
"self",
",",
"tunnel_range",
")",
":",
"for",
"ident",
"in",
"tunnel_range",
":",
"if",
"not",
"self",
".",
"_is_valid_nexus_vni",
"(",
"ident",
")",
":",
"raise",
"exc",
".",
"NetworkTunnelRangeError",
"(",
"tunnel_range",
... | Raise an exception for invalid tunnel range or malformed range. | [
"Raise",
"an",
"exception",
"for",
"invalid",
"tunnel",
"range",
"or",
"malformed",
"range",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/type_nexus_vxlan.py#L113-L126 | train | 37,922 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/type_nexus_vxlan.py | NexusVxlanTypeDriver.sync_allocations | def sync_allocations(self):
"""
Synchronize vxlan_allocations table with configured tunnel ranges.
"""
# determine current configured allocatable vnis
vxlan_vnis = set()
for tun_min, tun_max in self.tunnel_ranges:
vxlan_vnis |= set(six.moves.range(tun_min, tun_max + 1))
session = bc.get_writer_session()
with session.begin(subtransactions=True):
# remove from table unallocated tunnels not currently allocatable
# fetch results as list via all() because we'll be iterating
# through them twice
allocs = (session.query(nexus_models_v2.NexusVxlanAllocation).
with_lockmode("update").all())
# collect all vnis present in db
existing_vnis = set(alloc.vxlan_vni for alloc in allocs)
# collect those vnis that needs to be deleted from db
vnis_to_remove = [alloc.vxlan_vni for alloc in allocs
if (alloc.vxlan_vni not in vxlan_vnis and
not alloc.allocated)]
# Immediately delete vnis in chunks. This leaves no work for
# flush at the end of transaction
bulk_size = 100
chunked_vnis = (vnis_to_remove[i:i + bulk_size] for i in
range(0, len(vnis_to_remove), bulk_size))
for vni_list in chunked_vnis:
session.query(nexus_models_v2.NexusVxlanAllocation).filter(
nexus_models_v2.NexusVxlanAllocation.
vxlan_vni.in_(vni_list)).delete(
synchronize_session=False)
# collect vnis that need to be added
vnis = list(vxlan_vnis - existing_vnis)
chunked_vnis = (vnis[i:i + bulk_size] for i in
range(0, len(vnis), bulk_size))
for vni_list in chunked_vnis:
bulk = [{'vxlan_vni': vni, 'allocated': False}
for vni in vni_list]
session.execute(nexus_models_v2.NexusVxlanAllocation.
__table__.insert(), bulk) | python | def sync_allocations(self):
"""
Synchronize vxlan_allocations table with configured tunnel ranges.
"""
# determine current configured allocatable vnis
vxlan_vnis = set()
for tun_min, tun_max in self.tunnel_ranges:
vxlan_vnis |= set(six.moves.range(tun_min, tun_max + 1))
session = bc.get_writer_session()
with session.begin(subtransactions=True):
# remove from table unallocated tunnels not currently allocatable
# fetch results as list via all() because we'll be iterating
# through them twice
allocs = (session.query(nexus_models_v2.NexusVxlanAllocation).
with_lockmode("update").all())
# collect all vnis present in db
existing_vnis = set(alloc.vxlan_vni for alloc in allocs)
# collect those vnis that needs to be deleted from db
vnis_to_remove = [alloc.vxlan_vni for alloc in allocs
if (alloc.vxlan_vni not in vxlan_vnis and
not alloc.allocated)]
# Immediately delete vnis in chunks. This leaves no work for
# flush at the end of transaction
bulk_size = 100
chunked_vnis = (vnis_to_remove[i:i + bulk_size] for i in
range(0, len(vnis_to_remove), bulk_size))
for vni_list in chunked_vnis:
session.query(nexus_models_v2.NexusVxlanAllocation).filter(
nexus_models_v2.NexusVxlanAllocation.
vxlan_vni.in_(vni_list)).delete(
synchronize_session=False)
# collect vnis that need to be added
vnis = list(vxlan_vnis - existing_vnis)
chunked_vnis = (vnis[i:i + bulk_size] for i in
range(0, len(vnis), bulk_size))
for vni_list in chunked_vnis:
bulk = [{'vxlan_vni': vni, 'allocated': False}
for vni in vni_list]
session.execute(nexus_models_v2.NexusVxlanAllocation.
__table__.insert(), bulk) | [
"def",
"sync_allocations",
"(",
"self",
")",
":",
"# determine current configured allocatable vnis",
"vxlan_vnis",
"=",
"set",
"(",
")",
"for",
"tun_min",
",",
"tun_max",
"in",
"self",
".",
"tunnel_ranges",
":",
"vxlan_vnis",
"|=",
"set",
"(",
"six",
".",
"moves... | Synchronize vxlan_allocations table with configured tunnel ranges. | [
"Synchronize",
"vxlan_allocations",
"table",
"with",
"configured",
"tunnel",
"ranges",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/type_nexus_vxlan.py#L177-L218 | train | 37,923 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_events_handler.py | EventsHandler._setup_notification_listener | def _setup_notification_listener(self, topic_name, url):
"""Setup notification listener for a service."""
self.notify_listener = rpc.DfaNotifcationListener(
topic_name, url, rpc.DfaNotificationEndpoints(self)) | python | def _setup_notification_listener(self, topic_name, url):
"""Setup notification listener for a service."""
self.notify_listener = rpc.DfaNotifcationListener(
topic_name, url, rpc.DfaNotificationEndpoints(self)) | [
"def",
"_setup_notification_listener",
"(",
"self",
",",
"topic_name",
",",
"url",
")",
":",
"self",
".",
"notify_listener",
"=",
"rpc",
".",
"DfaNotifcationListener",
"(",
"topic_name",
",",
"url",
",",
"rpc",
".",
"DfaNotificationEndpoints",
"(",
"self",
")",
... | Setup notification listener for a service. | [
"Setup",
"notification",
"listener",
"for",
"a",
"service",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_events_handler.py#L96-L100 | train | 37,924 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_events_handler.py | EventsHandler.callback | def callback(self, timestamp, event_type, payload):
"""Callback method for processing events in notification queue.
:param timestamp: time the message is received.
:param event_type: event type in the notification queue such as
identity.project.created, identity.project.deleted.
:param payload: Contains information of an event
"""
try:
data = (event_type, payload)
LOG.debug('RX NOTIFICATION ==>\nevent_type: %(event)s, '
'payload: %(payload)s\n', (
{'event': event_type, 'payload': payload}))
if 'create' in event_type:
pri = self._create_pri
elif 'delete' in event_type:
pri = self._delete_pri
elif 'update' in event_type:
pri = self._update_pri
else:
pri = self._delete_pri
self._pq.put((pri, timestamp, data))
except Exception as exc:
LOG.exception('Error: %(err)s for event %(event)s',
{'err': str(exc), 'event': event_type}) | python | def callback(self, timestamp, event_type, payload):
"""Callback method for processing events in notification queue.
:param timestamp: time the message is received.
:param event_type: event type in the notification queue such as
identity.project.created, identity.project.deleted.
:param payload: Contains information of an event
"""
try:
data = (event_type, payload)
LOG.debug('RX NOTIFICATION ==>\nevent_type: %(event)s, '
'payload: %(payload)s\n', (
{'event': event_type, 'payload': payload}))
if 'create' in event_type:
pri = self._create_pri
elif 'delete' in event_type:
pri = self._delete_pri
elif 'update' in event_type:
pri = self._update_pri
else:
pri = self._delete_pri
self._pq.put((pri, timestamp, data))
except Exception as exc:
LOG.exception('Error: %(err)s for event %(event)s',
{'err': str(exc), 'event': event_type}) | [
"def",
"callback",
"(",
"self",
",",
"timestamp",
",",
"event_type",
",",
"payload",
")",
":",
"try",
":",
"data",
"=",
"(",
"event_type",
",",
"payload",
")",
"LOG",
".",
"debug",
"(",
"'RX NOTIFICATION ==>\\nevent_type: %(event)s, '",
"'payload: %(payload)s\\n'"... | Callback method for processing events in notification queue.
:param timestamp: time the message is received.
:param event_type: event type in the notification queue such as
identity.project.created, identity.project.deleted.
:param payload: Contains information of an event | [
"Callback",
"method",
"for",
"processing",
"events",
"in",
"notification",
"queue",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_events_handler.py#L125-L150 | train | 37,925 |
openstack/networking-cisco | networking_cisco/apps/saf/server/dfa_events_handler.py | EventsHandler.event_handler | def event_handler(self):
"""Wait on queue for listening to the events."""
if not self._notify_queue:
LOG.error('event_handler: no notification queue for %s',
self._service_name)
return
LOG.debug('calling event handler for %s', self)
self.start()
self.wait() | python | def event_handler(self):
"""Wait on queue for listening to the events."""
if not self._notify_queue:
LOG.error('event_handler: no notification queue for %s',
self._service_name)
return
LOG.debug('calling event handler for %s', self)
self.start()
self.wait() | [
"def",
"event_handler",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_notify_queue",
":",
"LOG",
".",
"error",
"(",
"'event_handler: no notification queue for %s'",
",",
"self",
".",
"_service_name",
")",
"return",
"LOG",
".",
"debug",
"(",
"'calling event ... | Wait on queue for listening to the events. | [
"Wait",
"on",
"queue",
"for",
"listening",
"to",
"the",
"events",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/server/dfa_events_handler.py#L152-L162 | train | 37,926 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/driver_mgr.py | DeviceDriverManager.set_driver | def set_driver(self, resource):
"""Set the driver for a neutron resource.
:param resource: Neutron resource in dict format.
Expected keys::
{
'id': <value>,
'hosting_device': { 'id': <value>, },
'router_type': {'cfg_agent_driver': <value>, }
}
:returns: driver object
"""
try:
resource_id = resource['id']
hosting_device = resource['hosting_device']
hd_id = hosting_device['id']
if hd_id in self._hosting_device_routing_drivers_binding:
driver = self._hosting_device_routing_drivers_binding[hd_id]
self._drivers[resource_id] = driver
else:
driver_class = resource['router_type']['cfg_agent_driver']
# save a copy of the obfuscated credentials
obfusc_creds = dict(hosting_device.get('credentials'))
if obfusc_creds:
# get un-obfuscated password
real_pw = self._cfg_agent.get_hosting_device_password(
obfusc_creds.get('credentials_id'))
hosting_device['credentials']['password'] = real_pw
driver = importutils.import_object(driver_class,
**hosting_device)
self._hosting_device_routing_drivers_binding[hd_id] = driver
if obfusc_creds:
hosting_device['credentials'] = obfusc_creds
self._drivers[resource_id] = driver
return driver
except ImportError:
with excutils.save_and_reraise_exception(reraise=False):
LOG.exception("Error loading cfg agent driver %(driver)s "
"for hosting device template %(t_name)s"
"(%(t_id)s)",
{'driver': driver_class, 't_id': hd_id,
't_name': resource['name']})
raise cfg_exceptions.DriverNotExist(driver=driver_class)
except KeyError as e:
with excutils.save_and_reraise_exception(reraise=False):
raise cfg_exceptions.DriverNotSetForMissingParameter(e) | python | def set_driver(self, resource):
"""Set the driver for a neutron resource.
:param resource: Neutron resource in dict format.
Expected keys::
{
'id': <value>,
'hosting_device': { 'id': <value>, },
'router_type': {'cfg_agent_driver': <value>, }
}
:returns: driver object
"""
try:
resource_id = resource['id']
hosting_device = resource['hosting_device']
hd_id = hosting_device['id']
if hd_id in self._hosting_device_routing_drivers_binding:
driver = self._hosting_device_routing_drivers_binding[hd_id]
self._drivers[resource_id] = driver
else:
driver_class = resource['router_type']['cfg_agent_driver']
# save a copy of the obfuscated credentials
obfusc_creds = dict(hosting_device.get('credentials'))
if obfusc_creds:
# get un-obfuscated password
real_pw = self._cfg_agent.get_hosting_device_password(
obfusc_creds.get('credentials_id'))
hosting_device['credentials']['password'] = real_pw
driver = importutils.import_object(driver_class,
**hosting_device)
self._hosting_device_routing_drivers_binding[hd_id] = driver
if obfusc_creds:
hosting_device['credentials'] = obfusc_creds
self._drivers[resource_id] = driver
return driver
except ImportError:
with excutils.save_and_reraise_exception(reraise=False):
LOG.exception("Error loading cfg agent driver %(driver)s "
"for hosting device template %(t_name)s"
"(%(t_id)s)",
{'driver': driver_class, 't_id': hd_id,
't_name': resource['name']})
raise cfg_exceptions.DriverNotExist(driver=driver_class)
except KeyError as e:
with excutils.save_and_reraise_exception(reraise=False):
raise cfg_exceptions.DriverNotSetForMissingParameter(e) | [
"def",
"set_driver",
"(",
"self",
",",
"resource",
")",
":",
"try",
":",
"resource_id",
"=",
"resource",
"[",
"'id'",
"]",
"hosting_device",
"=",
"resource",
"[",
"'hosting_device'",
"]",
"hd_id",
"=",
"hosting_device",
"[",
"'id'",
"]",
"if",
"hd_id",
"in... | Set the driver for a neutron resource.
:param resource: Neutron resource in dict format.
Expected keys::
{
'id': <value>,
'hosting_device': { 'id': <value>, },
'router_type': {'cfg_agent_driver': <value>, }
}
:returns: driver object | [
"Set",
"the",
"driver",
"for",
"a",
"neutron",
"resource",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/driver_mgr.py#L64-L111 | train | 37,927 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py | CiscoUcsmDriver._import_ucsmsdk | def _import_ucsmsdk(self):
"""Imports the ucsmsdk module.
This module is not installed as part of the normal Neutron
distributions. It is imported dynamically in this module so that
the import can be mocked, allowing unit testing without requiring
the installation of ucsmsdk.
"""
# Check if SSL certificate checking has been disabled.
# If so, warn the user before proceeding.
if not CONF.ml2_cisco_ucsm.ucsm_https_verify:
LOG.warning(const.SSL_WARNING)
# Monkey patch the ucsmsdk version of ssl to enable https_verify if
# required
from networking_cisco.ml2_drivers.ucsm import ucs_ssl
ucs_driver = importutils.import_module('ucsmsdk.ucsdriver')
ucs_driver.ssl = ucs_ssl
class ucsmsdk(object):
handle = importutils.import_class(
'ucsmsdk.ucshandle.UcsHandle')
fabricVlan = importutils.import_class(
'ucsmsdk.mometa.fabric.FabricVlan.FabricVlan')
vnicProfile = importutils.import_class(
'ucsmsdk.mometa.vnic.VnicProfile.VnicProfile')
vnicEtherIf = importutils.import_class(
'ucsmsdk.mometa.vnic.VnicEtherIf.VnicEtherIf')
vmVnicProfCl = importutils.import_class(
'ucsmsdk.mometa.vm.VmVnicProfCl.VmVnicProfCl')
return ucsmsdk | python | def _import_ucsmsdk(self):
"""Imports the ucsmsdk module.
This module is not installed as part of the normal Neutron
distributions. It is imported dynamically in this module so that
the import can be mocked, allowing unit testing without requiring
the installation of ucsmsdk.
"""
# Check if SSL certificate checking has been disabled.
# If so, warn the user before proceeding.
if not CONF.ml2_cisco_ucsm.ucsm_https_verify:
LOG.warning(const.SSL_WARNING)
# Monkey patch the ucsmsdk version of ssl to enable https_verify if
# required
from networking_cisco.ml2_drivers.ucsm import ucs_ssl
ucs_driver = importutils.import_module('ucsmsdk.ucsdriver')
ucs_driver.ssl = ucs_ssl
class ucsmsdk(object):
handle = importutils.import_class(
'ucsmsdk.ucshandle.UcsHandle')
fabricVlan = importutils.import_class(
'ucsmsdk.mometa.fabric.FabricVlan.FabricVlan')
vnicProfile = importutils.import_class(
'ucsmsdk.mometa.vnic.VnicProfile.VnicProfile')
vnicEtherIf = importutils.import_class(
'ucsmsdk.mometa.vnic.VnicEtherIf.VnicEtherIf')
vmVnicProfCl = importutils.import_class(
'ucsmsdk.mometa.vm.VmVnicProfCl.VmVnicProfCl')
return ucsmsdk | [
"def",
"_import_ucsmsdk",
"(",
"self",
")",
":",
"# Check if SSL certificate checking has been disabled.",
"# If so, warn the user before proceeding.",
"if",
"not",
"CONF",
".",
"ml2_cisco_ucsm",
".",
"ucsm_https_verify",
":",
"LOG",
".",
"warning",
"(",
"const",
".",
"SS... | Imports the ucsmsdk module.
This module is not installed as part of the normal Neutron
distributions. It is imported dynamically in this module so that
the import can be mocked, allowing unit testing without requiring
the installation of ucsmsdk. | [
"Imports",
"the",
"ucsmsdk",
"module",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py#L103-L135 | train | 37,928 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py | CiscoUcsmDriver.ucs_manager_connect | def ucs_manager_connect(self, ucsm_ip):
"""Connects to a UCS Manager."""
if not self.ucsmsdk:
self.ucsmsdk = self._import_ucsmsdk()
ucsm = CONF.ml2_cisco_ucsm.ucsms.get(ucsm_ip)
if not ucsm or not ucsm.ucsm_username or not ucsm.ucsm_password:
LOG.error('UCS Manager network driver failed to get login '
'credentials for UCSM %s', ucsm_ip)
return None
handle = self.ucsmsdk.handle(ucsm_ip, ucsm.ucsm_username,
ucsm.ucsm_password)
try:
handle.login()
except Exception as e:
# Raise a Neutron exception. Include a description of
# the original exception.
raise cexc.UcsmConnectFailed(ucsm_ip=ucsm_ip, exc=e)
return handle | python | def ucs_manager_connect(self, ucsm_ip):
"""Connects to a UCS Manager."""
if not self.ucsmsdk:
self.ucsmsdk = self._import_ucsmsdk()
ucsm = CONF.ml2_cisco_ucsm.ucsms.get(ucsm_ip)
if not ucsm or not ucsm.ucsm_username or not ucsm.ucsm_password:
LOG.error('UCS Manager network driver failed to get login '
'credentials for UCSM %s', ucsm_ip)
return None
handle = self.ucsmsdk.handle(ucsm_ip, ucsm.ucsm_username,
ucsm.ucsm_password)
try:
handle.login()
except Exception as e:
# Raise a Neutron exception. Include a description of
# the original exception.
raise cexc.UcsmConnectFailed(ucsm_ip=ucsm_ip, exc=e)
return handle | [
"def",
"ucs_manager_connect",
"(",
"self",
",",
"ucsm_ip",
")",
":",
"if",
"not",
"self",
".",
"ucsmsdk",
":",
"self",
".",
"ucsmsdk",
"=",
"self",
".",
"_import_ucsmsdk",
"(",
")",
"ucsm",
"=",
"CONF",
".",
"ml2_cisco_ucsm",
".",
"ucsms",
".",
"get",
... | Connects to a UCS Manager. | [
"Connects",
"to",
"a",
"UCS",
"Manager",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py#L165-L186 | train | 37,929 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py | CiscoUcsmDriver._create_vlanprofile | def _create_vlanprofile(self, handle, vlan_id, ucsm_ip):
"""Creates VLAN profile to able associated with the Port Profile."""
vlan_name = self.make_vlan_name(vlan_id)
vlan_profile_dest = (const.VLAN_PATH + const.VLAN_PROFILE_PATH_PREFIX +
vlan_name)
try:
vp1 = handle.query_dn(const.VLAN_PATH)
if not vp1:
LOG.warning('UCS Manager network driver Vlan Profile '
'path at %s missing', const.VLAN_PATH)
return False
# Create a vlan profile with the given vlan_id
vp2 = self.ucsmsdk.fabricVlan(
parent_mo_or_dn=vp1,
name=vlan_name,
compression_type=const.VLAN_COMPRESSION_TYPE,
sharing=const.NONE,
pub_nw_name="",
id=str(vlan_id),
mcast_policy_name="",
default_net="no")
handle.add_mo(vp2)
handle.commit()
if vp2:
LOG.debug('UCS Manager network driver Created Vlan '
'Profile %s at %s', vlan_name, vlan_profile_dest)
return True
except Exception as e:
return self._handle_ucsm_exception(e, 'Vlan Profile',
vlan_name, ucsm_ip) | python | def _create_vlanprofile(self, handle, vlan_id, ucsm_ip):
"""Creates VLAN profile to able associated with the Port Profile."""
vlan_name = self.make_vlan_name(vlan_id)
vlan_profile_dest = (const.VLAN_PATH + const.VLAN_PROFILE_PATH_PREFIX +
vlan_name)
try:
vp1 = handle.query_dn(const.VLAN_PATH)
if not vp1:
LOG.warning('UCS Manager network driver Vlan Profile '
'path at %s missing', const.VLAN_PATH)
return False
# Create a vlan profile with the given vlan_id
vp2 = self.ucsmsdk.fabricVlan(
parent_mo_or_dn=vp1,
name=vlan_name,
compression_type=const.VLAN_COMPRESSION_TYPE,
sharing=const.NONE,
pub_nw_name="",
id=str(vlan_id),
mcast_policy_name="",
default_net="no")
handle.add_mo(vp2)
handle.commit()
if vp2:
LOG.debug('UCS Manager network driver Created Vlan '
'Profile %s at %s', vlan_name, vlan_profile_dest)
return True
except Exception as e:
return self._handle_ucsm_exception(e, 'Vlan Profile',
vlan_name, ucsm_ip) | [
"def",
"_create_vlanprofile",
"(",
"self",
",",
"handle",
",",
"vlan_id",
",",
"ucsm_ip",
")",
":",
"vlan_name",
"=",
"self",
".",
"make_vlan_name",
"(",
"vlan_id",
")",
"vlan_profile_dest",
"=",
"(",
"const",
".",
"VLAN_PATH",
"+",
"const",
".",
"VLAN_PROFI... | Creates VLAN profile to able associated with the Port Profile. | [
"Creates",
"VLAN",
"profile",
"to",
"able",
"associated",
"with",
"the",
"Port",
"Profile",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_network_driver.py#L255-L289 | train | 37,930 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/service_vm_lib.py | ServiceVMManager.nova_services_up | def nova_services_up(self):
"""Checks if required Nova services are up and running.
returns: True if all needed Nova services are up, False otherwise
"""
required = set(['nova-conductor', 'nova-cert', 'nova-scheduler',
'nova-compute'])
try:
services = self._nclient.services.list()
# There are several individual Nova client exceptions but they have
# no other common base than Exception, hence the long list.
except Exception as e:
LOG.error('Failure determining running Nova services: %s', e)
return False
return not bool(required.difference(
[service.binary for service in services
if service.status == 'enabled' and service.state == 'up'])) | python | def nova_services_up(self):
"""Checks if required Nova services are up and running.
returns: True if all needed Nova services are up, False otherwise
"""
required = set(['nova-conductor', 'nova-cert', 'nova-scheduler',
'nova-compute'])
try:
services = self._nclient.services.list()
# There are several individual Nova client exceptions but they have
# no other common base than Exception, hence the long list.
except Exception as e:
LOG.error('Failure determining running Nova services: %s', e)
return False
return not bool(required.difference(
[service.binary for service in services
if service.status == 'enabled' and service.state == 'up'])) | [
"def",
"nova_services_up",
"(",
"self",
")",
":",
"required",
"=",
"set",
"(",
"[",
"'nova-conductor'",
",",
"'nova-cert'",
",",
"'nova-scheduler'",
",",
"'nova-compute'",
"]",
")",
"try",
":",
"services",
"=",
"self",
".",
"_nclient",
".",
"services",
".",
... | Checks if required Nova services are up and running.
returns: True if all needed Nova services are up, False otherwise | [
"Checks",
"if",
"required",
"Nova",
"services",
"are",
"up",
"and",
"running",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/service_vm_lib.py#L62-L78 | train | 37,931 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py | L3RouterTypeAwareScheduler._get_unscheduled_routers | def _get_unscheduled_routers(self, plugin, context):
"""Get routers with no agent binding."""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
# TODO(gongysh) consider the disabled agent's router
no_agent_binding = ~sql.exists().where(
bc.Router.id == bc.rb_model.RouterL3AgentBinding.router_id)
# Modified to only include routers of network namespace type
ns_routertype_id = plugin.get_namespace_router_type_id(context)
query = context.session.query(bc.Router.id)
query = query.join(l3_models.RouterHostingDeviceBinding)
query = query.filter(
l3_models.RouterHostingDeviceBinding.router_type_id ==
ns_routertype_id, no_agent_binding)
unscheduled_router_ids = [router_id_[0] for router_id_ in query]
if unscheduled_router_ids:
return plugin.get_routers(
context, filters={'id': unscheduled_router_ids})
return [] | python | def _get_unscheduled_routers(self, plugin, context):
"""Get routers with no agent binding."""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
# TODO(gongysh) consider the disabled agent's router
no_agent_binding = ~sql.exists().where(
bc.Router.id == bc.rb_model.RouterL3AgentBinding.router_id)
# Modified to only include routers of network namespace type
ns_routertype_id = plugin.get_namespace_router_type_id(context)
query = context.session.query(bc.Router.id)
query = query.join(l3_models.RouterHostingDeviceBinding)
query = query.filter(
l3_models.RouterHostingDeviceBinding.router_type_id ==
ns_routertype_id, no_agent_binding)
unscheduled_router_ids = [router_id_[0] for router_id_ in query]
if unscheduled_router_ids:
return plugin.get_routers(
context, filters={'id': unscheduled_router_ids})
return [] | [
"def",
"_get_unscheduled_routers",
"(",
"self",
",",
"plugin",
",",
"context",
")",
":",
"if",
"NEUTRON_VERSION",
".",
"version",
"[",
"0",
"]",
"<=",
"NEUTRON_NEWTON_VERSION",
".",
"version",
"[",
"0",
"]",
":",
"context",
",",
"plugin",
"=",
"plugin",
",... | Get routers with no agent binding. | [
"Get",
"routers",
"with",
"no",
"agent",
"binding",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py#L38-L56 | train | 37,932 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py | L3RouterTypeAwareScheduler._filter_unscheduled_routers | def _filter_unscheduled_routers(self, plugin, context, routers):
"""Filter from list of routers the ones that are not scheduled.
Only for release < pike.
"""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
unscheduled_routers = []
for router in routers:
if (router[routertype.TYPE_ATTR] !=
plugin.get_namespace_router_type_id(context)):
# ignore non-namespace routers
continue
l3_agents = plugin.get_l3_agents_hosting_routers(
context, [router['id']])
if l3_agents:
LOG.debug('Router %(router_id)s has already been '
'hosted by L3 agent %(agent_id)s',
{'router_id': router['id'],
'agent_id': l3_agents[0]['id']})
else:
unscheduled_routers.append(router)
return unscheduled_routers | python | def _filter_unscheduled_routers(self, plugin, context, routers):
"""Filter from list of routers the ones that are not scheduled.
Only for release < pike.
"""
if NEUTRON_VERSION.version[0] <= NEUTRON_NEWTON_VERSION.version[0]:
context, plugin = plugin, context
unscheduled_routers = []
for router in routers:
if (router[routertype.TYPE_ATTR] !=
plugin.get_namespace_router_type_id(context)):
# ignore non-namespace routers
continue
l3_agents = plugin.get_l3_agents_hosting_routers(
context, [router['id']])
if l3_agents:
LOG.debug('Router %(router_id)s has already been '
'hosted by L3 agent %(agent_id)s',
{'router_id': router['id'],
'agent_id': l3_agents[0]['id']})
else:
unscheduled_routers.append(router)
return unscheduled_routers | [
"def",
"_filter_unscheduled_routers",
"(",
"self",
",",
"plugin",
",",
"context",
",",
"routers",
")",
":",
"if",
"NEUTRON_VERSION",
".",
"version",
"[",
"0",
"]",
"<=",
"NEUTRON_NEWTON_VERSION",
".",
"version",
"[",
"0",
"]",
":",
"context",
",",
"plugin",
... | Filter from list of routers the ones that are not scheduled.
Only for release < pike. | [
"Filter",
"from",
"list",
"of",
"routers",
"the",
"ones",
"that",
"are",
"not",
"scheduled",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py#L58-L80 | train | 37,933 |
openstack/networking-cisco | networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py | L3RouterTypeAwareScheduler._get_underscheduled_routers | def _get_underscheduled_routers(self, plugin, context):
"""For release >= pike."""
underscheduled_routers = []
max_agents_for_ha = plugin.get_number_of_agents_for_scheduling(context)
for router, count in plugin.get_routers_l3_agents_count(context):
if (router[routertype.TYPE_ATTR] !=
plugin.get_namespace_router_type_id(context)):
# ignore non-namespace routers
continue
if (count < 1 or
router.get('ha', False) and count < max_agents_for_ha):
# Either the router was un-scheduled (scheduled to 0 agents),
# or it's an HA router and it was under-scheduled (scheduled to
# less than max_agents_for_ha). Either way, it should be added
# to the list of routers we want to handle.
underscheduled_routers.append(router)
return underscheduled_routers | python | def _get_underscheduled_routers(self, plugin, context):
"""For release >= pike."""
underscheduled_routers = []
max_agents_for_ha = plugin.get_number_of_agents_for_scheduling(context)
for router, count in plugin.get_routers_l3_agents_count(context):
if (router[routertype.TYPE_ATTR] !=
plugin.get_namespace_router_type_id(context)):
# ignore non-namespace routers
continue
if (count < 1 or
router.get('ha', False) and count < max_agents_for_ha):
# Either the router was un-scheduled (scheduled to 0 agents),
# or it's an HA router and it was under-scheduled (scheduled to
# less than max_agents_for_ha). Either way, it should be added
# to the list of routers we want to handle.
underscheduled_routers.append(router)
return underscheduled_routers | [
"def",
"_get_underscheduled_routers",
"(",
"self",
",",
"plugin",
",",
"context",
")",
":",
"underscheduled_routers",
"=",
"[",
"]",
"max_agents_for_ha",
"=",
"plugin",
".",
"get_number_of_agents_for_scheduling",
"(",
"context",
")",
"for",
"router",
",",
"count",
... | For release >= pike. | [
"For",
"release",
">",
"=",
"pike",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/l3/schedulers/l3_routertype_aware_agent_scheduler.py#L82-L99 | train | 37,934 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/scheduler/hosting_device_cfg_agent_scheduler.py | HostingDeviceCfgAgentScheduler.auto_schedule_hosting_devices | def auto_schedule_hosting_devices(self, plugin, context, agent_host):
"""Schedules unassociated hosting devices to Cisco cfg agent.
Schedules hosting devices to agent running on <agent_host>.
"""
query = context.session.query(bc.Agent)
query = query.filter_by(agent_type=c_constants.AGENT_TYPE_CFG,
host=agent_host, admin_state_up=True)
try:
cfg_agent_db = query.one()
except (exc.MultipleResultsFound, exc.NoResultFound):
LOG.debug('No enabled Cisco cfg agent on host %s', agent_host)
return
if cfg_agentschedulers_db.CfgAgentSchedulerDbMixin.is_agent_down(
cfg_agent_db.heartbeat_timestamp):
LOG.warning('Cisco cfg agent %s is not alive',
cfg_agent_db.id)
return cfg_agent_db | python | def auto_schedule_hosting_devices(self, plugin, context, agent_host):
"""Schedules unassociated hosting devices to Cisco cfg agent.
Schedules hosting devices to agent running on <agent_host>.
"""
query = context.session.query(bc.Agent)
query = query.filter_by(agent_type=c_constants.AGENT_TYPE_CFG,
host=agent_host, admin_state_up=True)
try:
cfg_agent_db = query.one()
except (exc.MultipleResultsFound, exc.NoResultFound):
LOG.debug('No enabled Cisco cfg agent on host %s', agent_host)
return
if cfg_agentschedulers_db.CfgAgentSchedulerDbMixin.is_agent_down(
cfg_agent_db.heartbeat_timestamp):
LOG.warning('Cisco cfg agent %s is not alive',
cfg_agent_db.id)
return cfg_agent_db | [
"def",
"auto_schedule_hosting_devices",
"(",
"self",
",",
"plugin",
",",
"context",
",",
"agent_host",
")",
":",
"query",
"=",
"context",
".",
"session",
".",
"query",
"(",
"bc",
".",
"Agent",
")",
"query",
"=",
"query",
".",
"filter_by",
"(",
"agent_type"... | Schedules unassociated hosting devices to Cisco cfg agent.
Schedules hosting devices to agent running on <agent_host>. | [
"Schedules",
"unassociated",
"hosting",
"devices",
"to",
"Cisco",
"cfg",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/scheduler/hosting_device_cfg_agent_scheduler.py#L37-L54 | train | 37,935 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver._get_external_network_dict | def _get_external_network_dict(self, context, port_db):
"""Get external network information
Get the information about the external network,
so that it can be used to create the hidden port,
subnet, and network.
"""
if port_db.device_owner == DEVICE_OWNER_ROUTER_GW:
network = self._core_plugin.get_network(context,
port_db.network_id)
else:
router = self.l3_plugin.get_router(context,
port_db.device_id)
ext_gw_info = router.get(EXTERNAL_GW_INFO)
if not ext_gw_info:
return {}, None
network = self._core_plugin.get_network(context,
ext_gw_info['network_id'])
# network names in GBP workflow need to be reduced, since
# the network may contain UUIDs
external_network = self.get_ext_net_name(network['name'])
# TODO(tbachman): see if we can get rid of the default
transit_net = self.transit_nets_cfg.get(
external_network) or self._default_ext_dict
transit_net['network_name'] = external_network
return transit_net, network | python | def _get_external_network_dict(self, context, port_db):
"""Get external network information
Get the information about the external network,
so that it can be used to create the hidden port,
subnet, and network.
"""
if port_db.device_owner == DEVICE_OWNER_ROUTER_GW:
network = self._core_plugin.get_network(context,
port_db.network_id)
else:
router = self.l3_plugin.get_router(context,
port_db.device_id)
ext_gw_info = router.get(EXTERNAL_GW_INFO)
if not ext_gw_info:
return {}, None
network = self._core_plugin.get_network(context,
ext_gw_info['network_id'])
# network names in GBP workflow need to be reduced, since
# the network may contain UUIDs
external_network = self.get_ext_net_name(network['name'])
# TODO(tbachman): see if we can get rid of the default
transit_net = self.transit_nets_cfg.get(
external_network) or self._default_ext_dict
transit_net['network_name'] = external_network
return transit_net, network | [
"def",
"_get_external_network_dict",
"(",
"self",
",",
"context",
",",
"port_db",
")",
":",
"if",
"port_db",
".",
"device_owner",
"==",
"DEVICE_OWNER_ROUTER_GW",
":",
"network",
"=",
"self",
".",
"_core_plugin",
".",
"get_network",
"(",
"context",
",",
"port_db"... | Get external network information
Get the information about the external network,
so that it can be used to create the hidden port,
subnet, and network. | [
"Get",
"external",
"network",
"information"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L148-L174 | train | 37,936 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver.apic_driver | def apic_driver(self):
"""Get APIC driver
There are different drivers for the GBP workflow
and Neutron workflow for APIC. First see if the GBP
workflow is active, and if so get the APIC driver for it.
If the GBP service isn't installed, try to get the driver
from the Neutron (APIC ML2) workflow.
"""
if not self._apic_driver:
try:
self._apic_driver = (bc.get_plugin(
'GROUP_POLICY').policy_driver_manager.
policy_drivers['apic'].obj)
self._get_ext_net_name = self._get_ext_net_name_gbp
self._get_vrf_context = self._get_vrf_context_gbp
except AttributeError:
LOG.info("GBP service plugin not present -- will "
"try APIC ML2 plugin.")
if not self._apic_driver:
try:
self._apic_driver = (
self._core_plugin.mechanism_manager.mech_drivers[
'cisco_apic_ml2'].obj)
self._get_ext_net_name = self._get_ext_net_name_neutron
self._get_vrf_context = self._get_vrf_context_neutron
except KeyError:
LOG.error("APIC ML2 plugin not present: "
"no APIC ML2 driver could be found.")
raise AciDriverNoAciDriverInstalledOrConfigured()
return self._apic_driver | python | def apic_driver(self):
"""Get APIC driver
There are different drivers for the GBP workflow
and Neutron workflow for APIC. First see if the GBP
workflow is active, and if so get the APIC driver for it.
If the GBP service isn't installed, try to get the driver
from the Neutron (APIC ML2) workflow.
"""
if not self._apic_driver:
try:
self._apic_driver = (bc.get_plugin(
'GROUP_POLICY').policy_driver_manager.
policy_drivers['apic'].obj)
self._get_ext_net_name = self._get_ext_net_name_gbp
self._get_vrf_context = self._get_vrf_context_gbp
except AttributeError:
LOG.info("GBP service plugin not present -- will "
"try APIC ML2 plugin.")
if not self._apic_driver:
try:
self._apic_driver = (
self._core_plugin.mechanism_manager.mech_drivers[
'cisco_apic_ml2'].obj)
self._get_ext_net_name = self._get_ext_net_name_neutron
self._get_vrf_context = self._get_vrf_context_neutron
except KeyError:
LOG.error("APIC ML2 plugin not present: "
"no APIC ML2 driver could be found.")
raise AciDriverNoAciDriverInstalledOrConfigured()
return self._apic_driver | [
"def",
"apic_driver",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_apic_driver",
":",
"try",
":",
"self",
".",
"_apic_driver",
"=",
"(",
"bc",
".",
"get_plugin",
"(",
"'GROUP_POLICY'",
")",
".",
"policy_driver_manager",
".",
"policy_drivers",
"[",
"'... | Get APIC driver
There are different drivers for the GBP workflow
and Neutron workflow for APIC. First see if the GBP
workflow is active, and if so get the APIC driver for it.
If the GBP service isn't installed, try to get the driver
from the Neutron (APIC ML2) workflow. | [
"Get",
"APIC",
"driver"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L183-L213 | train | 37,937 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver._snat_subnet_for_ext_net | def _snat_subnet_for_ext_net(self, context, subnet, net):
"""Determine if an SNAT subnet is for this external network.
This method determines if a given SNAT subnet is intended for
the passed external network.
For APIC ML2/Neutron workflow, SNAT subnets are created on
a separate network from the external network. The association
with an external network is made by putting the name of the
external network in the name of the SNAT network name, using
a well-known prefix.
"""
if subnet['network_id'] == net['id']:
return True
network = self._core_plugin.get_network(
context.elevated(), subnet['network_id'])
ext_net_name = network['name']
if (APIC_SNAT_NET + '-') in ext_net_name:
# This is APIC ML2 mode -- we need to strip the prefix
ext_net_name = ext_net_name[len(APIC_SNAT_NET + '-'):]
if net['id'] == ext_net_name:
return True
return False | python | def _snat_subnet_for_ext_net(self, context, subnet, net):
"""Determine if an SNAT subnet is for this external network.
This method determines if a given SNAT subnet is intended for
the passed external network.
For APIC ML2/Neutron workflow, SNAT subnets are created on
a separate network from the external network. The association
with an external network is made by putting the name of the
external network in the name of the SNAT network name, using
a well-known prefix.
"""
if subnet['network_id'] == net['id']:
return True
network = self._core_plugin.get_network(
context.elevated(), subnet['network_id'])
ext_net_name = network['name']
if (APIC_SNAT_NET + '-') in ext_net_name:
# This is APIC ML2 mode -- we need to strip the prefix
ext_net_name = ext_net_name[len(APIC_SNAT_NET + '-'):]
if net['id'] == ext_net_name:
return True
return False | [
"def",
"_snat_subnet_for_ext_net",
"(",
"self",
",",
"context",
",",
"subnet",
",",
"net",
")",
":",
"if",
"subnet",
"[",
"'network_id'",
"]",
"==",
"net",
"[",
"'id'",
"]",
":",
"return",
"True",
"network",
"=",
"self",
".",
"_core_plugin",
".",
"get_ne... | Determine if an SNAT subnet is for this external network.
This method determines if a given SNAT subnet is intended for
the passed external network.
For APIC ML2/Neutron workflow, SNAT subnets are created on
a separate network from the external network. The association
with an external network is made by putting the name of the
external network in the name of the SNAT network name, using
a well-known prefix. | [
"Determine",
"if",
"an",
"SNAT",
"subnet",
"is",
"for",
"this",
"external",
"network",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L215-L238 | train | 37,938 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver.extend_hosting_port_info | def extend_hosting_port_info(self, context, port_db, hosting_device,
hosting_info):
"""Get the segmenetation ID and interface
This extends the hosting info attribute with the segmentation ID
and physical interface used on the external router to connect to
the ACI fabric. The segmentation ID should have been set already
by the call to allocate_hosting_port, but if it's not present, use
the value from the port resource.
"""
if hosting_info.get('segmentation_id') is None:
LOG.debug('No segmentation ID in hosting_info -- assigning')
hosting_info['segmentation_id'] = (
port_db.hosting_info.get('segmentation_id'))
is_external = (port_db.device_owner == DEVICE_OWNER_ROUTER_GW)
hosting_info['physical_interface'] = self._get_interface_info(
hosting_device['id'], port_db.network_id, is_external)
ext_dict, net = self._get_external_network_dict(context, port_db)
if is_external and ext_dict:
hosting_info['network_name'] = ext_dict['network_name']
hosting_info['cidr_exposed'] = ext_dict['cidr_exposed']
hosting_info['gateway_ip'] = ext_dict['gateway_ip']
details = self.get_vrf_context(context,
port_db['device_id'], port_db)
router_id = port_db.device_id
router = self.l3_plugin.get_router(context, router_id)
# skip routers not created by the user -- they will have
# empty-string tenant IDs
if router.get(ROUTER_ROLE_ATTR):
return
hosting_info['vrf_id'] = details['vrf_id']
if ext_dict.get('global_config'):
hosting_info['global_config'] = (
ext_dict['global_config'])
self._add_snat_info(context, router, net, hosting_info)
else:
if ext_dict.get('interface_config'):
hosting_info['interface_config'] = ext_dict['interface_config'] | python | def extend_hosting_port_info(self, context, port_db, hosting_device,
hosting_info):
"""Get the segmenetation ID and interface
This extends the hosting info attribute with the segmentation ID
and physical interface used on the external router to connect to
the ACI fabric. The segmentation ID should have been set already
by the call to allocate_hosting_port, but if it's not present, use
the value from the port resource.
"""
if hosting_info.get('segmentation_id') is None:
LOG.debug('No segmentation ID in hosting_info -- assigning')
hosting_info['segmentation_id'] = (
port_db.hosting_info.get('segmentation_id'))
is_external = (port_db.device_owner == DEVICE_OWNER_ROUTER_GW)
hosting_info['physical_interface'] = self._get_interface_info(
hosting_device['id'], port_db.network_id, is_external)
ext_dict, net = self._get_external_network_dict(context, port_db)
if is_external and ext_dict:
hosting_info['network_name'] = ext_dict['network_name']
hosting_info['cidr_exposed'] = ext_dict['cidr_exposed']
hosting_info['gateway_ip'] = ext_dict['gateway_ip']
details = self.get_vrf_context(context,
port_db['device_id'], port_db)
router_id = port_db.device_id
router = self.l3_plugin.get_router(context, router_id)
# skip routers not created by the user -- they will have
# empty-string tenant IDs
if router.get(ROUTER_ROLE_ATTR):
return
hosting_info['vrf_id'] = details['vrf_id']
if ext_dict.get('global_config'):
hosting_info['global_config'] = (
ext_dict['global_config'])
self._add_snat_info(context, router, net, hosting_info)
else:
if ext_dict.get('interface_config'):
hosting_info['interface_config'] = ext_dict['interface_config'] | [
"def",
"extend_hosting_port_info",
"(",
"self",
",",
"context",
",",
"port_db",
",",
"hosting_device",
",",
"hosting_info",
")",
":",
"if",
"hosting_info",
".",
"get",
"(",
"'segmentation_id'",
")",
"is",
"None",
":",
"LOG",
".",
"debug",
"(",
"'No segmentatio... | Get the segmenetation ID and interface
This extends the hosting info attribute with the segmentation ID
and physical interface used on the external router to connect to
the ACI fabric. The segmentation ID should have been set already
by the call to allocate_hosting_port, but if it's not present, use
the value from the port resource. | [
"Get",
"the",
"segmenetation",
"ID",
"and",
"interface"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L258-L295 | train | 37,939 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver.allocate_hosting_port | def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
"""Get the VLAN and port for this hosting device
The VLAN used between the APIC and the external router is stored
by the APIC driver. This calls into the APIC driver to first get
the ACI VRF information associated with this port, then uses that
to look up the VLAN to use for this port to the external router
(kept as part of the L3 Out policy in ACI).
"""
# If this is a router interface, the VLAN comes from APIC.
# If it's the gateway, the VLAN comes from the segment ID
if port_db.get('device_owner') == DEVICE_OWNER_ROUTER_GW:
ext_dict, net = self._get_external_network_dict(context, port_db)
# If an OpFlex network is used on the external network,
# the actual segment ID comes from the config file
if net and net.get('provider:network_type') == 'opflex':
if ext_dict.get('segmentation_id'):
return {'allocated_port_id': port_db.id,
'allocated_vlan': ext_dict['segmentation_id']}
else:
raise AciDriverConfigMissingSegmentationId(ext_net=net)
return super(AciVLANTrunkingPlugDriver,
self).allocate_hosting_port(
context, router_id,
port_db, network_type, hosting_device_id)
# shouldn't happen, but just in case
if port_db.get('device_owner') != DEVICE_OWNER_ROUTER_INTF:
return
# get the external network that this port connects to.
# if there isn't an external gateway yet on the router,
# then don't allocate a port
router = self.l3_plugin.get_router(context, router_id)
gw_info = router[EXTERNAL_GW_INFO]
if not gw_info:
return
network_id = gw_info.get('network_id')
networks = self._core_plugin.get_networks(
context.elevated(), {'id': [network_id]})
l3out_network = networks[0]
l3out_name = self.get_ext_net_name(l3out_network['name'])
# For VLAN apic driver provides VLAN tag
details = self.get_vrf_context(context, router_id, port_db)
if details is None:
LOG.debug('aci_vlan_trunking_driver: No vrf_details')
return
vrf_name = details.get('vrf_name')
vrf_tenant = details.get('vrf_tenant')
allocated_vlan = self.apic_driver.l3out_vlan_alloc.get_vlan_allocated(
l3out_name, vrf_name, vrf_tenant=vrf_tenant)
if allocated_vlan is None:
if not vrf_tenant:
# TODO(tbachman): I can't remember why this is here
return super(AciVLANTrunkingPlugDriver,
self).allocate_hosting_port(
context, router_id,
port_db, network_type, hosting_device_id
)
# Database must have been messed up if this happens ...
return
return {'allocated_port_id': port_db.id,
'allocated_vlan': allocated_vlan} | python | def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
"""Get the VLAN and port for this hosting device
The VLAN used between the APIC and the external router is stored
by the APIC driver. This calls into the APIC driver to first get
the ACI VRF information associated with this port, then uses that
to look up the VLAN to use for this port to the external router
(kept as part of the L3 Out policy in ACI).
"""
# If this is a router interface, the VLAN comes from APIC.
# If it's the gateway, the VLAN comes from the segment ID
if port_db.get('device_owner') == DEVICE_OWNER_ROUTER_GW:
ext_dict, net = self._get_external_network_dict(context, port_db)
# If an OpFlex network is used on the external network,
# the actual segment ID comes from the config file
if net and net.get('provider:network_type') == 'opflex':
if ext_dict.get('segmentation_id'):
return {'allocated_port_id': port_db.id,
'allocated_vlan': ext_dict['segmentation_id']}
else:
raise AciDriverConfigMissingSegmentationId(ext_net=net)
return super(AciVLANTrunkingPlugDriver,
self).allocate_hosting_port(
context, router_id,
port_db, network_type, hosting_device_id)
# shouldn't happen, but just in case
if port_db.get('device_owner') != DEVICE_OWNER_ROUTER_INTF:
return
# get the external network that this port connects to.
# if there isn't an external gateway yet on the router,
# then don't allocate a port
router = self.l3_plugin.get_router(context, router_id)
gw_info = router[EXTERNAL_GW_INFO]
if not gw_info:
return
network_id = gw_info.get('network_id')
networks = self._core_plugin.get_networks(
context.elevated(), {'id': [network_id]})
l3out_network = networks[0]
l3out_name = self.get_ext_net_name(l3out_network['name'])
# For VLAN apic driver provides VLAN tag
details = self.get_vrf_context(context, router_id, port_db)
if details is None:
LOG.debug('aci_vlan_trunking_driver: No vrf_details')
return
vrf_name = details.get('vrf_name')
vrf_tenant = details.get('vrf_tenant')
allocated_vlan = self.apic_driver.l3out_vlan_alloc.get_vlan_allocated(
l3out_name, vrf_name, vrf_tenant=vrf_tenant)
if allocated_vlan is None:
if not vrf_tenant:
# TODO(tbachman): I can't remember why this is here
return super(AciVLANTrunkingPlugDriver,
self).allocate_hosting_port(
context, router_id,
port_db, network_type, hosting_device_id
)
# Database must have been messed up if this happens ...
return
return {'allocated_port_id': port_db.id,
'allocated_vlan': allocated_vlan} | [
"def",
"allocate_hosting_port",
"(",
"self",
",",
"context",
",",
"router_id",
",",
"port_db",
",",
"network_type",
",",
"hosting_device_id",
")",
":",
"# If this is a router interface, the VLAN comes from APIC.",
"# If it's the gateway, the VLAN comes from the segment ID",
"if",... | Get the VLAN and port for this hosting device
The VLAN used between the APIC and the external router is stored
by the APIC driver. This calls into the APIC driver to first get
the ACI VRF information associated with this port, then uses that
to look up the VLAN to use for this port to the external router
(kept as part of the L3 Out policy in ACI). | [
"Get",
"the",
"VLAN",
"and",
"port",
"for",
"this",
"hosting",
"device"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L297-L362 | train | 37,940 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py | AciVLANTrunkingPlugDriver._get_ext_net_name_gbp | def _get_ext_net_name_gbp(self, network_name):
"""Get the external network name
The name of the external network used in the APIC
configuration file can be different from the name
of the external network in Neutron, especially using
the GBP workflow
"""
prefix = network_name[:re.search(UUID_REGEX, network_name).start() - 1]
return prefix.strip(APIC_OWNED) | python | def _get_ext_net_name_gbp(self, network_name):
"""Get the external network name
The name of the external network used in the APIC
configuration file can be different from the name
of the external network in Neutron, especially using
the GBP workflow
"""
prefix = network_name[:re.search(UUID_REGEX, network_name).start() - 1]
return prefix.strip(APIC_OWNED) | [
"def",
"_get_ext_net_name_gbp",
"(",
"self",
",",
"network_name",
")",
":",
"prefix",
"=",
"network_name",
"[",
":",
"re",
".",
"search",
"(",
"UUID_REGEX",
",",
"network_name",
")",
".",
"start",
"(",
")",
"-",
"1",
"]",
"return",
"prefix",
".",
"strip"... | Get the external network name
The name of the external network used in the APIC
configuration file can be different from the name
of the external network in Neutron, especially using
the GBP workflow | [
"Get",
"the",
"external",
"network",
"name"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/plugging_drivers/aci_vlan_trunking_driver.py#L365-L374 | train | 37,941 |
openstack/networking-cisco | networking_cisco/apps/saf/common/utils.py | is_valid_mac | def is_valid_mac(addr):
"""Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx
"""
addrs = addr.split(':')
if len(addrs) != 6:
return False
for m in addrs:
try:
if int(m, 16) > 255:
return False
except ValueError:
return False
return True | python | def is_valid_mac(addr):
"""Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx
"""
addrs = addr.split(':')
if len(addrs) != 6:
return False
for m in addrs:
try:
if int(m, 16) > 255:
return False
except ValueError:
return False
return True | [
"def",
"is_valid_mac",
"(",
"addr",
")",
":",
"addrs",
"=",
"addr",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"addrs",
")",
"!=",
"6",
":",
"return",
"False",
"for",
"m",
"in",
"addrs",
":",
"try",
":",
"if",
"int",
"(",
"m",
",",
"16",
... | Check the syntax of a given mac address.
The acceptable format is xx:xx:xx:xx:xx:xx | [
"Check",
"the",
"syntax",
"of",
"a",
"given",
"mac",
"address",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/common/utils.py#L144-L158 | train | 37,942 |
openstack/networking-cisco | networking_cisco/apps/saf/common/utils.py | make_cidr | def make_cidr(gw, mask):
"""Create network address in CIDR format.
Return network address for a given gateway address and netmask.
"""
try:
int_mask = (0xFFFFFFFF << (32 - int(mask))) & 0xFFFFFFFF
gw_addr_int = struct.unpack('>L', socket.inet_aton(gw))[0] & int_mask
return (socket.inet_ntoa(struct.pack("!I", gw_addr_int)) +
'/' + str(mask))
except (socket.error, struct.error, ValueError, TypeError):
return | python | def make_cidr(gw, mask):
"""Create network address in CIDR format.
Return network address for a given gateway address and netmask.
"""
try:
int_mask = (0xFFFFFFFF << (32 - int(mask))) & 0xFFFFFFFF
gw_addr_int = struct.unpack('>L', socket.inet_aton(gw))[0] & int_mask
return (socket.inet_ntoa(struct.pack("!I", gw_addr_int)) +
'/' + str(mask))
except (socket.error, struct.error, ValueError, TypeError):
return | [
"def",
"make_cidr",
"(",
"gw",
",",
"mask",
")",
":",
"try",
":",
"int_mask",
"=",
"(",
"0xFFFFFFFF",
"<<",
"(",
"32",
"-",
"int",
"(",
"mask",
")",
")",
")",
"&",
"0xFFFFFFFF",
"gw_addr_int",
"=",
"struct",
".",
"unpack",
"(",
"'>L'",
",",
"socket... | Create network address in CIDR format.
Return network address for a given gateway address and netmask. | [
"Create",
"network",
"address",
"in",
"CIDR",
"format",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/common/utils.py#L161-L172 | train | 37,943 |
openstack/networking-cisco | networking_cisco/apps/saf/common/utils.py | find_agent_host_id | def find_agent_host_id(this_host):
"""Returns the neutron agent host id for RHEL-OSP6 HA setup."""
host_id = this_host
try:
for root, dirs, files in os.walk('/run/resource-agents'):
for fi in files:
if 'neutron-scale-' in fi:
host_id = 'neutron-n-' + fi.split('-')[2]
break
return host_id
except IndexError:
return host_id | python | def find_agent_host_id(this_host):
"""Returns the neutron agent host id for RHEL-OSP6 HA setup."""
host_id = this_host
try:
for root, dirs, files in os.walk('/run/resource-agents'):
for fi in files:
if 'neutron-scale-' in fi:
host_id = 'neutron-n-' + fi.split('-')[2]
break
return host_id
except IndexError:
return host_id | [
"def",
"find_agent_host_id",
"(",
"this_host",
")",
":",
"host_id",
"=",
"this_host",
"try",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"'/run/resource-agents'",
")",
":",
"for",
"fi",
"in",
"files",
":",
"if",
"'neutron... | Returns the neutron agent host id for RHEL-OSP6 HA setup. | [
"Returns",
"the",
"neutron",
"agent",
"host",
"id",
"for",
"RHEL",
"-",
"OSP6",
"HA",
"setup",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/apps/saf/common/utils.py#L175-L187 | train | 37,944 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._build_credentials | def _build_credentials(self, nexus_switches):
"""Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list
"""
credentials = {}
for switch_ip, attrs in nexus_switches.items():
credentials[switch_ip] = (
attrs[const.USERNAME], attrs[const.PASSWORD],
attrs[const.HTTPS_VERIFY], attrs[const.HTTPS_CERT],
None)
if not attrs[const.HTTPS_VERIFY]:
LOG.warning("HTTPS Certificate verification is "
"disabled. Your connection to Nexus "
"Switch %(ip)s is insecure.",
{'ip': switch_ip})
return credentials | python | def _build_credentials(self, nexus_switches):
"""Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list
"""
credentials = {}
for switch_ip, attrs in nexus_switches.items():
credentials[switch_ip] = (
attrs[const.USERNAME], attrs[const.PASSWORD],
attrs[const.HTTPS_VERIFY], attrs[const.HTTPS_CERT],
None)
if not attrs[const.HTTPS_VERIFY]:
LOG.warning("HTTPS Certificate verification is "
"disabled. Your connection to Nexus "
"Switch %(ip)s is insecure.",
{'ip': switch_ip})
return credentials | [
"def",
"_build_credentials",
"(",
"self",
",",
"nexus_switches",
")",
":",
"credentials",
"=",
"{",
"}",
"for",
"switch_ip",
",",
"attrs",
"in",
"nexus_switches",
".",
"items",
"(",
")",
":",
"credentials",
"[",
"switch_ip",
"]",
"=",
"(",
"attrs",
"[",
... | Build credential table for Rest API Client.
:param nexus_switches: switch config
:returns credentials: switch credentials list | [
"Build",
"credential",
"table",
"for",
"Rest",
"API",
"Client",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L76-L93 | train | 37,945 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.capture_and_print_timeshot | def capture_and_print_timeshot(self, start_time, which,
other=99, switch="x.x.x.x"):
"""Determine delta, keep track, and print results."""
curr_timeout = time.time() - start_time
if which in self.time_stats:
self.time_stats[which]["total_time"] += curr_timeout
self.time_stats[which]["total_count"] += 1
if (curr_timeout < self.time_stats[which]["min"]):
self.time_stats[which]["min"] = curr_timeout
if (curr_timeout > self.time_stats[which]["max"]):
self.time_stats[which]["max"] = curr_timeout
else:
self.time_stats[which] = {
"total_time": curr_timeout,
"total_count": 1,
"min": curr_timeout,
"max": curr_timeout}
LOG.debug("NEXUS_TIME_STATS %(switch)s, pid %(pid)d, tid %(tid)d: "
"%(which)s_timeout %(curr)f count %(count)d "
"average %(ave)f other %(other)d min %(min)f max %(max)f",
{'switch': switch,
'pid': os.getpid(),
'tid': threading.current_thread().ident,
'which': which,
'curr': curr_timeout,
'count': self.time_stats[which]["total_count"],
'ave': (self.time_stats[which]["total_time"] /
self.time_stats[which]["total_count"]),
'other': other,
'min': self.time_stats[which]["min"],
'max': self.time_stats[which]["max"]}) | python | def capture_and_print_timeshot(self, start_time, which,
other=99, switch="x.x.x.x"):
"""Determine delta, keep track, and print results."""
curr_timeout = time.time() - start_time
if which in self.time_stats:
self.time_stats[which]["total_time"] += curr_timeout
self.time_stats[which]["total_count"] += 1
if (curr_timeout < self.time_stats[which]["min"]):
self.time_stats[which]["min"] = curr_timeout
if (curr_timeout > self.time_stats[which]["max"]):
self.time_stats[which]["max"] = curr_timeout
else:
self.time_stats[which] = {
"total_time": curr_timeout,
"total_count": 1,
"min": curr_timeout,
"max": curr_timeout}
LOG.debug("NEXUS_TIME_STATS %(switch)s, pid %(pid)d, tid %(tid)d: "
"%(which)s_timeout %(curr)f count %(count)d "
"average %(ave)f other %(other)d min %(min)f max %(max)f",
{'switch': switch,
'pid': os.getpid(),
'tid': threading.current_thread().ident,
'which': which,
'curr': curr_timeout,
'count': self.time_stats[which]["total_count"],
'ave': (self.time_stats[which]["total_time"] /
self.time_stats[which]["total_count"]),
'other': other,
'min': self.time_stats[which]["min"],
'max': self.time_stats[which]["max"]}) | [
"def",
"capture_and_print_timeshot",
"(",
"self",
",",
"start_time",
",",
"which",
",",
"other",
"=",
"99",
",",
"switch",
"=",
"\"x.x.x.x\"",
")",
":",
"curr_timeout",
"=",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
"if",
"which",
"in",
"self",
"... | Determine delta, keep track, and print results. | [
"Determine",
"delta",
"keep",
"track",
"and",
"print",
"results",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L117-L148 | train | 37,946 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.get_interface_switch | def get_interface_switch(self, nexus_host,
intf_type, interface):
"""Get the interface data from host.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns response: Returns interface data
"""
if intf_type == "ethernet":
path_interface = "phys-[eth" + interface + "]"
else:
path_interface = "aggr-[po" + interface + "]"
action = snipp.PATH_IF % path_interface
starttime = time.time()
response = self.client.rest_get(action, nexus_host)
self.capture_and_print_timeshot(starttime, "getif",
switch=nexus_host)
LOG.debug("GET call returned interface %(if_type)s %(interface)s "
"config", {'if_type': intf_type, 'interface': interface})
return response | python | def get_interface_switch(self, nexus_host,
intf_type, interface):
"""Get the interface data from host.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns response: Returns interface data
"""
if intf_type == "ethernet":
path_interface = "phys-[eth" + interface + "]"
else:
path_interface = "aggr-[po" + interface + "]"
action = snipp.PATH_IF % path_interface
starttime = time.time()
response = self.client.rest_get(action, nexus_host)
self.capture_and_print_timeshot(starttime, "getif",
switch=nexus_host)
LOG.debug("GET call returned interface %(if_type)s %(interface)s "
"config", {'if_type': intf_type, 'interface': interface})
return response | [
"def",
"get_interface_switch",
"(",
"self",
",",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
":",
"if",
"intf_type",
"==",
"\"ethernet\"",
":",
"path_interface",
"=",
"\"phys-[eth\"",
"+",
"interface",
"+",
"\"]\"",
"else",
":",
"path_interface",
"=",... | Get the interface data from host.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns response: Returns interface data | [
"Get",
"the",
"interface",
"data",
"from",
"host",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L150-L175 | train | 37,947 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._get_interface_switch_trunk_present | def _get_interface_switch_trunk_present(
self, nexus_host, intf_type, interface):
"""Check if 'switchport trunk' configs present.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns mode_found: True if 'trunk mode' present
:returns vlan_configured: True if trunk allowed vlan list present
"""
result = self.get_interface_switch(nexus_host, intf_type, interface)
if_type = 'l1PhysIf' if intf_type == "ethernet" else 'pcAggrIf'
if_info = result['imdata'][0][if_type]
try:
mode_cfg = if_info['attributes']['mode']
except Exception:
mode_cfg = None
mode_found = (mode_cfg == "trunk")
try:
vlan_list = if_info['attributes']['trunkVlans']
except Exception:
vlan_list = None
vlan_configured = (vlan_list != const.UNCONFIGURED_VLAN)
return mode_found, vlan_configured | python | def _get_interface_switch_trunk_present(
self, nexus_host, intf_type, interface):
"""Check if 'switchport trunk' configs present.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns mode_found: True if 'trunk mode' present
:returns vlan_configured: True if trunk allowed vlan list present
"""
result = self.get_interface_switch(nexus_host, intf_type, interface)
if_type = 'l1PhysIf' if intf_type == "ethernet" else 'pcAggrIf'
if_info = result['imdata'][0][if_type]
try:
mode_cfg = if_info['attributes']['mode']
except Exception:
mode_cfg = None
mode_found = (mode_cfg == "trunk")
try:
vlan_list = if_info['attributes']['trunkVlans']
except Exception:
vlan_list = None
vlan_configured = (vlan_list != const.UNCONFIGURED_VLAN)
return mode_found, vlan_configured | [
"def",
"_get_interface_switch_trunk_present",
"(",
"self",
",",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
":",
"result",
"=",
"self",
".",
"get_interface_switch",
"(",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
"if_type",
"=",
"'l1PhysIf'"... | Check if 'switchport trunk' configs present.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns mode_found: True if 'trunk mode' present
:returns vlan_configured: True if trunk allowed vlan list present | [
"Check",
"if",
"switchport",
"trunk",
"configs",
"present",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L177-L208 | train | 37,948 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.add_ch_grp_to_interface | def add_ch_grp_to_interface(
self, nexus_host, if_type, port, ch_grp):
"""Applies channel-group n to ethernet interface."""
if if_type != "ethernet":
LOG.error("Unexpected interface type %(iftype)s when "
"adding change group", {'iftype': if_type})
return
starttime = time.time()
path_snip = snipp.PATH_ALL
path_interface = "phys-[eth" + port + "]"
body_snip = snipp.BODY_ADD_CH_GRP % (ch_grp, ch_grp, path_interface)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "add_ch_group",
switch=nexus_host) | python | def add_ch_grp_to_interface(
self, nexus_host, if_type, port, ch_grp):
"""Applies channel-group n to ethernet interface."""
if if_type != "ethernet":
LOG.error("Unexpected interface type %(iftype)s when "
"adding change group", {'iftype': if_type})
return
starttime = time.time()
path_snip = snipp.PATH_ALL
path_interface = "phys-[eth" + port + "]"
body_snip = snipp.BODY_ADD_CH_GRP % (ch_grp, ch_grp, path_interface)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "add_ch_group",
switch=nexus_host) | [
"def",
"add_ch_grp_to_interface",
"(",
"self",
",",
"nexus_host",
",",
"if_type",
",",
"port",
",",
"ch_grp",
")",
":",
"if",
"if_type",
"!=",
"\"ethernet\"",
":",
"LOG",
".",
"error",
"(",
"\"Unexpected interface type %(iftype)s when \"",
"\"adding change group\"",
... | Applies channel-group n to ethernet interface. | [
"Applies",
"channel",
"-",
"group",
"n",
"to",
"ethernet",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L210-L230 | train | 37,949 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._apply_user_port_channel_config | def _apply_user_port_channel_config(self, nexus_host, vpc_nbr):
"""Adds STP and no lacp suspend config to port channel. """
cli_cmds = self._get_user_port_channel_config(nexus_host, vpc_nbr)
if cli_cmds:
self._send_cli_conf_string(nexus_host, cli_cmds)
else:
vpc_str = str(vpc_nbr)
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_ADD_PORT_CH_P2 % (vpc_str, vpc_str)
self.send_edit_string(nexus_host, path_snip, body_snip) | python | def _apply_user_port_channel_config(self, nexus_host, vpc_nbr):
"""Adds STP and no lacp suspend config to port channel. """
cli_cmds = self._get_user_port_channel_config(nexus_host, vpc_nbr)
if cli_cmds:
self._send_cli_conf_string(nexus_host, cli_cmds)
else:
vpc_str = str(vpc_nbr)
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_ADD_PORT_CH_P2 % (vpc_str, vpc_str)
self.send_edit_string(nexus_host, path_snip, body_snip) | [
"def",
"_apply_user_port_channel_config",
"(",
"self",
",",
"nexus_host",
",",
"vpc_nbr",
")",
":",
"cli_cmds",
"=",
"self",
".",
"_get_user_port_channel_config",
"(",
"nexus_host",
",",
"vpc_nbr",
")",
"if",
"cli_cmds",
":",
"self",
".",
"_send_cli_conf_string",
... | Adds STP and no lacp suspend config to port channel. | [
"Adds",
"STP",
"and",
"no",
"lacp",
"suspend",
"config",
"to",
"port",
"channel",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L254-L264 | train | 37,950 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.create_port_channel | def create_port_channel(self, nexus_host, vpc_nbr):
"""Creates port channel n on Nexus switch."""
starttime = time.time()
vpc_str = str(vpc_nbr)
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_ADD_PORT_CH % (vpc_str, vpc_str, vpc_str)
self.send_edit_string(nexus_host, path_snip, body_snip)
self._apply_user_port_channel_config(nexus_host, vpc_nbr)
self.capture_and_print_timeshot(
starttime, "create_port_channel",
switch=nexus_host) | python | def create_port_channel(self, nexus_host, vpc_nbr):
"""Creates port channel n on Nexus switch."""
starttime = time.time()
vpc_str = str(vpc_nbr)
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_ADD_PORT_CH % (vpc_str, vpc_str, vpc_str)
self.send_edit_string(nexus_host, path_snip, body_snip)
self._apply_user_port_channel_config(nexus_host, vpc_nbr)
self.capture_and_print_timeshot(
starttime, "create_port_channel",
switch=nexus_host) | [
"def",
"create_port_channel",
"(",
"self",
",",
"nexus_host",
",",
"vpc_nbr",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"vpc_str",
"=",
"str",
"(",
"vpc_nbr",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_ALL",
"body_snip",
"=",
"snipp",
".... | Creates port channel n on Nexus switch. | [
"Creates",
"port",
"channel",
"n",
"on",
"Nexus",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L266-L281 | train | 37,951 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.delete_port_channel | def delete_port_channel(self, nexus_host, vpc_nbr):
"""Deletes delete port channel on Nexus switch."""
starttime = time.time()
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_DEL_PORT_CH % (vpc_nbr)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "delete_port_channel",
switch=nexus_host) | python | def delete_port_channel(self, nexus_host, vpc_nbr):
"""Deletes delete port channel on Nexus switch."""
starttime = time.time()
path_snip = snipp.PATH_ALL
body_snip = snipp.BODY_DEL_PORT_CH % (vpc_nbr)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "delete_port_channel",
switch=nexus_host) | [
"def",
"delete_port_channel",
"(",
"self",
",",
"nexus_host",
",",
"vpc_nbr",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_ALL",
"body_snip",
"=",
"snipp",
".",
"BODY_DEL_PORT_CH",
"%",
"(",
"vpc_nbr",
")... | Deletes delete port channel on Nexus switch. | [
"Deletes",
"delete",
"port",
"channel",
"on",
"Nexus",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L283-L295 | train | 37,952 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._get_port_channel_group | def _get_port_channel_group(self, nexus_host, intf_type, interface):
"""Look for 'channel-group x' config and return x.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns pc_group: Returns port channel group if
present else 0
"""
ch_grp = 0
# channel-group only applied to ethernet,
# otherwise, return 0
if intf_type != 'ethernet':
return ch_grp
match_key = "eth" + interface
action = snipp.PATH_GET_PC_MEMBERS
starttime = time.time()
result = self.client.rest_get(action, nexus_host)
self.capture_and_print_timeshot(starttime, "getpc",
switch=nexus_host)
try:
for pcmbr in result['imdata']:
mbr_data = pcmbr['pcRsMbrIfs']['attributes']
if mbr_data['tSKey'] == match_key:
_, nbr = mbr_data['parentSKey'].split("po")
ch_grp = int(nbr)
break
except Exception:
# Valid when there is no channel-group configured.
ch_grp = 0
LOG.debug("GET interface %(key)s port channel is %(pc)d",
{'key': match_key, 'pc': ch_grp})
return ch_grp | python | def _get_port_channel_group(self, nexus_host, intf_type, interface):
"""Look for 'channel-group x' config and return x.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns pc_group: Returns port channel group if
present else 0
"""
ch_grp = 0
# channel-group only applied to ethernet,
# otherwise, return 0
if intf_type != 'ethernet':
return ch_grp
match_key = "eth" + interface
action = snipp.PATH_GET_PC_MEMBERS
starttime = time.time()
result = self.client.rest_get(action, nexus_host)
self.capture_and_print_timeshot(starttime, "getpc",
switch=nexus_host)
try:
for pcmbr in result['imdata']:
mbr_data = pcmbr['pcRsMbrIfs']['attributes']
if mbr_data['tSKey'] == match_key:
_, nbr = mbr_data['parentSKey'].split("po")
ch_grp = int(nbr)
break
except Exception:
# Valid when there is no channel-group configured.
ch_grp = 0
LOG.debug("GET interface %(key)s port channel is %(pc)d",
{'key': match_key, 'pc': ch_grp})
return ch_grp | [
"def",
"_get_port_channel_group",
"(",
"self",
",",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
":",
"ch_grp",
"=",
"0",
"# channel-group only applied to ethernet,",
"# otherwise, return 0",
"if",
"intf_type",
"!=",
"'ethernet'",
":",
"return",
"ch_grp",
"m... | Look for 'channel-group x' config and return x.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:returns pc_group: Returns port channel group if
present else 0 | [
"Look",
"for",
"channel",
"-",
"group",
"x",
"config",
"and",
"return",
"x",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L297-L338 | train | 37,953 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.initialize_baremetal_switch_interfaces | def initialize_baremetal_switch_interfaces(self, interfaces):
"""Initialize Nexus interfaces and for initial baremetal event.
This get/create port channel number, applies channel-group to
ethernet interface, and initializes trunking on interface.
:param interfaces: Receive a list of interfaces containing:
nexus_host: IP address of Nexus switch
intf_type: String which specifies interface type. example: ethernet
interface: String indicating which interface. example: 1/19
is_native: Whether native vlan must be configured.
ch_grp: May replace port channel to each entry. channel number is
0 if none
"""
if not interfaces:
return
max_ifs = len(interfaces)
starttime = time.time()
learned, nexus_ip_list = self._build_host_list_and_verify_chgrp(
interfaces)
if not nexus_ip_list:
return
if max_ifs > 1:
# update vpc db with learned vpcid or get new one.
if learned:
ch_grp = interfaces[0][-1]
self._configure_learned_port_channel(
nexus_ip_list, ch_grp)
else:
ch_grp = self._get_new_baremetal_portchannel_id(nexus_ip_list)
else:
ch_grp = 0
for i, (nexus_host, intf_type, nexus_port, is_native,
ch_grp_saved) in enumerate(interfaces):
if max_ifs > 1:
if learned:
ch_grp = ch_grp_saved
else:
self._config_new_baremetal_portchannel(
ch_grp, nexus_host, intf_type, nexus_port)
self._replace_interface_ch_grp(interfaces, i, ch_grp)
# init port-channel instead of the provided ethernet
intf_type = 'port-channel'
nexus_port = str(ch_grp)
else:
self._replace_interface_ch_grp(interfaces, i, ch_grp)
trunk_mode_present, vlan_present = (
self._get_interface_switch_trunk_present(
nexus_host, intf_type, nexus_port))
if not vlan_present:
self.send_enable_vlan_on_trunk_int(
nexus_host, "", intf_type, nexus_port, False,
not trunk_mode_present)
elif not trunk_mode_present:
LOG.warning(TRUNK_MODE_NOT_FOUND, nexus_host,
nexus_help.format_interface_name(
intf_type, nexus_port))
self.capture_and_print_timeshot(
starttime, "init_bmif",
switch=nexus_host) | python | def initialize_baremetal_switch_interfaces(self, interfaces):
"""Initialize Nexus interfaces and for initial baremetal event.
This get/create port channel number, applies channel-group to
ethernet interface, and initializes trunking on interface.
:param interfaces: Receive a list of interfaces containing:
nexus_host: IP address of Nexus switch
intf_type: String which specifies interface type. example: ethernet
interface: String indicating which interface. example: 1/19
is_native: Whether native vlan must be configured.
ch_grp: May replace port channel to each entry. channel number is
0 if none
"""
if not interfaces:
return
max_ifs = len(interfaces)
starttime = time.time()
learned, nexus_ip_list = self._build_host_list_and_verify_chgrp(
interfaces)
if not nexus_ip_list:
return
if max_ifs > 1:
# update vpc db with learned vpcid or get new one.
if learned:
ch_grp = interfaces[0][-1]
self._configure_learned_port_channel(
nexus_ip_list, ch_grp)
else:
ch_grp = self._get_new_baremetal_portchannel_id(nexus_ip_list)
else:
ch_grp = 0
for i, (nexus_host, intf_type, nexus_port, is_native,
ch_grp_saved) in enumerate(interfaces):
if max_ifs > 1:
if learned:
ch_grp = ch_grp_saved
else:
self._config_new_baremetal_portchannel(
ch_grp, nexus_host, intf_type, nexus_port)
self._replace_interface_ch_grp(interfaces, i, ch_grp)
# init port-channel instead of the provided ethernet
intf_type = 'port-channel'
nexus_port = str(ch_grp)
else:
self._replace_interface_ch_grp(interfaces, i, ch_grp)
trunk_mode_present, vlan_present = (
self._get_interface_switch_trunk_present(
nexus_host, intf_type, nexus_port))
if not vlan_present:
self.send_enable_vlan_on_trunk_int(
nexus_host, "", intf_type, nexus_port, False,
not trunk_mode_present)
elif not trunk_mode_present:
LOG.warning(TRUNK_MODE_NOT_FOUND, nexus_host,
nexus_help.format_interface_name(
intf_type, nexus_port))
self.capture_and_print_timeshot(
starttime, "init_bmif",
switch=nexus_host) | [
"def",
"initialize_baremetal_switch_interfaces",
"(",
"self",
",",
"interfaces",
")",
":",
"if",
"not",
"interfaces",
":",
"return",
"max_ifs",
"=",
"len",
"(",
"interfaces",
")",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"learned",
",",
"nexus_ip_list"... | Initialize Nexus interfaces and for initial baremetal event.
This get/create port channel number, applies channel-group to
ethernet interface, and initializes trunking on interface.
:param interfaces: Receive a list of interfaces containing:
nexus_host: IP address of Nexus switch
intf_type: String which specifies interface type. example: ethernet
interface: String indicating which interface. example: 1/19
is_native: Whether native vlan must be configured.
ch_grp: May replace port channel to each entry. channel number is
0 if none | [
"Initialize",
"Nexus",
"interfaces",
"and",
"for",
"initial",
"baremetal",
"event",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L468-L535 | train | 37,954 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.initialize_all_switch_interfaces | def initialize_all_switch_interfaces(self, interfaces,
switch_ip=None, replay=True):
"""Configure Nexus interface and get port channel number.
Called during switch replay or just init if no replay
is configured. For latter case, only configured interfaces
are affected by this method.
During switch replay, the change group from the
host mapping data base is used. There is no attempt
to relearn port-channel from the Nexus switch. What
we last knew it to be will persist.
:param interfaces: List of interfaces for a given switch.
ch_grp can be altered as last arg
to each interface. If no ch_grp,
this arg will be zero.
:param switch_ip: IP address of Nexus switch
:param replay: Whether in replay path
"""
if not interfaces:
return
starttime = time.time()
if replay:
try:
vpcs = nxos_db.get_active_switch_vpc_allocs(switch_ip)
except cexc.NexusVPCAllocNotFound:
vpcs = []
for vpc in vpcs:
# if this is an allocated vpc, then recreate it
if not vpc.learned:
self.create_port_channel(switch_ip, vpc.vpc_id)
for i, (nexus_host, intf_type, nexus_port, is_native,
ch_grp) in enumerate(interfaces):
if replay and ch_grp != 0:
try:
vpc = nxos_db.get_switch_vpc_alloc(switch_ip, ch_grp)
self.add_ch_grp_to_interface(
nexus_host, intf_type, nexus_port, ch_grp)
except cexc.NexusVPCAllocNotFound:
pass
# if channel-group exists, switch to port-channel
# instead of the provided ethernet interface
intf_type = 'port-channel'
nexus_port = str(ch_grp)
#substitute content of ch_grp
no_chgrp_len = len(interfaces[i]) - 1
interfaces[i] = interfaces[i][:no_chgrp_len] + (ch_grp,)
trunk_mode_present, vlan_present = (
self._get_interface_switch_trunk_present(
nexus_host, intf_type, nexus_port))
if not vlan_present:
self.send_enable_vlan_on_trunk_int(
nexus_host, "", intf_type, nexus_port, False,
not trunk_mode_present)
elif not trunk_mode_present:
LOG.warning(TRUNK_MODE_NOT_FOUND, nexus_host,
nexus_help.format_interface_name(
intf_type, nexus_port))
self.capture_and_print_timeshot(
starttime, "get_allif",
switch=nexus_host) | python | def initialize_all_switch_interfaces(self, interfaces,
switch_ip=None, replay=True):
"""Configure Nexus interface and get port channel number.
Called during switch replay or just init if no replay
is configured. For latter case, only configured interfaces
are affected by this method.
During switch replay, the change group from the
host mapping data base is used. There is no attempt
to relearn port-channel from the Nexus switch. What
we last knew it to be will persist.
:param interfaces: List of interfaces for a given switch.
ch_grp can be altered as last arg
to each interface. If no ch_grp,
this arg will be zero.
:param switch_ip: IP address of Nexus switch
:param replay: Whether in replay path
"""
if not interfaces:
return
starttime = time.time()
if replay:
try:
vpcs = nxos_db.get_active_switch_vpc_allocs(switch_ip)
except cexc.NexusVPCAllocNotFound:
vpcs = []
for vpc in vpcs:
# if this is an allocated vpc, then recreate it
if not vpc.learned:
self.create_port_channel(switch_ip, vpc.vpc_id)
for i, (nexus_host, intf_type, nexus_port, is_native,
ch_grp) in enumerate(interfaces):
if replay and ch_grp != 0:
try:
vpc = nxos_db.get_switch_vpc_alloc(switch_ip, ch_grp)
self.add_ch_grp_to_interface(
nexus_host, intf_type, nexus_port, ch_grp)
except cexc.NexusVPCAllocNotFound:
pass
# if channel-group exists, switch to port-channel
# instead of the provided ethernet interface
intf_type = 'port-channel'
nexus_port = str(ch_grp)
#substitute content of ch_grp
no_chgrp_len = len(interfaces[i]) - 1
interfaces[i] = interfaces[i][:no_chgrp_len] + (ch_grp,)
trunk_mode_present, vlan_present = (
self._get_interface_switch_trunk_present(
nexus_host, intf_type, nexus_port))
if not vlan_present:
self.send_enable_vlan_on_trunk_int(
nexus_host, "", intf_type, nexus_port, False,
not trunk_mode_present)
elif not trunk_mode_present:
LOG.warning(TRUNK_MODE_NOT_FOUND, nexus_host,
nexus_help.format_interface_name(
intf_type, nexus_port))
self.capture_and_print_timeshot(
starttime, "get_allif",
switch=nexus_host) | [
"def",
"initialize_all_switch_interfaces",
"(",
"self",
",",
"interfaces",
",",
"switch_ip",
"=",
"None",
",",
"replay",
"=",
"True",
")",
":",
"if",
"not",
"interfaces",
":",
"return",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"if",
"replay",
":",
... | Configure Nexus interface and get port channel number.
Called during switch replay or just init if no replay
is configured. For latter case, only configured interfaces
are affected by this method.
During switch replay, the change group from the
host mapping data base is used. There is no attempt
to relearn port-channel from the Nexus switch. What
we last knew it to be will persist.
:param interfaces: List of interfaces for a given switch.
ch_grp can be altered as last arg
to each interface. If no ch_grp,
this arg will be zero.
:param switch_ip: IP address of Nexus switch
:param replay: Whether in replay path | [
"Configure",
"Nexus",
"interface",
"and",
"get",
"port",
"channel",
"number",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L537-L604 | train | 37,955 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.get_nexus_type | def get_nexus_type(self, nexus_host):
"""Given the nexus host, get the type of Nexus switch.
:param nexus_host: IP address of Nexus switch
:returns: Nexus type
"""
starttime = time.time()
response = self.client.rest_get(
snipp.PATH_GET_NEXUS_TYPE, nexus_host)
self.capture_and_print_timeshot(
starttime, "gettype",
switch=nexus_host)
if response:
try:
result = response['imdata'][0]["eqptCh"]['attributes']['descr']
except Exception:
# Nexus Type is not depended on at this time so it's ok
# if can't get the Nexus type. The real purpose
# of this method is to determine if the connection is active.
result = ''
nexus_type = re.findall(
"Nexus\s*(\d)\d+\s*[0-9A-Z]+\s*"
"[cC]hassis",
result)
if len(nexus_type) > 0:
LOG.debug("GET call returned Nexus type %d",
int(nexus_type[0]))
return int(nexus_type[0])
else:
result = ''
LOG.debug("GET call failed to return Nexus type. Received %s.",
result)
return -1 | python | def get_nexus_type(self, nexus_host):
"""Given the nexus host, get the type of Nexus switch.
:param nexus_host: IP address of Nexus switch
:returns: Nexus type
"""
starttime = time.time()
response = self.client.rest_get(
snipp.PATH_GET_NEXUS_TYPE, nexus_host)
self.capture_and_print_timeshot(
starttime, "gettype",
switch=nexus_host)
if response:
try:
result = response['imdata'][0]["eqptCh"]['attributes']['descr']
except Exception:
# Nexus Type is not depended on at this time so it's ok
# if can't get the Nexus type. The real purpose
# of this method is to determine if the connection is active.
result = ''
nexus_type = re.findall(
"Nexus\s*(\d)\d+\s*[0-9A-Z]+\s*"
"[cC]hassis",
result)
if len(nexus_type) > 0:
LOG.debug("GET call returned Nexus type %d",
int(nexus_type[0]))
return int(nexus_type[0])
else:
result = ''
LOG.debug("GET call failed to return Nexus type. Received %s.",
result)
return -1 | [
"def",
"get_nexus_type",
"(",
"self",
",",
"nexus_host",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
"self",
".",
"client",
".",
"rest_get",
"(",
"snipp",
".",
"PATH_GET_NEXUS_TYPE",
",",
"nexus_host",
")",
"self",
".",
"c... | Given the nexus host, get the type of Nexus switch.
:param nexus_host: IP address of Nexus switch
:returns: Nexus type | [
"Given",
"the",
"nexus",
"host",
"get",
"the",
"type",
"of",
"Nexus",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L606-L641 | train | 37,956 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.get_create_vlan | def get_create_vlan(self, nexus_host, vlanid, vni, conf_str):
"""Returns an XML snippet for create VLAN on a Nexus Switch."""
starttime = time.time()
if vni:
body_snip = snipp.BODY_VXLAN_ALL_INCR % (vlanid, vni)
else:
body_snip = snipp.BODY_VLAN_ALL_INCR % vlanid
conf_str += body_snip + snipp.BODY_VLAN_ALL_CONT
self.capture_and_print_timeshot(
starttime, "get_create_vlan",
switch=nexus_host)
return conf_str | python | def get_create_vlan(self, nexus_host, vlanid, vni, conf_str):
"""Returns an XML snippet for create VLAN on a Nexus Switch."""
starttime = time.time()
if vni:
body_snip = snipp.BODY_VXLAN_ALL_INCR % (vlanid, vni)
else:
body_snip = snipp.BODY_VLAN_ALL_INCR % vlanid
conf_str += body_snip + snipp.BODY_VLAN_ALL_CONT
self.capture_and_print_timeshot(
starttime, "get_create_vlan",
switch=nexus_host)
return conf_str | [
"def",
"get_create_vlan",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"vni",
",",
"conf_str",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"if",
"vni",
":",
"body_snip",
"=",
"snipp",
".",
"BODY_VXLAN_ALL_INCR",
"%",
"(",
"vlanid",
... | Returns an XML snippet for create VLAN on a Nexus Switch. | [
"Returns",
"an",
"XML",
"snippet",
"for",
"create",
"VLAN",
"on",
"a",
"Nexus",
"Switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L654-L669 | train | 37,957 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.set_all_vlan_states | def set_all_vlan_states(self, nexus_host, vlanid_range):
"""Set the VLAN states to active."""
starttime = time.time()
if not vlanid_range:
LOG.warning("Exiting set_all_vlan_states: "
"No vlans to configure")
return
# Eliminate possible whitespace and separate vlans by commas
vlan_id_list = re.sub(r'\s', '', vlanid_range).split(',')
if not vlan_id_list or not vlan_id_list[0]:
LOG.warning("Exiting set_all_vlan_states: "
"No vlans to configure")
return
path_str, body_vlan_all = self.start_create_vlan()
while vlan_id_list:
rangev = vlan_id_list.pop(0)
if '-' in rangev:
fr, to = rangev.split('-')
max = int(to) + 1
for vlan_id in range(int(fr), max):
body_vlan_all = self.get_create_vlan(
nexus_host, vlan_id, 0, body_vlan_all)
else:
body_vlan_all = self.get_create_vlan(
nexus_host, rangev, 0, body_vlan_all)
body_vlan_all = self.end_create_vlan(body_vlan_all)
self.send_edit_string(
nexus_host, path_str, body_vlan_all)
self.capture_and_print_timeshot(
starttime, "set_all_vlan_states",
switch=nexus_host) | python | def set_all_vlan_states(self, nexus_host, vlanid_range):
"""Set the VLAN states to active."""
starttime = time.time()
if not vlanid_range:
LOG.warning("Exiting set_all_vlan_states: "
"No vlans to configure")
return
# Eliminate possible whitespace and separate vlans by commas
vlan_id_list = re.sub(r'\s', '', vlanid_range).split(',')
if not vlan_id_list or not vlan_id_list[0]:
LOG.warning("Exiting set_all_vlan_states: "
"No vlans to configure")
return
path_str, body_vlan_all = self.start_create_vlan()
while vlan_id_list:
rangev = vlan_id_list.pop(0)
if '-' in rangev:
fr, to = rangev.split('-')
max = int(to) + 1
for vlan_id in range(int(fr), max):
body_vlan_all = self.get_create_vlan(
nexus_host, vlan_id, 0, body_vlan_all)
else:
body_vlan_all = self.get_create_vlan(
nexus_host, rangev, 0, body_vlan_all)
body_vlan_all = self.end_create_vlan(body_vlan_all)
self.send_edit_string(
nexus_host, path_str, body_vlan_all)
self.capture_and_print_timeshot(
starttime, "set_all_vlan_states",
switch=nexus_host) | [
"def",
"set_all_vlan_states",
"(",
"self",
",",
"nexus_host",
",",
"vlanid_range",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"if",
"not",
"vlanid_range",
":",
"LOG",
".",
"warning",
"(",
"\"Exiting set_all_vlan_states: \"",
"\"No vlans to configur... | Set the VLAN states to active. | [
"Set",
"the",
"VLAN",
"states",
"to",
"active",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L671-L707 | train | 37,958 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.create_vlan | def create_vlan(self, nexus_host, vlanid, vni):
"""Given switch, vlanid, vni, Create a VLAN on Switch."""
starttime = time.time()
path_snip, body_snip = self.start_create_vlan()
body_snip = self.get_create_vlan(nexus_host, vlanid, vni, body_snip)
body_snip = self.end_create_vlan(body_snip)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "create_vlan_seg",
switch=nexus_host) | python | def create_vlan(self, nexus_host, vlanid, vni):
"""Given switch, vlanid, vni, Create a VLAN on Switch."""
starttime = time.time()
path_snip, body_snip = self.start_create_vlan()
body_snip = self.get_create_vlan(nexus_host, vlanid, vni, body_snip)
body_snip = self.end_create_vlan(body_snip)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "create_vlan_seg",
switch=nexus_host) | [
"def",
"create_vlan",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"vni",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
",",
"body_snip",
"=",
"self",
".",
"start_create_vlan",
"(",
")",
"body_snip",
"=",
"self",
".",
"... | Given switch, vlanid, vni, Create a VLAN on Switch. | [
"Given",
"switch",
"vlanid",
"vni",
"Create",
"a",
"VLAN",
"on",
"Switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L709-L721 | train | 37,959 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.delete_vlan | def delete_vlan(self, nexus_host, vlanid):
"""Delete a VLAN on Nexus Switch given the VLAN ID."""
starttime = time.time()
path_snip = snipp.PATH_VLAN % vlanid
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "del_vlan",
switch=nexus_host) | python | def delete_vlan(self, nexus_host, vlanid):
"""Delete a VLAN on Nexus Switch given the VLAN ID."""
starttime = time.time()
path_snip = snipp.PATH_VLAN % vlanid
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "del_vlan",
switch=nexus_host) | [
"def",
"delete_vlan",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_VLAN",
"%",
"vlanid",
"self",
".",
"client",
".",
"rest_delete",
"(",
"path_snip",
",",
... | Delete a VLAN on Nexus Switch given the VLAN ID. | [
"Delete",
"a",
"VLAN",
"on",
"Nexus",
"Switch",
"given",
"the",
"VLAN",
"ID",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L723-L732 | train | 37,960 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._get_vlan_body_on_trunk_int | def _get_vlan_body_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native, is_delete,
add_mode):
"""Prepares an XML snippet for VLAN on a trunk interface.
:param nexus_host: IP address of Nexus switch
:param vlanid: Vlanid(s) to add to interface
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:param is_native: Is native vlan config desired?
:param is_delete: Is this a delete operation?
:param add_mode: Add mode trunk
:returns path_snippet, body_snippet
"""
starttime = time.time()
LOG.debug("NexusDriver get if body config for host %s: "
"if_type %s port %s",
nexus_host, intf_type, interface)
if intf_type == "ethernet":
body_if_type = "l1PhysIf"
path_interface = "phys-[eth" + interface + "]"
else:
body_if_type = "pcAggrIf"
path_interface = "aggr-[po" + interface + "]"
path_snip = (snipp.PATH_IF % (path_interface))
mode = snipp.BODY_PORT_CH_MODE if add_mode else ''
if is_delete:
increment_it = "-"
debug_desc = "delif"
native_vlan = ""
else:
native_vlan = 'vlan-' + str(vlanid)
debug_desc = "createif"
if vlanid is "":
increment_it = ""
else:
increment_it = "+"
if is_native:
body_snip = (snipp.BODY_NATIVE_TRUNKVLAN %
(body_if_type, mode, increment_it + str(vlanid),
str(native_vlan)))
else:
body_snip = (snipp.BODY_TRUNKVLAN %
(body_if_type, mode, increment_it + str(vlanid)))
self.capture_and_print_timeshot(
starttime, debug_desc,
switch=nexus_host)
return path_snip, body_snip | python | def _get_vlan_body_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native, is_delete,
add_mode):
"""Prepares an XML snippet for VLAN on a trunk interface.
:param nexus_host: IP address of Nexus switch
:param vlanid: Vlanid(s) to add to interface
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:param is_native: Is native vlan config desired?
:param is_delete: Is this a delete operation?
:param add_mode: Add mode trunk
:returns path_snippet, body_snippet
"""
starttime = time.time()
LOG.debug("NexusDriver get if body config for host %s: "
"if_type %s port %s",
nexus_host, intf_type, interface)
if intf_type == "ethernet":
body_if_type = "l1PhysIf"
path_interface = "phys-[eth" + interface + "]"
else:
body_if_type = "pcAggrIf"
path_interface = "aggr-[po" + interface + "]"
path_snip = (snipp.PATH_IF % (path_interface))
mode = snipp.BODY_PORT_CH_MODE if add_mode else ''
if is_delete:
increment_it = "-"
debug_desc = "delif"
native_vlan = ""
else:
native_vlan = 'vlan-' + str(vlanid)
debug_desc = "createif"
if vlanid is "":
increment_it = ""
else:
increment_it = "+"
if is_native:
body_snip = (snipp.BODY_NATIVE_TRUNKVLAN %
(body_if_type, mode, increment_it + str(vlanid),
str(native_vlan)))
else:
body_snip = (snipp.BODY_TRUNKVLAN %
(body_if_type, mode, increment_it + str(vlanid)))
self.capture_and_print_timeshot(
starttime, debug_desc,
switch=nexus_host)
return path_snip, body_snip | [
"def",
"_get_vlan_body_on_trunk_int",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"intf_type",
",",
"interface",
",",
"is_native",
",",
"is_delete",
",",
"add_mode",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"LOG",
".",
"debug",
"(... | Prepares an XML snippet for VLAN on a trunk interface.
:param nexus_host: IP address of Nexus switch
:param vlanid: Vlanid(s) to add to interface
:param intf_type: String which specifies interface type.
example: ethernet
:param interface: String indicating which interface.
example: 1/19
:param is_native: Is native vlan config desired?
:param is_delete: Is this a delete operation?
:param add_mode: Add mode trunk
:returns path_snippet, body_snippet | [
"Prepares",
"an",
"XML",
"snippet",
"for",
"VLAN",
"on",
"a",
"trunk",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L734-L790 | train | 37,961 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.disable_vlan_on_trunk_int | def disable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native):
"""Disable a VLAN on a trunk interface."""
starttime = time.time()
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, True, False)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "delif",
switch=nexus_host) | python | def disable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native):
"""Disable a VLAN on a trunk interface."""
starttime = time.time()
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, True, False)
self.send_edit_string(nexus_host, path_snip, body_snip)
self.capture_and_print_timeshot(
starttime, "delif",
switch=nexus_host) | [
"def",
"disable_vlan_on_trunk_int",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"intf_type",
",",
"interface",
",",
"is_native",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
",",
"body_snip",
"=",
"self",
".",
"_get_vlan_bo... | Disable a VLAN on a trunk interface. | [
"Disable",
"a",
"VLAN",
"on",
"a",
"trunk",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L792-L804 | train | 37,962 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.send_edit_string | def send_edit_string(self, nexus_host, path_snip, body_snip,
check_to_close_session=True):
"""Sends rest Post request to Nexus switch."""
starttime = time.time()
LOG.debug("NexusDriver edit config for host %s: path: %s body: %s",
nexus_host, path_snip, body_snip)
self.client.rest_post(path_snip, nexus_host, body_snip)
self.capture_and_print_timeshot(
starttime, "send_edit",
switch=nexus_host) | python | def send_edit_string(self, nexus_host, path_snip, body_snip,
check_to_close_session=True):
"""Sends rest Post request to Nexus switch."""
starttime = time.time()
LOG.debug("NexusDriver edit config for host %s: path: %s body: %s",
nexus_host, path_snip, body_snip)
self.client.rest_post(path_snip, nexus_host, body_snip)
self.capture_and_print_timeshot(
starttime, "send_edit",
switch=nexus_host) | [
"def",
"send_edit_string",
"(",
"self",
",",
"nexus_host",
",",
"path_snip",
",",
"body_snip",
",",
"check_to_close_session",
"=",
"True",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"LOG",
".",
"debug",
"(",
"\"NexusDriver edit config for host %s... | Sends rest Post request to Nexus switch. | [
"Sends",
"rest",
"Post",
"request",
"to",
"Nexus",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L806-L816 | train | 37,963 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver._send_cli_conf_string | def _send_cli_conf_string(self, nexus_host, cli_str):
"""Sends CLI Config commands to Nexus switch using NXAPI."""
starttime = time.time()
path_snip = snipp.PATH_USER_CMDS
body_snip = snipp.BODY_USER_CONF_CMDS % ('1', cli_str)
LOG.debug("NexusDriver CLI config for host %s: path: %s body: %s",
nexus_host, path_snip, body_snip)
self.nxapi_client.rest_post(path_snip, nexus_host, body_snip)
self.capture_and_print_timeshot(
starttime, "send_cliconf",
switch=nexus_host) | python | def _send_cli_conf_string(self, nexus_host, cli_str):
"""Sends CLI Config commands to Nexus switch using NXAPI."""
starttime = time.time()
path_snip = snipp.PATH_USER_CMDS
body_snip = snipp.BODY_USER_CONF_CMDS % ('1', cli_str)
LOG.debug("NexusDriver CLI config for host %s: path: %s body: %s",
nexus_host, path_snip, body_snip)
self.nxapi_client.rest_post(path_snip, nexus_host, body_snip)
self.capture_and_print_timeshot(
starttime, "send_cliconf",
switch=nexus_host) | [
"def",
"_send_cli_conf_string",
"(",
"self",
",",
"nexus_host",
",",
"cli_str",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_USER_CMDS",
"body_snip",
"=",
"snipp",
".",
"BODY_USER_CONF_CMDS",
"%",
"(",
"'1'... | Sends CLI Config commands to Nexus switch using NXAPI. | [
"Sends",
"CLI",
"Config",
"commands",
"to",
"Nexus",
"switch",
"using",
"NXAPI",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L818-L829 | train | 37,964 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.send_enable_vlan_on_trunk_int | def send_enable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native, add_mode=False):
"""Gathers and sends an interface trunk XML snippet."""
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, False, add_mode)
self.send_edit_string(nexus_host, path_snip, body_snip) | python | def send_enable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type,
interface, is_native, add_mode=False):
"""Gathers and sends an interface trunk XML snippet."""
path_snip, body_snip = self._get_vlan_body_on_trunk_int(
nexus_host, vlanid, intf_type, interface,
is_native, False, add_mode)
self.send_edit_string(nexus_host, path_snip, body_snip) | [
"def",
"send_enable_vlan_on_trunk_int",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
",",
"intf_type",
",",
"interface",
",",
"is_native",
",",
"add_mode",
"=",
"False",
")",
":",
"path_snip",
",",
"body_snip",
"=",
"self",
".",
"_get_vlan_body_on_trunk_int",
... | Gathers and sends an interface trunk XML snippet. | [
"Gathers",
"and",
"sends",
"an",
"interface",
"trunk",
"XML",
"snippet",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L831-L838 | train | 37,965 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.create_and_trunk_vlan | def create_and_trunk_vlan(self, nexus_host, vlan_id, intf_type,
nexus_port, vni, is_native):
"""Create VLAN and trunk it on the specified ports."""
starttime = time.time()
self.create_vlan(nexus_host, vlan_id, vni)
LOG.debug("NexusDriver created VLAN: %s", vlan_id)
if nexus_port:
self.send_enable_vlan_on_trunk_int(
nexus_host, vlan_id,
intf_type, nexus_port,
is_native)
self.capture_and_print_timeshot(
starttime, "create_all",
switch=nexus_host) | python | def create_and_trunk_vlan(self, nexus_host, vlan_id, intf_type,
nexus_port, vni, is_native):
"""Create VLAN and trunk it on the specified ports."""
starttime = time.time()
self.create_vlan(nexus_host, vlan_id, vni)
LOG.debug("NexusDriver created VLAN: %s", vlan_id)
if nexus_port:
self.send_enable_vlan_on_trunk_int(
nexus_host, vlan_id,
intf_type, nexus_port,
is_native)
self.capture_and_print_timeshot(
starttime, "create_all",
switch=nexus_host) | [
"def",
"create_and_trunk_vlan",
"(",
"self",
",",
"nexus_host",
",",
"vlan_id",
",",
"intf_type",
",",
"nexus_port",
",",
"vni",
",",
"is_native",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"create_vlan",
"(",
"nexus_host",
","... | Create VLAN and trunk it on the specified ports. | [
"Create",
"VLAN",
"and",
"trunk",
"it",
"on",
"the",
"specified",
"ports",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L840-L857 | train | 37,966 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.enable_vxlan_feature | def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf):
"""Enable VXLAN on the switch."""
# Configure the "feature" commands and NVE interface
# (without "member" subcommand configuration).
# The Nexus 9K will not allow the "interface nve" configuration
# until the "feature nv overlay" command is issued and installed.
# To get around the N9K failing on the "interface nve" command
# send the two XML snippets down separately.
starttime = time.time()
# Do CLI 'feature nv overlay'
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "enabled"))
# Do CLI 'feature vn-segment-vlan-based'
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
(snipp.BODY_VNSEG_STATE % "enabled"))
# Do CLI 'int nve1' to Create nve1
self.send_edit_string(
nexus_host,
(snipp.PATH_NVE_CREATE % nve_int_num),
(snipp.BODY_NVE_CREATE % nve_int_num))
# Do CLI 'no shut
# source-interface loopback %s'
# beneath int nve1
self.send_edit_string(
nexus_host,
(snipp.PATH_NVE_CREATE % nve_int_num),
(snipp.BODY_NVE_ADD_LOOPBACK % ("enabled", src_intf)))
self.capture_and_print_timeshot(
starttime, "enable_vxlan",
switch=nexus_host) | python | def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf):
"""Enable VXLAN on the switch."""
# Configure the "feature" commands and NVE interface
# (without "member" subcommand configuration).
# The Nexus 9K will not allow the "interface nve" configuration
# until the "feature nv overlay" command is issued and installed.
# To get around the N9K failing on the "interface nve" command
# send the two XML snippets down separately.
starttime = time.time()
# Do CLI 'feature nv overlay'
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "enabled"))
# Do CLI 'feature vn-segment-vlan-based'
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
(snipp.BODY_VNSEG_STATE % "enabled"))
# Do CLI 'int nve1' to Create nve1
self.send_edit_string(
nexus_host,
(snipp.PATH_NVE_CREATE % nve_int_num),
(snipp.BODY_NVE_CREATE % nve_int_num))
# Do CLI 'no shut
# source-interface loopback %s'
# beneath int nve1
self.send_edit_string(
nexus_host,
(snipp.PATH_NVE_CREATE % nve_int_num),
(snipp.BODY_NVE_ADD_LOOPBACK % ("enabled", src_intf)))
self.capture_and_print_timeshot(
starttime, "enable_vxlan",
switch=nexus_host) | [
"def",
"enable_vxlan_feature",
"(",
"self",
",",
"nexus_host",
",",
"nve_int_num",
",",
"src_intf",
")",
":",
"# Configure the \"feature\" commands and NVE interface",
"# (without \"member\" subcommand configuration).",
"# The Nexus 9K will not allow the \"interface nve\" configuration",... | Enable VXLAN on the switch. | [
"Enable",
"VXLAN",
"on",
"the",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L859-L894 | train | 37,967 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.disable_vxlan_feature | def disable_vxlan_feature(self, nexus_host):
"""Disable VXLAN on the switch."""
# Removing the "feature nv overlay" configuration also
# removes the "interface nve" configuration.
starttime = time.time()
# Do CLI 'no feature nv overlay'
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "disabled"))
# Do CLI 'no feature vn-segment-vlan-based'
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
(snipp.BODY_VNSEG_STATE % "disabled"))
self.capture_and_print_timeshot(
starttime, "disable_vxlan",
switch=nexus_host) | python | def disable_vxlan_feature(self, nexus_host):
"""Disable VXLAN on the switch."""
# Removing the "feature nv overlay" configuration also
# removes the "interface nve" configuration.
starttime = time.time()
# Do CLI 'no feature nv overlay'
self.send_edit_string(nexus_host, snipp.PATH_VXLAN_STATE,
(snipp.BODY_VXLAN_STATE % "disabled"))
# Do CLI 'no feature vn-segment-vlan-based'
self.send_edit_string(nexus_host, snipp.PATH_VNSEG_STATE,
(snipp.BODY_VNSEG_STATE % "disabled"))
self.capture_and_print_timeshot(
starttime, "disable_vxlan",
switch=nexus_host) | [
"def",
"disable_vxlan_feature",
"(",
"self",
",",
"nexus_host",
")",
":",
"# Removing the \"feature nv overlay\" configuration also",
"# removes the \"interface nve\" configuration.",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"# Do CLI 'no feature nv overlay'",
"self",
"... | Disable VXLAN on the switch. | [
"Disable",
"VXLAN",
"on",
"the",
"switch",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L896-L914 | train | 37,968 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.create_nve_member | def create_nve_member(self, nexus_host, nve_int_num, vni, mcast_group):
"""Add a member configuration to the NVE interface."""
# Do CLI [no] member vni %s mcast-group %s
# beneath int nve1
starttime = time.time()
path = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
body = snipp.BODY_VNI_UPDATE % (vni, vni, vni, mcast_group)
self.send_edit_string(nexus_host, path, body)
self.capture_and_print_timeshot(
starttime, "create_nve",
switch=nexus_host) | python | def create_nve_member(self, nexus_host, nve_int_num, vni, mcast_group):
"""Add a member configuration to the NVE interface."""
# Do CLI [no] member vni %s mcast-group %s
# beneath int nve1
starttime = time.time()
path = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
body = snipp.BODY_VNI_UPDATE % (vni, vni, vni, mcast_group)
self.send_edit_string(nexus_host, path, body)
self.capture_and_print_timeshot(
starttime, "create_nve",
switch=nexus_host) | [
"def",
"create_nve_member",
"(",
"self",
",",
"nexus_host",
",",
"nve_int_num",
",",
"vni",
",",
"mcast_group",
")",
":",
"# Do CLI [no] member vni %s mcast-group %s",
"# beneath int nve1",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path",
"=",
"snipp",
"."... | Add a member configuration to the NVE interface. | [
"Add",
"a",
"member",
"configuration",
"to",
"the",
"NVE",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L916-L930 | train | 37,969 |
openstack/networking-cisco | networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py | CiscoNexusRestapiDriver.delete_nve_member | def delete_nve_member(self, nexus_host, nve_int_num, vni):
"""Delete a member configuration on the NVE interface."""
starttime = time.time()
path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "delete_nve",
switch=nexus_host) | python | def delete_nve_member(self, nexus_host, nve_int_num, vni):
"""Delete a member configuration on the NVE interface."""
starttime = time.time()
path_snip = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "delete_nve",
switch=nexus_host) | [
"def",
"delete_nve_member",
"(",
"self",
",",
"nexus_host",
",",
"nve_int_num",
",",
"vni",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_VNI_UPDATE",
"%",
"(",
"nve_int_num",
",",
"vni",
")",
"self",
".... | Delete a member configuration on the NVE interface. | [
"Delete",
"a",
"member",
"configuration",
"on",
"the",
"NVE",
"interface",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/nexus/nexus_restapi_network_driver.py#L932-L942 | train | 37,970 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py | ASR1kRoutingDriver._get_vrf_name | def _get_vrf_name(self, ri):
"""
overloaded method for generating a vrf_name that supports
region_id
"""
router_id = ri.router_name()[:self.DEV_NAME_LEN]
is_multi_region_enabled = cfg.CONF.multi_region.enable_multi_region
if is_multi_region_enabled:
region_id = cfg.CONF.multi_region.region_id
vrf_name = "%s-%s" % (router_id, region_id)
else:
vrf_name = router_id
return vrf_name | python | def _get_vrf_name(self, ri):
"""
overloaded method for generating a vrf_name that supports
region_id
"""
router_id = ri.router_name()[:self.DEV_NAME_LEN]
is_multi_region_enabled = cfg.CONF.multi_region.enable_multi_region
if is_multi_region_enabled:
region_id = cfg.CONF.multi_region.region_id
vrf_name = "%s-%s" % (router_id, region_id)
else:
vrf_name = router_id
return vrf_name | [
"def",
"_get_vrf_name",
"(",
"self",
",",
"ri",
")",
":",
"router_id",
"=",
"ri",
".",
"router_name",
"(",
")",
"[",
":",
"self",
".",
"DEV_NAME_LEN",
"]",
"is_multi_region_enabled",
"=",
"cfg",
".",
"CONF",
".",
"multi_region",
".",
"enable_multi_region",
... | overloaded method for generating a vrf_name that supports
region_id | [
"overloaded",
"method",
"for",
"generating",
"a",
"vrf_name",
"that",
"supports",
"region_id"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py#L360-L373 | train | 37,971 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py | ASR1kRoutingDriver._get_item | def _get_item(list_containing_dicts_entries, attribute_value,
attribute_name='subnet_id'):
"""Searches a list of dicts and returns the first matching entry
The dict entry returned contains the attribute 'attribute_name' whose
value equals 'attribute_value'. If no such dict is found in the list
an empty dict is returned.
"""
for item in list_containing_dicts_entries:
if item.get(attribute_name) == attribute_value:
return item
return {} | python | def _get_item(list_containing_dicts_entries, attribute_value,
attribute_name='subnet_id'):
"""Searches a list of dicts and returns the first matching entry
The dict entry returned contains the attribute 'attribute_name' whose
value equals 'attribute_value'. If no such dict is found in the list
an empty dict is returned.
"""
for item in list_containing_dicts_entries:
if item.get(attribute_name) == attribute_value:
return item
return {} | [
"def",
"_get_item",
"(",
"list_containing_dicts_entries",
",",
"attribute_value",
",",
"attribute_name",
"=",
"'subnet_id'",
")",
":",
"for",
"item",
"in",
"list_containing_dicts_entries",
":",
"if",
"item",
".",
"get",
"(",
"attribute_name",
")",
"==",
"attribute_v... | Searches a list of dicts and returns the first matching entry
The dict entry returned contains the attribute 'attribute_name' whose
value equals 'attribute_value'. If no such dict is found in the list
an empty dict is returned. | [
"Searches",
"a",
"list",
"of",
"dicts",
"and",
"returns",
"the",
"first",
"matching",
"entry"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py#L425-L436 | train | 37,972 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py | ASR1kRoutingDriver._nat_rules_for_internet_access | def _nat_rules_for_internet_access(self, acl_no, network, netmask,
inner_itfc, outer_itfc, vrf_name):
"""Configure the NAT rules for an internal network.
Configuring NAT rules in the ASR1k is a three step process. First
create an ACL for the IP range of the internal network. Then enable
dynamic source NATing on the external interface of the ASR1k for this
ACL and VRF of the neutron router. Finally enable NAT on the interfaces
of the ASR1k where the internal and external networks are connected.
:param acl_no: ACL number of the internal network.
:param network: internal network
:param netmask: netmask of the internal network.
:param inner_itfc: (name of) interface connected to the internal
network
:param outer_itfc: (name of) interface connected to the external
network
:param vrf_name: VRF corresponding to this virtual router
:return: True if configuration succeeded
:raises: networking_cisco.plugins.cisco.cfg_agent.cfg_exceptions.
IOSXEConfigException
"""
acl_present = self._check_acl(acl_no, network, netmask)
if not acl_present:
conf_str = snippets.CREATE_ACL % (acl_no, network, netmask)
self._edit_running_config(conf_str, 'CREATE_ACL')
pool_name = "%s_nat_pool" % vrf_name
conf_str = asr1k_snippets.SET_DYN_SRC_TRL_POOL % (acl_no, pool_name,
vrf_name)
try:
self._edit_running_config(conf_str, 'SET_DYN_SRC_TRL_POOL')
except Exception as dyn_nat_e:
LOG.info("Ignore exception for SET_DYN_SRC_TRL_POOL: %s. "
"The config seems to be applied properly but netconf "
"seems to report an error.", dyn_nat_e)
conf_str = snippets.SET_NAT % (inner_itfc, 'inside')
self._edit_running_config(conf_str, 'SET_NAT')
conf_str = snippets.SET_NAT % (outer_itfc, 'outside')
self._edit_running_config(conf_str, 'SET_NAT') | python | def _nat_rules_for_internet_access(self, acl_no, network, netmask,
inner_itfc, outer_itfc, vrf_name):
"""Configure the NAT rules for an internal network.
Configuring NAT rules in the ASR1k is a three step process. First
create an ACL for the IP range of the internal network. Then enable
dynamic source NATing on the external interface of the ASR1k for this
ACL and VRF of the neutron router. Finally enable NAT on the interfaces
of the ASR1k where the internal and external networks are connected.
:param acl_no: ACL number of the internal network.
:param network: internal network
:param netmask: netmask of the internal network.
:param inner_itfc: (name of) interface connected to the internal
network
:param outer_itfc: (name of) interface connected to the external
network
:param vrf_name: VRF corresponding to this virtual router
:return: True if configuration succeeded
:raises: networking_cisco.plugins.cisco.cfg_agent.cfg_exceptions.
IOSXEConfigException
"""
acl_present = self._check_acl(acl_no, network, netmask)
if not acl_present:
conf_str = snippets.CREATE_ACL % (acl_no, network, netmask)
self._edit_running_config(conf_str, 'CREATE_ACL')
pool_name = "%s_nat_pool" % vrf_name
conf_str = asr1k_snippets.SET_DYN_SRC_TRL_POOL % (acl_no, pool_name,
vrf_name)
try:
self._edit_running_config(conf_str, 'SET_DYN_SRC_TRL_POOL')
except Exception as dyn_nat_e:
LOG.info("Ignore exception for SET_DYN_SRC_TRL_POOL: %s. "
"The config seems to be applied properly but netconf "
"seems to report an error.", dyn_nat_e)
conf_str = snippets.SET_NAT % (inner_itfc, 'inside')
self._edit_running_config(conf_str, 'SET_NAT')
conf_str = snippets.SET_NAT % (outer_itfc, 'outside')
self._edit_running_config(conf_str, 'SET_NAT') | [
"def",
"_nat_rules_for_internet_access",
"(",
"self",
",",
"acl_no",
",",
"network",
",",
"netmask",
",",
"inner_itfc",
",",
"outer_itfc",
",",
"vrf_name",
")",
":",
"acl_present",
"=",
"self",
".",
"_check_acl",
"(",
"acl_no",
",",
"network",
",",
"netmask",
... | Configure the NAT rules for an internal network.
Configuring NAT rules in the ASR1k is a three step process. First
create an ACL for the IP range of the internal network. Then enable
dynamic source NATing on the external interface of the ASR1k for this
ACL and VRF of the neutron router. Finally enable NAT on the interfaces
of the ASR1k where the internal and external networks are connected.
:param acl_no: ACL number of the internal network.
:param network: internal network
:param netmask: netmask of the internal network.
:param inner_itfc: (name of) interface connected to the internal
network
:param outer_itfc: (name of) interface connected to the external
network
:param vrf_name: VRF corresponding to this virtual router
:return: True if configuration succeeded
:raises: networking_cisco.plugins.cisco.cfg_agent.cfg_exceptions.
IOSXEConfigException | [
"Configure",
"the",
"NAT",
"rules",
"for",
"an",
"internal",
"network",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py#L851-L892 | train | 37,973 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py | ASR1kRoutingDriver._remove_internal_nw_nat_rules | def _remove_internal_nw_nat_rules(self, ri, ports, ext_port,
intf_deleted=False):
"""
Removes the NAT rules already configured when an internal network is
removed.
:param ri -- router-info object
:param ports -- list of affected ports where network nat rules
was affected
:param ext_port -- external facing port
:param intf_deleted-- If True, indicates that the subinterface was
deleted.
"""
acls = []
# first disable nat in all inner ports
for port in ports:
in_itfc_name = self._get_interface_name_from_hosting_port(port)
acls.append(self._generate_acl_num_from_port(port))
is_alone = len(port['change_details']['current_ports']) == 1
if not intf_deleted and is_alone is True:
self._remove_interface_nat(in_itfc_name, 'inside')
# There is a possibility that the dynamic NAT rule cannot be removed
# from the running config, if there is still traffic in the inner
# interface causing a rule to be present in the NAT translation
# table. For this we give 2 seconds for the 'inside NAT rule' to
# expire and then clear the NAT translation table manually. This can
# be costly and hence is not enabled here, pending further
# sinvestigation.
# LOG.debug("Sleep for 2 seconds before clearing NAT rules")
# time.sleep(2)
# clear the NAT translation table
# self._remove_dyn_nat_translations()
# remove dynamic nat rules and acls
vrf_name = self._get_vrf_name(ri)
ext_itfc_name = self._get_interface_name_from_hosting_port(ext_port)
for acl in acls:
self._remove_dyn_nat_rule(acl, ext_itfc_name, vrf_name) | python | def _remove_internal_nw_nat_rules(self, ri, ports, ext_port,
intf_deleted=False):
"""
Removes the NAT rules already configured when an internal network is
removed.
:param ri -- router-info object
:param ports -- list of affected ports where network nat rules
was affected
:param ext_port -- external facing port
:param intf_deleted-- If True, indicates that the subinterface was
deleted.
"""
acls = []
# first disable nat in all inner ports
for port in ports:
in_itfc_name = self._get_interface_name_from_hosting_port(port)
acls.append(self._generate_acl_num_from_port(port))
is_alone = len(port['change_details']['current_ports']) == 1
if not intf_deleted and is_alone is True:
self._remove_interface_nat(in_itfc_name, 'inside')
# There is a possibility that the dynamic NAT rule cannot be removed
# from the running config, if there is still traffic in the inner
# interface causing a rule to be present in the NAT translation
# table. For this we give 2 seconds for the 'inside NAT rule' to
# expire and then clear the NAT translation table manually. This can
# be costly and hence is not enabled here, pending further
# sinvestigation.
# LOG.debug("Sleep for 2 seconds before clearing NAT rules")
# time.sleep(2)
# clear the NAT translation table
# self._remove_dyn_nat_translations()
# remove dynamic nat rules and acls
vrf_name = self._get_vrf_name(ri)
ext_itfc_name = self._get_interface_name_from_hosting_port(ext_port)
for acl in acls:
self._remove_dyn_nat_rule(acl, ext_itfc_name, vrf_name) | [
"def",
"_remove_internal_nw_nat_rules",
"(",
"self",
",",
"ri",
",",
"ports",
",",
"ext_port",
",",
"intf_deleted",
"=",
"False",
")",
":",
"acls",
"=",
"[",
"]",
"# first disable nat in all inner ports",
"for",
"port",
"in",
"ports",
":",
"in_itfc_name",
"=",
... | Removes the NAT rules already configured when an internal network is
removed.
:param ri -- router-info object
:param ports -- list of affected ports where network nat rules
was affected
:param ext_port -- external facing port
:param intf_deleted-- If True, indicates that the subinterface was
deleted. | [
"Removes",
"the",
"NAT",
"rules",
"already",
"configured",
"when",
"an",
"internal",
"network",
"is",
"removed",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py#L894-L932 | train | 37,974 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py | ASR1kRoutingDriver._do_add_floating_ip_asr1k | def _do_add_floating_ip_asr1k(self, floating_ip, fixed_ip, vrf,
ex_gw_port):
"""
To implement a floating ip, an ip static nat is configured in the
underlying router ex_gw_port contains data to derive the vlan
associated with related subnet for the fixed ip. The vlan in turn
is applied to the redundancy parameter for setting the IP NAT.
"""
vlan = ex_gw_port['hosting_info']['segmentation_id']
hsrp_grp = ex_gw_port[ha.HA_INFO]['group']
LOG.debug("add floating_ip: %(fip)s, fixed_ip: %(fixed_ip)s, "
"vrf: %(vrf)s, ex_gw_port: %(port)s",
{'fip': floating_ip, 'fixed_ip': fixed_ip, 'vrf': vrf,
'port': ex_gw_port})
confstr = (asr1k_snippets.SET_STATIC_SRC_TRL_NO_VRF_MATCH %
(fixed_ip, floating_ip, vrf, hsrp_grp, vlan))
self._edit_running_config(confstr, 'SET_STATIC_SRC_TRL_NO_VRF_MATCH') | python | def _do_add_floating_ip_asr1k(self, floating_ip, fixed_ip, vrf,
ex_gw_port):
"""
To implement a floating ip, an ip static nat is configured in the
underlying router ex_gw_port contains data to derive the vlan
associated with related subnet for the fixed ip. The vlan in turn
is applied to the redundancy parameter for setting the IP NAT.
"""
vlan = ex_gw_port['hosting_info']['segmentation_id']
hsrp_grp = ex_gw_port[ha.HA_INFO]['group']
LOG.debug("add floating_ip: %(fip)s, fixed_ip: %(fixed_ip)s, "
"vrf: %(vrf)s, ex_gw_port: %(port)s",
{'fip': floating_ip, 'fixed_ip': fixed_ip, 'vrf': vrf,
'port': ex_gw_port})
confstr = (asr1k_snippets.SET_STATIC_SRC_TRL_NO_VRF_MATCH %
(fixed_ip, floating_ip, vrf, hsrp_grp, vlan))
self._edit_running_config(confstr, 'SET_STATIC_SRC_TRL_NO_VRF_MATCH') | [
"def",
"_do_add_floating_ip_asr1k",
"(",
"self",
",",
"floating_ip",
",",
"fixed_ip",
",",
"vrf",
",",
"ex_gw_port",
")",
":",
"vlan",
"=",
"ex_gw_port",
"[",
"'hosting_info'",
"]",
"[",
"'segmentation_id'",
"]",
"hsrp_grp",
"=",
"ex_gw_port",
"[",
"ha",
".",
... | To implement a floating ip, an ip static nat is configured in the
underlying router ex_gw_port contains data to derive the vlan
associated with related subnet for the fixed ip. The vlan in turn
is applied to the redundancy parameter for setting the IP NAT. | [
"To",
"implement",
"a",
"floating",
"ip",
"an",
"ip",
"static",
"nat",
"is",
"configured",
"in",
"the",
"underlying",
"router",
"ex_gw_port",
"contains",
"data",
"to",
"derive",
"the",
"vlan",
"associated",
"with",
"related",
"subnet",
"for",
"the",
"fixed",
... | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/asr1k/asr1k_routing_driver.py#L952-L970 | train | 37,975 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py | DeviceMgrCfgRpcCallback.report_non_responding_hosting_devices | def report_non_responding_hosting_devices(self, context, host,
hosting_device_ids):
"""Report that a hosting device is determined to be dead.
:param context: contains user information
:param host: originator of callback
:param hosting_device_ids: list of non-responding hosting devices
"""
# let the generic status update callback function handle this callback
self.update_hosting_device_status(context, host,
{const.HD_DEAD: hosting_device_ids}) | python | def report_non_responding_hosting_devices(self, context, host,
hosting_device_ids):
"""Report that a hosting device is determined to be dead.
:param context: contains user information
:param host: originator of callback
:param hosting_device_ids: list of non-responding hosting devices
"""
# let the generic status update callback function handle this callback
self.update_hosting_device_status(context, host,
{const.HD_DEAD: hosting_device_ids}) | [
"def",
"report_non_responding_hosting_devices",
"(",
"self",
",",
"context",
",",
"host",
",",
"hosting_device_ids",
")",
":",
"# let the generic status update callback function handle this callback",
"self",
".",
"update_hosting_device_status",
"(",
"context",
",",
"host",
"... | Report that a hosting device is determined to be dead.
:param context: contains user information
:param host: originator of callback
:param hosting_device_ids: list of non-responding hosting devices | [
"Report",
"that",
"a",
"hosting",
"device",
"is",
"determined",
"to",
"be",
"dead",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py#L29-L39 | train | 37,976 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py | DeviceMgrCfgRpcCallback.update_hosting_device_status | def update_hosting_device_status(self, context, host, status_info):
"""Report status changes for hosting devices.
:param context: contains user information
:param host: originator of callback
:param status_info: Dictionary with list of hosting device ids for
each type of hosting device status to be updated i.e.::
{
HD_ACTIVE: list_of_ids_of_active_hds,
HD_NOT_RESPONDING: list_of_ids_of_not_responding_hds,
HD_DEAD: list_of_ids_of_dead_hds,
...
}
"""
for status, hd_ids in six.iteritems(status_info):
# update hosting device entry in db to new status
hd_spec = {'hosting_device': {'status': status}}
for hd_id in hd_ids:
self._dmplugin.update_hosting_device(context, hd_id, hd_spec)
if status == const.HD_DEAD or status == const.HD_ERROR:
self._dmplugin.handle_non_responding_hosting_devices(
context, host, hd_ids) | python | def update_hosting_device_status(self, context, host, status_info):
"""Report status changes for hosting devices.
:param context: contains user information
:param host: originator of callback
:param status_info: Dictionary with list of hosting device ids for
each type of hosting device status to be updated i.e.::
{
HD_ACTIVE: list_of_ids_of_active_hds,
HD_NOT_RESPONDING: list_of_ids_of_not_responding_hds,
HD_DEAD: list_of_ids_of_dead_hds,
...
}
"""
for status, hd_ids in six.iteritems(status_info):
# update hosting device entry in db to new status
hd_spec = {'hosting_device': {'status': status}}
for hd_id in hd_ids:
self._dmplugin.update_hosting_device(context, hd_id, hd_spec)
if status == const.HD_DEAD or status == const.HD_ERROR:
self._dmplugin.handle_non_responding_hosting_devices(
context, host, hd_ids) | [
"def",
"update_hosting_device_status",
"(",
"self",
",",
"context",
",",
"host",
",",
"status_info",
")",
":",
"for",
"status",
",",
"hd_ids",
"in",
"six",
".",
"iteritems",
"(",
"status_info",
")",
":",
"# update hosting device entry in db to new status",
"hd_spec"... | Report status changes for hosting devices.
:param context: contains user information
:param host: originator of callback
:param status_info: Dictionary with list of hosting device ids for
each type of hosting device status to be updated i.e.::
{
HD_ACTIVE: list_of_ids_of_active_hds,
HD_NOT_RESPONDING: list_of_ids_of_not_responding_hds,
HD_DEAD: list_of_ids_of_dead_hds,
...
} | [
"Report",
"status",
"changes",
"for",
"hosting",
"devices",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py#L58-L80 | train | 37,977 |
openstack/networking-cisco | networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py | DeviceMgrCfgRpcCallback.get_hosting_devices_for_agent | def get_hosting_devices_for_agent(self, context, host):
"""Fetches routers that a Cisco cfg agent is managing.
This function is supposed to be called when the agent has started,
is ready to take on assignments and before any callbacks to fetch
logical resources are issued.
:param context: contains user information
:param host: originator of callback
:returns: dict of hosting devices managed by the cfg agent
"""
agent_ids = self._dmplugin.get_cfg_agents(context, active=None,
filters={'host': [host]})
if agent_ids:
return [self._dmplugin.get_device_info_for_agent(context, hd_db)
for hd_db in self._dmplugin.get_hosting_devices_db(
context, filters={'cfg_agent_id': [agent_ids[0].id]})]
return [] | python | def get_hosting_devices_for_agent(self, context, host):
"""Fetches routers that a Cisco cfg agent is managing.
This function is supposed to be called when the agent has started,
is ready to take on assignments and before any callbacks to fetch
logical resources are issued.
:param context: contains user information
:param host: originator of callback
:returns: dict of hosting devices managed by the cfg agent
"""
agent_ids = self._dmplugin.get_cfg_agents(context, active=None,
filters={'host': [host]})
if agent_ids:
return [self._dmplugin.get_device_info_for_agent(context, hd_db)
for hd_db in self._dmplugin.get_hosting_devices_db(
context, filters={'cfg_agent_id': [agent_ids[0].id]})]
return [] | [
"def",
"get_hosting_devices_for_agent",
"(",
"self",
",",
"context",
",",
"host",
")",
":",
"agent_ids",
"=",
"self",
".",
"_dmplugin",
".",
"get_cfg_agents",
"(",
"context",
",",
"active",
"=",
"None",
",",
"filters",
"=",
"{",
"'host'",
":",
"[",
"host",... | Fetches routers that a Cisco cfg agent is managing.
This function is supposed to be called when the agent has started,
is ready to take on assignments and before any callbacks to fetch
logical resources are issued.
:param context: contains user information
:param host: originator of callback
:returns: dict of hosting devices managed by the cfg agent | [
"Fetches",
"routers",
"that",
"a",
"Cisco",
"cfg",
"agent",
"is",
"managing",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/device_manager/rpc/devices_cfgagent_rpc_cb.py#L87-L104 | train | 37,978 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/scheduler/l3_routertype_aware_schedulers_db.py | L3RouterTypeAwareSchedulerDbMixin.remove_router_from_hosting_device | def remove_router_from_hosting_device(self, context, hosting_device_id,
router_id):
"""Remove the router from hosting device.
After removal, the router will be non-hosted until there is update
which leads to re-schedule or be added to another hosting device
manually.
"""
e_context = context.elevated()
r_hd_binding_db = self._get_router_binding_info(e_context, router_id)
if r_hd_binding_db.hosting_device_id != hosting_device_id:
raise routertypeawarescheduler.RouterNotHostedByHostingDevice(
router_id=router_id, hosting_device_id=hosting_device_id)
router = self.get_router(context, router_id)
self.add_type_and_hosting_device_info(
e_context, router, r_hd_binding_db, schedule=False)
# conditionally remove router from backlog ensure it does not get
# scheduled automatically
self.remove_router_from_backlog(id)
l3_cfg_notifier = self.agent_notifiers.get(AGENT_TYPE_L3_CFG)
if l3_cfg_notifier:
l3_cfg_notifier.router_removed_from_hosting_device(context, router)
LOG.debug("Unscheduling router %s", r_hd_binding_db.router_id)
self.unschedule_router_from_hosting_device(context, r_hd_binding_db)
# now unbind the router from the hosting device
with e_context.session.begin(subtransactions=True):
r_hd_binding_db.hosting_device_id = None
e_context.session.add(r_hd_binding_db) | python | def remove_router_from_hosting_device(self, context, hosting_device_id,
router_id):
"""Remove the router from hosting device.
After removal, the router will be non-hosted until there is update
which leads to re-schedule or be added to another hosting device
manually.
"""
e_context = context.elevated()
r_hd_binding_db = self._get_router_binding_info(e_context, router_id)
if r_hd_binding_db.hosting_device_id != hosting_device_id:
raise routertypeawarescheduler.RouterNotHostedByHostingDevice(
router_id=router_id, hosting_device_id=hosting_device_id)
router = self.get_router(context, router_id)
self.add_type_and_hosting_device_info(
e_context, router, r_hd_binding_db, schedule=False)
# conditionally remove router from backlog ensure it does not get
# scheduled automatically
self.remove_router_from_backlog(id)
l3_cfg_notifier = self.agent_notifiers.get(AGENT_TYPE_L3_CFG)
if l3_cfg_notifier:
l3_cfg_notifier.router_removed_from_hosting_device(context, router)
LOG.debug("Unscheduling router %s", r_hd_binding_db.router_id)
self.unschedule_router_from_hosting_device(context, r_hd_binding_db)
# now unbind the router from the hosting device
with e_context.session.begin(subtransactions=True):
r_hd_binding_db.hosting_device_id = None
e_context.session.add(r_hd_binding_db) | [
"def",
"remove_router_from_hosting_device",
"(",
"self",
",",
"context",
",",
"hosting_device_id",
",",
"router_id",
")",
":",
"e_context",
"=",
"context",
".",
"elevated",
"(",
")",
"r_hd_binding_db",
"=",
"self",
".",
"_get_router_binding_info",
"(",
"e_context",
... | Remove the router from hosting device.
After removal, the router will be non-hosted until there is update
which leads to re-schedule or be added to another hosting device
manually. | [
"Remove",
"the",
"router",
"from",
"hosting",
"device",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/scheduler/l3_routertype_aware_schedulers_db.py#L115-L142 | train | 37,979 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/scheduler/l3_routertype_aware_schedulers_db.py | L3RouterTypeAwareSchedulerDbMixin.get_number_of_agents_for_scheduling | def get_number_of_agents_for_scheduling(self, context):
"""Return number of agents on which the router will be scheduled."""
num_agents = len(self.get_l3_agents(context, active=True,
filters={'agent_modes': [bc.constants.L3_AGENT_MODE_LEGACY,
bc.constants.L3_AGENT_MODE_DVR_SNAT]}))
max_agents = cfg.CONF.max_l3_agents_per_router
if max_agents:
if max_agents > num_agents:
LOG.info("Number of active agents lower than "
"max_l3_agents_per_router. L3 agents "
"available: %s", num_agents)
else:
num_agents = max_agents
return num_agents | python | def get_number_of_agents_for_scheduling(self, context):
"""Return number of agents on which the router will be scheduled."""
num_agents = len(self.get_l3_agents(context, active=True,
filters={'agent_modes': [bc.constants.L3_AGENT_MODE_LEGACY,
bc.constants.L3_AGENT_MODE_DVR_SNAT]}))
max_agents = cfg.CONF.max_l3_agents_per_router
if max_agents:
if max_agents > num_agents:
LOG.info("Number of active agents lower than "
"max_l3_agents_per_router. L3 agents "
"available: %s", num_agents)
else:
num_agents = max_agents
return num_agents | [
"def",
"get_number_of_agents_for_scheduling",
"(",
"self",
",",
"context",
")",
":",
"num_agents",
"=",
"len",
"(",
"self",
".",
"get_l3_agents",
"(",
"context",
",",
"active",
"=",
"True",
",",
"filters",
"=",
"{",
"'agent_modes'",
":",
"[",
"bc",
".",
"c... | Return number of agents on which the router will be scheduled. | [
"Return",
"number",
"of",
"agents",
"on",
"which",
"the",
"router",
"will",
"be",
"scheduled",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/scheduler/l3_routertype_aware_schedulers_db.py#L276-L291 | train | 37,980 |
openstack/networking-cisco | networking_cisco/plugins/cisco/db/l3/l3_router_appliance_db.py | _notify_subnet_create | def _notify_subnet_create(resource, event, trigger, **kwargs):
"""Called when a new subnet is created in the external network"""
context = kwargs['context']
subnet = kwargs['subnet']
l3plugin = bc.get_plugin(L3_ROUTER_NAT)
for router in l3plugin.get_routers(context):
if (router['external_gateway_info'] and
(router['external_gateway_info']['network_id'] ==
subnet['network_id'])):
router_data = {'router': router}
l3plugin.update_router(context, router['id'], router_data) | python | def _notify_subnet_create(resource, event, trigger, **kwargs):
"""Called when a new subnet is created in the external network"""
context = kwargs['context']
subnet = kwargs['subnet']
l3plugin = bc.get_plugin(L3_ROUTER_NAT)
for router in l3plugin.get_routers(context):
if (router['external_gateway_info'] and
(router['external_gateway_info']['network_id'] ==
subnet['network_id'])):
router_data = {'router': router}
l3plugin.update_router(context, router['id'], router_data) | [
"def",
"_notify_subnet_create",
"(",
"resource",
",",
"event",
",",
"trigger",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"kwargs",
"[",
"'context'",
"]",
"subnet",
"=",
"kwargs",
"[",
"'subnet'",
"]",
"l3plugin",
"=",
"bc",
".",
"get_plugin",
"(... | Called when a new subnet is created in the external network | [
"Called",
"when",
"a",
"new",
"subnet",
"is",
"created",
"in",
"the",
"external",
"network"
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/db/l3/l3_router_appliance_db.py#L1601-L1611 | train | 37,981 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.is_port_profile_created | def is_port_profile_created(self, vlan_id, device_id):
"""Indicates if port profile has been created on UCS Manager."""
entry = self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, device_id=device_id).first()
return entry and entry.created_on_ucs | python | def is_port_profile_created(self, vlan_id, device_id):
"""Indicates if port profile has been created on UCS Manager."""
entry = self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, device_id=device_id).first()
return entry and entry.created_on_ucs | [
"def",
"is_port_profile_created",
"(",
"self",
",",
"vlan_id",
",",
"device_id",
")",
":",
"entry",
"=",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"PortProfile",
")",
".",
"filter_by",
"(",
"vlan_id",
"=",
"vlan_id",
",",
"device_id",
"... | Indicates if port profile has been created on UCS Manager. | [
"Indicates",
"if",
"port",
"profile",
"has",
"been",
"created",
"on",
"UCS",
"Manager",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L26-L30 | train | 37,982 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.get_port_profile_for_vlan | def get_port_profile_for_vlan(self, vlan_id, device_id):
"""Returns Vlan id associated with the port profile."""
entry = self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, device_id=device_id).first()
return entry.profile_id if entry else None | python | def get_port_profile_for_vlan(self, vlan_id, device_id):
"""Returns Vlan id associated with the port profile."""
entry = self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, device_id=device_id).first()
return entry.profile_id if entry else None | [
"def",
"get_port_profile_for_vlan",
"(",
"self",
",",
"vlan_id",
",",
"device_id",
")",
":",
"entry",
"=",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"PortProfile",
")",
".",
"filter_by",
"(",
"vlan_id",
"=",
"vlan_id",
",",
"device_id",
... | Returns Vlan id associated with the port profile. | [
"Returns",
"Vlan",
"id",
"associated",
"with",
"the",
"port",
"profile",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L32-L36 | train | 37,983 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.add_port_profile | def add_port_profile(self, profile_name, vlan_id, device_id):
"""Adds a port profile and its vlan_id to the table."""
if not self.get_port_profile_for_vlan(vlan_id, device_id):
port_profile = ucsm_model.PortProfile(profile_id=profile_name,
vlan_id=vlan_id,
device_id=device_id,
created_on_ucs=False)
with self.session.begin(subtransactions=True):
self.session.add(port_profile)
return port_profile | python | def add_port_profile(self, profile_name, vlan_id, device_id):
"""Adds a port profile and its vlan_id to the table."""
if not self.get_port_profile_for_vlan(vlan_id, device_id):
port_profile = ucsm_model.PortProfile(profile_id=profile_name,
vlan_id=vlan_id,
device_id=device_id,
created_on_ucs=False)
with self.session.begin(subtransactions=True):
self.session.add(port_profile)
return port_profile | [
"def",
"add_port_profile",
"(",
"self",
",",
"profile_name",
",",
"vlan_id",
",",
"device_id",
")",
":",
"if",
"not",
"self",
".",
"get_port_profile_for_vlan",
"(",
"vlan_id",
",",
"device_id",
")",
":",
"port_profile",
"=",
"ucsm_model",
".",
"PortProfile",
"... | Adds a port profile and its vlan_id to the table. | [
"Adds",
"a",
"port",
"profile",
"and",
"its",
"vlan_id",
"to",
"the",
"table",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L38-L47 | train | 37,984 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.set_port_profile_created | def set_port_profile_created(self, vlan_id, profile_name, device_id):
"""Sets created_on_ucs flag to True."""
with self.session.begin(subtransactions=True):
port_profile = self.session.query(
ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, profile_id=profile_name,
device_id=device_id).first()
if port_profile:
port_profile.created_on_ucs = True
self.session.merge(port_profile)
else:
new_profile = ucsm_model.PortProfile(profile_id=profile_name,
vlan_id=vlan_id,
device_id=device_id,
created_on_ucs=True)
self.session.add(new_profile) | python | def set_port_profile_created(self, vlan_id, profile_name, device_id):
"""Sets created_on_ucs flag to True."""
with self.session.begin(subtransactions=True):
port_profile = self.session.query(
ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id, profile_id=profile_name,
device_id=device_id).first()
if port_profile:
port_profile.created_on_ucs = True
self.session.merge(port_profile)
else:
new_profile = ucsm_model.PortProfile(profile_id=profile_name,
vlan_id=vlan_id,
device_id=device_id,
created_on_ucs=True)
self.session.add(new_profile) | [
"def",
"set_port_profile_created",
"(",
"self",
",",
"vlan_id",
",",
"profile_name",
",",
"device_id",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"port_profile",
"=",
"self",
".",
"session",
".",
... | Sets created_on_ucs flag to True. | [
"Sets",
"created_on_ucs",
"flag",
"to",
"True",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L49-L64 | train | 37,985 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.delete_vlan_entry | def delete_vlan_entry(self, vlan_id):
"""Deletes entry for a vlan_id if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | python | def delete_vlan_entry(self, vlan_id):
"""Deletes entry for a vlan_id if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.PortProfile).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | [
"def",
"delete_vlan_entry",
"(",
"self",
",",
"vlan_id",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"PortProfile",
")",
... | Deletes entry for a vlan_id if it exists. | [
"Deletes",
"entry",
"for",
"a",
"vlan_id",
"if",
"it",
"exists",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L66-L73 | train | 37,986 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.set_sp_template_updated | def set_sp_template_updated(self, vlan_id, sp_template, device_id):
"""Sets update_on_ucs flag to True."""
entry = self.get_sp_template_vlan_entry(vlan_id,
sp_template,
device_id)
if entry:
entry.updated_on_ucs = True
self.session.merge(entry)
return entry
else:
return False | python | def set_sp_template_updated(self, vlan_id, sp_template, device_id):
"""Sets update_on_ucs flag to True."""
entry = self.get_sp_template_vlan_entry(vlan_id,
sp_template,
device_id)
if entry:
entry.updated_on_ucs = True
self.session.merge(entry)
return entry
else:
return False | [
"def",
"set_sp_template_updated",
"(",
"self",
",",
"vlan_id",
",",
"sp_template",
",",
"device_id",
")",
":",
"entry",
"=",
"self",
".",
"get_sp_template_vlan_entry",
"(",
"vlan_id",
",",
"sp_template",
",",
"device_id",
")",
"if",
"entry",
":",
"entry",
".",... | Sets update_on_ucs flag to True. | [
"Sets",
"update_on_ucs",
"flag",
"to",
"True",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L91-L101 | train | 37,987 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.delete_sp_template_for_vlan | def delete_sp_template_for_vlan(self, vlan_id):
"""Deletes SP Template for a vlan_id if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(
ucsm_model.ServiceProfileTemplate).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | python | def delete_sp_template_for_vlan(self, vlan_id):
"""Deletes SP Template for a vlan_id if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(
ucsm_model.ServiceProfileTemplate).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | [
"def",
"delete_sp_template_for_vlan",
"(",
"self",
",",
"vlan_id",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"ServiceProf... | Deletes SP Template for a vlan_id if it exists. | [
"Deletes",
"SP",
"Template",
"for",
"a",
"vlan_id",
"if",
"it",
"exists",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L103-L111 | train | 37,988 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.set_vnic_template_updated | def set_vnic_template_updated(self, vlan_id, ucsm_ip, vnic_template,
physnet):
"""Sets update_on_ucs flag to True for a Vnic Template entry."""
with self.session.begin(subtransactions=True):
entry = self.get_vnic_template_vlan_entry(vlan_id, vnic_template,
ucsm_ip, physnet)
if entry:
entry.updated_on_ucs = True
self.session.merge(entry)
return entry | python | def set_vnic_template_updated(self, vlan_id, ucsm_ip, vnic_template,
physnet):
"""Sets update_on_ucs flag to True for a Vnic Template entry."""
with self.session.begin(subtransactions=True):
entry = self.get_vnic_template_vlan_entry(vlan_id, vnic_template,
ucsm_ip, physnet)
if entry:
entry.updated_on_ucs = True
self.session.merge(entry)
return entry | [
"def",
"set_vnic_template_updated",
"(",
"self",
",",
"vlan_id",
",",
"ucsm_ip",
",",
"vnic_template",
",",
"physnet",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"entry",
"=",
"self",
".",
"get_vn... | Sets update_on_ucs flag to True for a Vnic Template entry. | [
"Sets",
"update_on_ucs",
"flag",
"to",
"True",
"for",
"a",
"Vnic",
"Template",
"entry",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L135-L144 | train | 37,989 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.delete_vnic_template_for_vlan | def delete_vnic_template_for_vlan(self, vlan_id):
"""Deletes VNIC Template for a vlan_id and physnet if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.VnicTemplate).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | python | def delete_vnic_template_for_vlan(self, vlan_id):
"""Deletes VNIC Template for a vlan_id and physnet if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(ucsm_model.VnicTemplate).filter_by(
vlan_id=vlan_id).delete()
except orm.exc.NoResultFound:
return | [
"def",
"delete_vnic_template_for_vlan",
"(",
"self",
",",
"vlan_id",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"VnicTempl... | Deletes VNIC Template for a vlan_id and physnet if it exists. | [
"Deletes",
"VNIC",
"Template",
"for",
"a",
"vlan_id",
"and",
"physnet",
"if",
"it",
"exists",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L146-L153 | train | 37,990 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.has_port_profile_to_delete | def has_port_profile_to_delete(self, profile_name, device_id):
"""Returns True if port profile delete table containes PP."""
count = self.session.query(ucsm_model.PortProfileDelete).filter_by(
profile_id=profile_name, device_id=device_id).count()
return count != 0 | python | def has_port_profile_to_delete(self, profile_name, device_id):
"""Returns True if port profile delete table containes PP."""
count = self.session.query(ucsm_model.PortProfileDelete).filter_by(
profile_id=profile_name, device_id=device_id).count()
return count != 0 | [
"def",
"has_port_profile_to_delete",
"(",
"self",
",",
"profile_name",
",",
"device_id",
")",
":",
"count",
"=",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
"PortProfileDelete",
")",
".",
"filter_by",
"(",
"profile_id",
"=",
"profile_name",
"... | Returns True if port profile delete table containes PP. | [
"Returns",
"True",
"if",
"port",
"profile",
"delete",
"table",
"containes",
"PP",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L155-L159 | train | 37,991 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.add_port_profile_to_delete_table | def add_port_profile_to_delete_table(self, profile_name, device_id):
"""Adds a port profile to the delete table."""
if not self.has_port_profile_to_delete(profile_name, device_id):
port_profile = ucsm_model.PortProfileDelete(
profile_id=profile_name, device_id=device_id)
with self.session.begin(subtransactions=True):
self.session.add(port_profile)
return port_profile | python | def add_port_profile_to_delete_table(self, profile_name, device_id):
"""Adds a port profile to the delete table."""
if not self.has_port_profile_to_delete(profile_name, device_id):
port_profile = ucsm_model.PortProfileDelete(
profile_id=profile_name, device_id=device_id)
with self.session.begin(subtransactions=True):
self.session.add(port_profile)
return port_profile | [
"def",
"add_port_profile_to_delete_table",
"(",
"self",
",",
"profile_name",
",",
"device_id",
")",
":",
"if",
"not",
"self",
".",
"has_port_profile_to_delete",
"(",
"profile_name",
",",
"device_id",
")",
":",
"port_profile",
"=",
"ucsm_model",
".",
"PortProfileDele... | Adds a port profile to the delete table. | [
"Adds",
"a",
"port",
"profile",
"to",
"the",
"delete",
"table",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L161-L168 | train | 37,992 |
openstack/networking-cisco | networking_cisco/ml2_drivers/ucsm/ucsm_db.py | UcsmDbModel.remove_port_profile_to_delete | def remove_port_profile_to_delete(self, profile_name, device_id):
"""Removes port profile to be deleted from table."""
with self.session.begin(subtransactions=True):
self.session.query(ucsm_model.PortProfileDelete).filter_by(
profile_id=profile_name, device_id=device_id).delete() | python | def remove_port_profile_to_delete(self, profile_name, device_id):
"""Removes port profile to be deleted from table."""
with self.session.begin(subtransactions=True):
self.session.query(ucsm_model.PortProfileDelete).filter_by(
profile_id=profile_name, device_id=device_id).delete() | [
"def",
"remove_port_profile_to_delete",
"(",
"self",
",",
"profile_name",
",",
"device_id",
")",
":",
"with",
"self",
".",
"session",
".",
"begin",
"(",
"subtransactions",
"=",
"True",
")",
":",
"self",
".",
"session",
".",
"query",
"(",
"ucsm_model",
".",
... | Removes port profile to be deleted from table. | [
"Removes",
"port",
"profile",
"to",
"be",
"deleted",
"from",
"table",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/ml2_drivers/ucsm/ucsm_db.py#L173-L177 | train | 37,993 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cpnr/cpnr_dhcp_relay_agent.py | DhcpPacket.parse | def parse(cls, buf):
"""Parse DHCP Packet.
1. To get client IP Address(ciaddr).
2. To get relaying gateway IP Address(giaddr).
3. To get DHCP Relay Agent Information Option Suboption
such as Link Selection, VSS, Server Identifier override.
"""
pkt = DhcpPacket()
(pkt.ciaddr,) = cls.struct('4s').unpack_from(buf, 12)
(pkt.giaddr,) = cls.struct('4s').unpack_from(buf, 24)
cls.struct('4s').pack_into(buf, 24, b'')
pos = 240
while pos < len(buf):
(opttag,) = cls.struct('B').unpack_from(buf, pos)
if opttag == 0:
pos += 1
continue
if opttag == END:
pkt.end = pos
break
(optlen,) = cls.struct('B').unpack_from(buf, pos + 1)
startpos = pos
pos += 2
if opttag != RELAY_AGENT_INFO:
pos += optlen
continue
optend = pos + optlen
while pos < optend:
(subopttag, suboptlen) = cls.struct('BB').unpack_from(buf, pos)
fmt = '%is' % (suboptlen,)
(val,) = cls.struct(fmt).unpack_from(buf, pos + 2)
pkt.relay_options[subopttag] = val
pos += suboptlen + 2
cls.struct('%is' % (optlen + 2)).pack_into(buf, startpos, b'')
pkt.buf = buf
return pkt | python | def parse(cls, buf):
"""Parse DHCP Packet.
1. To get client IP Address(ciaddr).
2. To get relaying gateway IP Address(giaddr).
3. To get DHCP Relay Agent Information Option Suboption
such as Link Selection, VSS, Server Identifier override.
"""
pkt = DhcpPacket()
(pkt.ciaddr,) = cls.struct('4s').unpack_from(buf, 12)
(pkt.giaddr,) = cls.struct('4s').unpack_from(buf, 24)
cls.struct('4s').pack_into(buf, 24, b'')
pos = 240
while pos < len(buf):
(opttag,) = cls.struct('B').unpack_from(buf, pos)
if opttag == 0:
pos += 1
continue
if opttag == END:
pkt.end = pos
break
(optlen,) = cls.struct('B').unpack_from(buf, pos + 1)
startpos = pos
pos += 2
if opttag != RELAY_AGENT_INFO:
pos += optlen
continue
optend = pos + optlen
while pos < optend:
(subopttag, suboptlen) = cls.struct('BB').unpack_from(buf, pos)
fmt = '%is' % (suboptlen,)
(val,) = cls.struct(fmt).unpack_from(buf, pos + 2)
pkt.relay_options[subopttag] = val
pos += suboptlen + 2
cls.struct('%is' % (optlen + 2)).pack_into(buf, startpos, b'')
pkt.buf = buf
return pkt | [
"def",
"parse",
"(",
"cls",
",",
"buf",
")",
":",
"pkt",
"=",
"DhcpPacket",
"(",
")",
"(",
"pkt",
".",
"ciaddr",
",",
")",
"=",
"cls",
".",
"struct",
"(",
"'4s'",
")",
".",
"unpack_from",
"(",
"buf",
",",
"12",
")",
"(",
"pkt",
".",
"giaddr",
... | Parse DHCP Packet.
1. To get client IP Address(ciaddr).
2. To get relaying gateway IP Address(giaddr).
3. To get DHCP Relay Agent Information Option Suboption
such as Link Selection, VSS, Server Identifier override. | [
"Parse",
"DHCP",
"Packet",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cpnr/cpnr_dhcp_relay_agent.py#L311-L348 | train | 37,994 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | CiscoDeviceManagementApi.register_for_duty | def register_for_duty(self, context):
"""Report that a config agent is ready for duty."""
cctxt = self.client.prepare()
return cctxt.call(context, 'register_for_duty', host=self.host) | python | def register_for_duty(self, context):
"""Report that a config agent is ready for duty."""
cctxt = self.client.prepare()
return cctxt.call(context, 'register_for_duty', host=self.host) | [
"def",
"register_for_duty",
"(",
"self",
",",
"context",
")",
":",
"cctxt",
"=",
"self",
".",
"client",
".",
"prepare",
"(",
")",
"return",
"cctxt",
".",
"call",
"(",
"context",
",",
"'register_for_duty'",
",",
"host",
"=",
"self",
".",
"host",
")"
] | Report that a config agent is ready for duty. | [
"Report",
"that",
"a",
"config",
"agent",
"is",
"ready",
"for",
"duty",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L82-L85 | train | 37,995 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | CiscoDeviceManagementApi.get_hosting_devices_for_agent | def get_hosting_devices_for_agent(self, context):
"""Get a list of hosting devices assigned to this agent."""
cctxt = self.client.prepare()
return cctxt.call(context,
'get_hosting_devices_for_agent',
host=self.host) | python | def get_hosting_devices_for_agent(self, context):
"""Get a list of hosting devices assigned to this agent."""
cctxt = self.client.prepare()
return cctxt.call(context,
'get_hosting_devices_for_agent',
host=self.host) | [
"def",
"get_hosting_devices_for_agent",
"(",
"self",
",",
"context",
")",
":",
"cctxt",
"=",
"self",
".",
"client",
".",
"prepare",
"(",
")",
"return",
"cctxt",
".",
"call",
"(",
"context",
",",
"'get_hosting_devices_for_agent'",
",",
"host",
"=",
"self",
".... | Get a list of hosting devices assigned to this agent. | [
"Get",
"a",
"list",
"of",
"hosting",
"devices",
"assigned",
"to",
"this",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L87-L92 | train | 37,996 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | CiscoCfgAgent.process_services | def process_services(self, device_ids=None, removed_devices_info=None):
"""Process services managed by this config agent.
This method is invoked by any of three scenarios.
1. Invoked by a periodic task running every `RPC_LOOP_INTERVAL`
seconds. This is the most common scenario.
In this mode, the method is called without any arguments.
2. Called by the `_process_backlogged_hosting_devices()` as part of
the backlog processing task. In this mode, a list of device_ids
are passed as arguments. These are the list of backlogged
hosting devices that are now reachable and we want to sync services
on them.
3. Called by the `hosting_devices_removed()` method. This is when
the config agent has received a notification from the plugin that
some hosting devices are going to be removed. The payload contains
the details of the hosting devices and the associated neutron
resources on them which should be processed and removed.
To avoid race conditions with these scenarios, this function is
protected by a lock.
This method goes on to invoke `process_service()` on the
different service helpers.
:param device_ids: List of devices that are now available and needs to
be processed
:param removed_devices_info: Info about the hosting devices which are
going to be removed and details of the resources hosted on them.
Expected Format::
{
'hosting_data': {'hd_id1': {'routers': [id1, id2, ...]},
'hd_id2': {'routers': [id3, id4, ...]}, ...},
'deconfigure': True/False
}
:returns: None
"""
LOG.debug("Processing services started")
# Now we process only routing service, additional services will be
# added in future
if self.routing_service_helper:
self.routing_service_helper.process_service(device_ids,
removed_devices_info)
else:
LOG.warning("No routing service helper loaded")
LOG.debug("Processing services completed") | python | def process_services(self, device_ids=None, removed_devices_info=None):
"""Process services managed by this config agent.
This method is invoked by any of three scenarios.
1. Invoked by a periodic task running every `RPC_LOOP_INTERVAL`
seconds. This is the most common scenario.
In this mode, the method is called without any arguments.
2. Called by the `_process_backlogged_hosting_devices()` as part of
the backlog processing task. In this mode, a list of device_ids
are passed as arguments. These are the list of backlogged
hosting devices that are now reachable and we want to sync services
on them.
3. Called by the `hosting_devices_removed()` method. This is when
the config agent has received a notification from the plugin that
some hosting devices are going to be removed. The payload contains
the details of the hosting devices and the associated neutron
resources on them which should be processed and removed.
To avoid race conditions with these scenarios, this function is
protected by a lock.
This method goes on to invoke `process_service()` on the
different service helpers.
:param device_ids: List of devices that are now available and needs to
be processed
:param removed_devices_info: Info about the hosting devices which are
going to be removed and details of the resources hosted on them.
Expected Format::
{
'hosting_data': {'hd_id1': {'routers': [id1, id2, ...]},
'hd_id2': {'routers': [id3, id4, ...]}, ...},
'deconfigure': True/False
}
:returns: None
"""
LOG.debug("Processing services started")
# Now we process only routing service, additional services will be
# added in future
if self.routing_service_helper:
self.routing_service_helper.process_service(device_ids,
removed_devices_info)
else:
LOG.warning("No routing service helper loaded")
LOG.debug("Processing services completed") | [
"def",
"process_services",
"(",
"self",
",",
"device_ids",
"=",
"None",
",",
"removed_devices_info",
"=",
"None",
")",
":",
"LOG",
".",
"debug",
"(",
"\"Processing services started\"",
")",
"# Now we process only routing service, additional services will be",
"# added in fu... | Process services managed by this config agent.
This method is invoked by any of three scenarios.
1. Invoked by a periodic task running every `RPC_LOOP_INTERVAL`
seconds. This is the most common scenario.
In this mode, the method is called without any arguments.
2. Called by the `_process_backlogged_hosting_devices()` as part of
the backlog processing task. In this mode, a list of device_ids
are passed as arguments. These are the list of backlogged
hosting devices that are now reachable and we want to sync services
on them.
3. Called by the `hosting_devices_removed()` method. This is when
the config agent has received a notification from the plugin that
some hosting devices are going to be removed. The payload contains
the details of the hosting devices and the associated neutron
resources on them which should be processed and removed.
To avoid race conditions with these scenarios, this function is
protected by a lock.
This method goes on to invoke `process_service()` on the
different service helpers.
:param device_ids: List of devices that are now available and needs to
be processed
:param removed_devices_info: Info about the hosting devices which are
going to be removed and details of the resources hosted on them.
Expected Format::
{
'hosting_data': {'hd_id1': {'routers': [id1, id2, ...]},
'hd_id2': {'routers': [id3, id4, ...]}, ...},
'deconfigure': True/False
}
:returns: None | [
"Process",
"services",
"managed",
"by",
"this",
"config",
"agent",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L217-L267 | train | 37,997 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | CiscoCfgAgent._process_backlogged_hosting_devices | def _process_backlogged_hosting_devices(self, context):
"""Process currently backlogged devices.
Go through the currently backlogged devices and process them.
For devices which are now reachable (compared to last time), we call
`process_services()` passing the now reachable device's id.
For devices which have passed the `hosting_device_dead_timeout` and
hence presumed dead, execute a RPC to the plugin informing that.
heartbeat revision
res['reachable'] - hosting device went from Unknown to Active state
process_services(...)
res['revived'] - hosting device went from Dead to Active
inform device manager that the hosting
device is now responsive
res['dead'] - hosting device went from Unknown to Dead
inform device manager that the hosting
device is non-responding
As additional note for the revived case:
Although the plugin was notified, there may be some lag
before the plugin actually can reschedule it's backlogged routers.
If process_services(device_ids...) isn't successful initially,
subsequent device syncs will be attempted until
MAX_DEVICE_SYNC_ATTEMPTS occurs. Main process_service task
will resume if sync_devices is populated.
:param context: RPC context
:return: None
"""
driver_mgr = self.get_routing_service_helper().driver_manager
res = self._dev_status.check_backlogged_hosting_devices(driver_mgr)
if res['reachable']:
self.process_services(device_ids=res['reachable'])
if res['revived']:
LOG.debug("Reporting revived hosting devices: %s " %
res['revived'])
# trigger a sync only on the revived hosting-devices
if self.conf.cfg_agent.enable_heartbeat is True:
self.devmgr_rpc.report_revived_hosting_devices(
context, hd_ids=res['revived'])
self.process_services(device_ids=res['revived'])
if res['dead']:
LOG.debug("Reporting dead hosting devices: %s", res['dead'])
self.devmgr_rpc.report_dead_hosting_devices(context,
hd_ids=res['dead']) | python | def _process_backlogged_hosting_devices(self, context):
"""Process currently backlogged devices.
Go through the currently backlogged devices and process them.
For devices which are now reachable (compared to last time), we call
`process_services()` passing the now reachable device's id.
For devices which have passed the `hosting_device_dead_timeout` and
hence presumed dead, execute a RPC to the plugin informing that.
heartbeat revision
res['reachable'] - hosting device went from Unknown to Active state
process_services(...)
res['revived'] - hosting device went from Dead to Active
inform device manager that the hosting
device is now responsive
res['dead'] - hosting device went from Unknown to Dead
inform device manager that the hosting
device is non-responding
As additional note for the revived case:
Although the plugin was notified, there may be some lag
before the plugin actually can reschedule it's backlogged routers.
If process_services(device_ids...) isn't successful initially,
subsequent device syncs will be attempted until
MAX_DEVICE_SYNC_ATTEMPTS occurs. Main process_service task
will resume if sync_devices is populated.
:param context: RPC context
:return: None
"""
driver_mgr = self.get_routing_service_helper().driver_manager
res = self._dev_status.check_backlogged_hosting_devices(driver_mgr)
if res['reachable']:
self.process_services(device_ids=res['reachable'])
if res['revived']:
LOG.debug("Reporting revived hosting devices: %s " %
res['revived'])
# trigger a sync only on the revived hosting-devices
if self.conf.cfg_agent.enable_heartbeat is True:
self.devmgr_rpc.report_revived_hosting_devices(
context, hd_ids=res['revived'])
self.process_services(device_ids=res['revived'])
if res['dead']:
LOG.debug("Reporting dead hosting devices: %s", res['dead'])
self.devmgr_rpc.report_dead_hosting_devices(context,
hd_ids=res['dead']) | [
"def",
"_process_backlogged_hosting_devices",
"(",
"self",
",",
"context",
")",
":",
"driver_mgr",
"=",
"self",
".",
"get_routing_service_helper",
"(",
")",
".",
"driver_manager",
"res",
"=",
"self",
".",
"_dev_status",
".",
"check_backlogged_hosting_devices",
"(",
... | Process currently backlogged devices.
Go through the currently backlogged devices and process them.
For devices which are now reachable (compared to last time), we call
`process_services()` passing the now reachable device's id.
For devices which have passed the `hosting_device_dead_timeout` and
hence presumed dead, execute a RPC to the plugin informing that.
heartbeat revision
res['reachable'] - hosting device went from Unknown to Active state
process_services(...)
res['revived'] - hosting device went from Dead to Active
inform device manager that the hosting
device is now responsive
res['dead'] - hosting device went from Unknown to Dead
inform device manager that the hosting
device is non-responding
As additional note for the revived case:
Although the plugin was notified, there may be some lag
before the plugin actually can reschedule it's backlogged routers.
If process_services(device_ids...) isn't successful initially,
subsequent device syncs will be attempted until
MAX_DEVICE_SYNC_ATTEMPTS occurs. Main process_service task
will resume if sync_devices is populated.
:param context: RPC context
:return: None | [
"Process",
"currently",
"backlogged",
"devices",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L269-L315 | train | 37,998 |
openstack/networking-cisco | networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py | CiscoCfgAgent.agent_updated | def agent_updated(self, context, payload):
"""Deal with agent updated RPC message."""
try:
if payload['admin_state_up']:
#TODO(hareeshp): implement agent updated handling
pass
except KeyError as e:
LOG.error("Invalid payload format for received RPC message "
"`agent_updated`. Error is %(error)s. Payload is "
"%(payload)s", {'error': e, 'payload': payload}) | python | def agent_updated(self, context, payload):
"""Deal with agent updated RPC message."""
try:
if payload['admin_state_up']:
#TODO(hareeshp): implement agent updated handling
pass
except KeyError as e:
LOG.error("Invalid payload format for received RPC message "
"`agent_updated`. Error is %(error)s. Payload is "
"%(payload)s", {'error': e, 'payload': payload}) | [
"def",
"agent_updated",
"(",
"self",
",",
"context",
",",
"payload",
")",
":",
"try",
":",
"if",
"payload",
"[",
"'admin_state_up'",
"]",
":",
"#TODO(hareeshp): implement agent updated handling",
"pass",
"except",
"KeyError",
"as",
"e",
":",
"LOG",
".",
"error",... | Deal with agent updated RPC message. | [
"Deal",
"with",
"agent",
"updated",
"RPC",
"message",
"."
] | aa58a30aec25b86f9aa5952b0863045975debfa9 | https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/cfg_agent.py#L317-L326 | train | 37,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.