Remove some pylint exclusions

Change-Id: I6909c10471039f1e68224679ceeb2867ab5a3a47
This commit is contained in:
asarfaty 2020-09-30 10:32:46 +02:00
parent 1a93a3f6ca
commit b6bd7e49d1
62 changed files with 276 additions and 362 deletions

View File

@ -20,16 +20,12 @@ disable=
# "E" Error for important programming issues (likely bugs)
access-member-before-definition,
no-member,
no-method-argument,
no-self-argument,
not-an-iterable,
# "W" Warnings for stylistic problems or minor programming issues
abstract-method,
abstract-class-instantiated,
arguments-differ,
attribute-defined-outside-init,
bad-builtin,
bad-indentation,
broad-except,
dangerous-default-value,
deprecated-lambda,
@ -75,10 +71,8 @@ disable=
consider-using-ternary,
duplicate-code,
interface-not-implemented,
no-else-return,
no-self-use,
redefined-argument-from-local,
simplifiable-if-statement,
too-few-public-methods,
too-many-ancestors,
too-many-arguments,

View File

@ -140,7 +140,7 @@ class ApiClientBase(object, metaclass=abc.ABCMeta):
{'rid': rid,
'conn': api_client.ctrl_conn_to_str(http_conn)})
return
elif hasattr(http_conn, "no_release"):
if hasattr(http_conn, "no_release"):
return
priority = http_conn.priority

View File

@ -122,8 +122,7 @@ class EventletApiRequest(request.ApiRequest):
LOG.info('[%d] Request timeout.', self._rid())
self._request_error = Exception(_('Request timeout'))
return None
else:
return self._handle_request()
return self._handle_request()
def _handle_request(self):
'''First level request handling.'''

View File

@ -246,12 +246,11 @@ class ApiRequest(object, metaclass=abc.ABCMeta):
else:
url = result.path
return (conn, url) # case 1
else:
LOG.warning("[%(rid)d] Received invalid redirect "
"location: '%(url)s'",
{'rid': self._rid(), 'url': url})
return (conn, None) # case 3
elif result.scheme not in ["http", "https"] or not result.hostname:
LOG.warning("[%(rid)d] Received invalid redirect "
"location: '%(url)s'",
{'rid': self._rid(), 'url': url})
return (conn, None) # case 3
if result.scheme not in ["http", "https"] or not result.hostname:
LOG.warning("[%(rid)d] Received malformed redirect "
"location: %(url)s",
{'rid': self._rid(), 'url': url})

View File

@ -39,13 +39,12 @@ class LockManager(object):
LOG.debug('Lock %s taken with stack trace %s', name,
traceback.extract_stack(limit=5))
return lck
else:
# Ensure that external=True
kwargs['external'] = True
lck = LockManager._get_lock_local(name, **kwargs)
LOG.debug('Lock %s taken with stack trace %s', name,
traceback.extract_stack(limit=5))
return lck
# Ensure that external=True
kwargs['external'] = True
lck = LockManager._get_lock_local(name, **kwargs)
LOG.debug('Lock %s taken with stack trace %s', name,
traceback.extract_stack(limit=5))
return lck
@staticmethod
def _get_lock_local(name, **kwargs):

View File

@ -150,8 +150,7 @@ def device_id_to_vm_id(device_id, obfuscate=False):
# hashing
if len(device_id) > MAX_DISPLAY_NAME_LEN or obfuscate:
return hashlib.sha1(device_id.encode()).hexdigest()
else:
return device_id or "N/A"
return device_id or "N/A"
def check_and_truncate(display_name):
@ -264,8 +263,7 @@ def get_name_and_uuid(name, uuid, tag=None, maxlen=80):
if tag:
maxlen = maxlen - len(tag) - 1
return name[:maxlen] + '_' + tag + short_uuid
else:
return name[:maxlen] + short_uuid
return name[:maxlen] + short_uuid
def is_ipv4_ip_address(addr):

View File

@ -57,8 +57,7 @@ def include_object(object, name, type_, reflected, compare_to):
if (type_ == 'table' and
name in set(external.TABLES) - set(external.REPO_VMWARE_TABLES)):
return False
else:
return True
return True
def run_migrations_offline():

View File

@ -394,7 +394,7 @@ def get_nsxv_internal_network(session, network_purpose, availability_zone,
if net_list:
# Should have only one results as purpose+az are the keys
return net_list[0]
elif default_fallback and availability_zone != nsx_az.DEFAULT_NAME:
if default_fallback and availability_zone != nsx_az.DEFAULT_NAME:
# try the default availability zone, since this zone does not
# have his own internal edge
net_list = (session.query(nsxv_models.NsxvInternalNetworks).

View File

@ -123,14 +123,13 @@ class MigrationManager(object):
count = len(subnets)
if count == 0:
return None
elif count == 1 and subnets[0]['cidr'] == rpc.METADATA_SUBNET_CIDR:
if count == 1 and subnets[0]['cidr'] == rpc.METADATA_SUBNET_CIDR:
reason = _("Cannot migrate a 'metadata' network")
raise n_exc.BadRequest(resource='network', msg=reason)
elif count > 1:
if count > 1:
reason = _("Unable to support multiple subnets per network")
raise p_exc.LsnMigrationConflict(net_id=network_id, reason=reason)
else:
return subnets[0]
return subnets[0]
def migrate(self, context, network_id, subnet=None):
"""Migrate subnet resources to LSN."""

View File

@ -347,13 +347,12 @@ class DvsManager(VCManagerBase):
return self._update_net_port_groups_config(net_moref,
spec_update_calback,
spec_update_data)
else:
dvs_moref = self._get_dvs_moref_by_id(dvs_id)
return self._update_vxlan_port_groups_config(dvs_moref,
net_id,
net_moref,
spec_update_calback,
spec_update_data)
dvs_moref = self._get_dvs_moref_by_id(dvs_id)
return self._update_vxlan_port_groups_config(dvs_moref,
net_id,
net_moref,
spec_update_calback,
spec_update_data)
# Update the dvs port groups config for a vxlan network
# Searching the port groups for a partial match to the network id & moref

View File

@ -47,5 +47,4 @@ class Advancedserviceproviders(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
return {}

View File

@ -90,8 +90,7 @@ class Api_replay(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}
def get_required_extensions(self):
# make sure this extension is called after those, so our change

View File

@ -105,5 +105,4 @@ class Edge_service_gateway_bgp_peer(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}

View File

@ -80,8 +80,7 @@ class Housekeeper(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}
class HousekeeperReadOnly(nexception.NotAuthorized):

View File

@ -75,5 +75,4 @@ class Lsn(api_extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}

View File

@ -56,5 +56,4 @@ class Maclearning(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
return {}

View File

@ -74,8 +74,7 @@ class Nsxpolicy(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}
class NsxPolicyReadOnly(nexception.NotAuthorized):

View File

@ -95,8 +95,7 @@ class Projectpluginmap(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}
class ProjectPluginReadOnly(nexception.NotAuthorized):

View File

@ -97,5 +97,4 @@ class Providersecuritygroup(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
return {}

View File

@ -59,5 +59,4 @@ class Routertype(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
return {}

View File

@ -62,5 +62,4 @@ class Secgroup_rule_local_ip_prefix(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}

View File

@ -66,5 +66,4 @@ class Securitygrouplogging(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}

View File

@ -68,5 +68,4 @@ class Securitygrouppolicy(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
return {}

View File

@ -49,5 +49,4 @@ class Vnicindex(extensions.ExtensionDescriptor):
def get_extended_resources(self, version):
if version == "2.0":
return EXTENDED_ATTRIBUTES_2_0
else:
return {}
return {}

View File

@ -89,8 +89,7 @@ def get_lswitches(cluster, neutron_net_id):
results.extend(lookup_switches_by_tag())
if results:
return results
else:
raise exception.NetworkNotFound(net_id=neutron_net_id)
raise exception.NetworkNotFound(net_id=neutron_net_id)
# This api is currently used only for unittests

View File

@ -127,11 +127,10 @@ class NsxHousekeeper(stevedore.named.NamedExtensionManager):
if non_readonly_jobs:
return True
return False
else:
# specific job is allowed if it is not in the readonly list
if job_name in self.readonly_jobs:
return False
return True
# specific job is allowed if it is not in the readonly list
if job_name in self.readonly_jobs:
return False
return True
def run(self, context, job_name, readonly=False):
self.results = {}

View File

@ -248,9 +248,8 @@ class NsxPluginV3Base(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
LOG.warning("Skipping tag %s for port %s: wrong format",
external_tag, port_id)
return {}
else:
return {'scope': tag_parts[0][:nsxlib_utils.MAX_RESOURCE_TYPE_LEN],
'tag': tag_parts[1][:nsxlib_utils.MAX_TAG_LEN]}
return {'scope': tag_parts[0][:nsxlib_utils.MAX_RESOURCE_TYPE_LEN],
'tag': tag_parts[1][:nsxlib_utils.MAX_TAG_LEN]}
def _translate_external_tags(self, external_tags, port_id):
new_tags = []
@ -1310,8 +1309,7 @@ class NsxPluginV3Base(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
if not network.get(pnet.PHYSICAL_NETWORK):
az = self.get_network_az(network)
return az._default_tier0_router
else:
return network.get(pnet.PHYSICAL_NETWORK)
return network.get(pnet.PHYSICAL_NETWORK)
def _validate_router_tz(self, context, tier0_uuid, subnets):
"""Ensure the related GW (Tier0 router) belongs to the same TZ
@ -2277,8 +2275,7 @@ class NsxPluginV3Base(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
not self.use_policy_dhcp)):
return self._create_bulk_with_callback('subnet', context, subnets,
_post_create, _rollback)
else:
return self._create_bulk('subnet', context, subnets)
return self._create_bulk('subnet', context, subnets)
def _get_neutron_net_ids_by_nsx_id(self, context, nsx_id):
"""Should be implemented by each plugin"""

View File

@ -188,10 +188,9 @@ class NsxDvsV2(addr_pair_db.AllowedAddressPairsMixin,
def _dvs_get_id(self, net_data):
if net_data['name'] == '':
return net_data['id']
else:
# Maximum name length is 80 characters. 'id' length is 36
# maximum prefix for name is 43
return '%s-%s' % (net_data['name'][:43], net_data['id'])
# Maximum name length is 80 characters. 'id' length is 36
# maximum prefix for name is 43
return '%s-%s' % (net_data['name'][:43], net_data['id'])
def _add_port_group(self, dvs_id, net_data, vlan_tag, trunk_mode):
if validators.is_attr_set(net_data.get(pnet.PHYSICAL_NETWORK)):

View File

@ -241,10 +241,9 @@ class NsxTVDPlugin(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
plugin = self.get_plugin_by_type(plugin_type)
if plugin:
return plugin._get_octavia_objects()
else:
return {'loadbalancer': None, 'listener': None, 'pool': None,
'member': None, 'healthmonitor': None, 'l7policy': None,
'l7rule': None}
return {'loadbalancer': None, 'listener': None, 'pool': None,
'member': None, 'healthmonitor': None, 'l7policy': None,
'l7rule': None}
def init_complete(self, resource, event, trigger, payload=None):
with locking.LockManager.get_lock('plugin-init-complete-tvd'):
@ -548,19 +547,18 @@ class NsxTVDPlugin(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
if subnets:
return subnets
return []
else:
# Read project plugin to filter relevant projects according to
# plugin
req_p = self._get_plugin_for_request(context, filters)
filters = filters or {}
subnets = super(NsxTVDPlugin, self).get_subnets(
context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
for subnet in subnets[:]:
p = self._get_plugin_from_project(context, subnet['tenant_id'])
if req_p and p != req_p:
subnets.remove(subnet)
return subnets
# Read project plugin to filter relevant projects according to
# plugin
req_p = self._get_plugin_for_request(context, filters)
filters = filters or {}
subnets = super(NsxTVDPlugin, self).get_subnets(
context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
for subnet in subnets[:]:
p = self._get_plugin_from_project(context, subnet['tenant_id'])
if req_p and p != req_p:
subnets.remove(subnet)
return subnets
def delete_subnet(self, context, id):
p = self._get_subnet_plugin_by_id(context, id)
@ -903,8 +901,7 @@ class NsxTVDPlugin(agentschedulers_db.AZDhcpAgentSchedulerDbMixin,
data = nsx_db.get_project_plugin_mapping(context.session, id)
if data:
return self._get_project_plugin_dict(data)
else:
raise n_exc.ObjectNotFound(id=id)
raise n_exc.ObjectNotFound(id=id)
def get_project_plugin_maps(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,

View File

@ -55,8 +55,7 @@ def filter_plugins(cls):
context.session, project_id)
if mapping:
return mapping['plugin']
else:
raise exceptions.ObjectNotFound(id=project_id)
raise exceptions.ObjectNotFound(id=project_id)
def add_separate_plugin_hook(name):
orig_method = getattr(cls, name, None)

View File

@ -952,11 +952,12 @@ class NsxPolicyPlugin(nsx_plugin_common.NsxPluginV3Base):
# use this profile
if STATEFUL_DHCP_NDRA_PROFILE_ID in profiles:
return STATEFUL_DHCP_NDRA_PROFILE_ID
elif STATELESS_DHCP_NDRA_PROFILE_ID in profiles:
if STATELESS_DHCP_NDRA_PROFILE_ID in profiles:
return STATELESS_DHCP_NDRA_PROFILE_ID
elif SLAAC_NDRA_PROFILE_ID in profiles:
if SLAAC_NDRA_PROFILE_ID in profiles:
# if there is slaac subnet and no DHCP subnet use SLAAC
return SLAAC_NDRA_PROFILE_ID
return NO_SLAAC_NDRA_PROFILE_ID
def _update_slaac_on_router(self, context, router_id,
@ -1402,7 +1403,7 @@ class NsxPolicyPlugin(nsx_plugin_common.NsxPluginV3Base):
if subnet.enable_dhcp and subnet.ip_version == ip_version:
if ip_version == 4:
return True
elif subnet.ipv6_address_mode != const.IPV6_SLAAC:
if subnet.ipv6_address_mode != const.IPV6_SLAAC:
return True
return False
@ -4109,15 +4110,13 @@ class NsxPolicyPlugin(nsx_plugin_common.NsxPluginV3Base):
# If it is an NSX network, return the TZ of the backend segment
segment_id = bindings[0].phy_uuid
return self.nsxpolicy.segment.get_transport_zone_id(segment_id)
elif bind_type == utils.NetworkTypes.L3_EXT:
if bind_type == utils.NetworkTypes.L3_EXT:
# External network has tier0 as phy_uuid
return
else:
return bindings[0].phy_uuid
else:
# Get the default one for the network AZ
az = self.get_network_az_by_net_id(context, net_id)
return az._default_overlay_tz_uuid
return bindings[0].phy_uuid
# Get the default one for the network AZ
az = self.get_network_az_by_net_id(context, net_id)
return az._default_overlay_tz_uuid
def _validate_router_tz(self, context, tier0_uuid, subnets):
# make sure the related GW (Tier0 router) belongs to the same TZ

View File

@ -77,25 +77,24 @@ class RouterSharedDriver(router_driver.RouterBaseDriver):
if not edge_id:
return super(nsx_v.NsxVPluginV2, self.plugin).update_router(
context, router_id, router)
else:
with locking.LockManager.get_lock(str(edge_id)):
gw_info = self.plugin._extract_external_gw(
context, router, is_extract=True)
super(nsx_v.NsxVPluginV2, self.plugin).update_router(
context, router_id, router)
with locking.LockManager.get_lock(str(edge_id)):
gw_info = self.plugin._extract_external_gw(
context, router, is_extract=True)
super(nsx_v.NsxVPluginV2, self.plugin).update_router(
context, router_id, router)
if gw_info != constants.ATTR_NOT_SPECIFIED:
self.plugin._update_router_gw_info(context, router_id, gw_info)
if 'admin_state_up' in r:
# If router was deployed on a different edge then
# admin-state-up is already updated on the new edge.
current_edge_id = (
edge_utils.get_router_edge_id(context, router_id))
if current_edge_id == edge_id:
self.plugin._update_router_admin_state(context, router_id,
self.get_type(),
r['admin_state_up'])
return self.plugin.get_router(context, router_id)
if gw_info != constants.ATTR_NOT_SPECIFIED:
self.plugin._update_router_gw_info(context, router_id, gw_info)
if 'admin_state_up' in r:
# If router was deployed on a different edge then
# admin-state-up is already updated on the new edge.
current_edge_id = (
edge_utils.get_router_edge_id(context, router_id))
if current_edge_id == edge_id:
self.plugin._update_router_admin_state(context, router_id,
self.get_type(),
r['admin_state_up'])
return self.plugin.get_router(context, router_id)
def detach_router(self, context, router_id, router):
LOG.debug("Detach shared router id %s", router_id)

View File

@ -251,8 +251,7 @@ class NsxVMetadataProxyHandler(object):
ports = self.nsxv_plugin.get_ports(context, filters=filters)
if ports:
return ports[0]['fixed_ips'][0]['ip_address']
else:
LOG.error("No port found for metadata for %s", rtr_id)
LOG.error("No port found for metadata for %s", rtr_id)
def _get_edge_rtr_id_by_ext_ip(self, context, edge_ip):
rtr_list = nsxv_db.get_nsxv_internal_edge(

View File

@ -840,11 +840,10 @@ class NsxVPluginV2(addr_pair_db.AllowedAddressPairsMixin,
if bindings:
if not multiprovider:
return bindings[0].binding_type in net_types
else:
for binding in bindings:
if binding.binding_type not in net_types:
return False
return True
for binding in bindings:
if binding.binding_type not in net_types:
return False
return True
return False
def _extend_network_dict_provider(self, context, network,
@ -896,7 +895,7 @@ class NsxVPluginV2(addr_pair_db.AllowedAddressPairsMixin,
if not context.is_admin:
return subnet
elif fields and as_providers.ADV_SERVICE_PROVIDERS in fields:
if fields and as_providers.ADV_SERVICE_PROVIDERS in fields:
subnet[as_providers.ADV_SERVICE_PROVIDERS] = (
self._get_subnet_as_providers(context, subnet))
return subnet
@ -1187,9 +1186,8 @@ class NsxVPluginV2(addr_pair_db.AllowedAddressPairsMixin,
def _get_physical_network(self, network_type, net_data):
if network_type == c_utils.NsxVNetworkTypes.VXLAN:
return self._get_network_vdn_scope_id(net_data)
else:
# Use the dvs_id of the availability zone
return self._get_network_az_dvs_id(net_data)
# Use the dvs_id of the availability zone
return self._get_network_az_dvs_id(net_data)
def _generate_segment_id(self, context, physical_network, net_data):
bindings = nsxv_db.get_network_bindings_by_physical_net(

View File

@ -45,33 +45,31 @@ class EdgeFirewallDriver(object):
def _convert_firewall_action(self, action):
if action == FWAAS_ALLOW:
return VSE_FWAAS_ALLOW
elif action == FWAAS_DENY:
if action == FWAAS_DENY:
return VSE_FWAAS_DENY
elif action == FWAAS_REJECT:
if action == FWAAS_REJECT:
return VSE_FWAAS_REJECT
else:
msg = _("Invalid action value %s in a firewall rule") % action
raise vcns_exc.VcnsBadRequest(resource='firewall_rule', msg=msg)
msg = _("Invalid action value %s in a firewall rule") % action
raise vcns_exc.VcnsBadRequest(resource='firewall_rule', msg=msg)
def _restore_firewall_action(self, action):
if action == VSE_FWAAS_ALLOW:
return FWAAS_ALLOW
elif action == VSE_FWAAS_DENY:
if action == VSE_FWAAS_DENY:
return FWAAS_DENY
elif action == VSE_FWAAS_REJECT:
if action == VSE_FWAAS_REJECT:
return FWAAS_REJECT
else:
msg = (_("Invalid action value %s in "
"a vshield firewall rule") % action)
raise vcns_exc.VcnsBadRequest(resource='firewall_rule', msg=msg)
msg = (_("Invalid action value %s in "
"a vshield firewall rule") % action)
raise vcns_exc.VcnsBadRequest(resource='firewall_rule', msg=msg)
def _get_port_range(self, min_port, max_port):
if not min_port or min_port == 'any':
return None
if min_port == max_port:
return str(min_port)
else:
return '%d:%d' % (min_port, max_port)
return '%d:%d' % (min_port, max_port)
def _get_ports_list_from_string(self, port_str):
"""Receives a string representation of the service ports,
@ -96,8 +94,7 @@ class EdgeFirewallDriver(object):
if port and port.isdigit():
ports_set.add(int(port))
return sorted(list(ports_set))
else:
return [int(port_str.strip())]
return [int(port_str.strip())]
def _convert_firewall_rule(self, rule, index=None):
vcns_rule = {
@ -239,8 +236,7 @@ class EdgeFirewallDriver(object):
if str(rule_cur['ruleId']) == rule_vseid:
if (i + 1) == len(fw_cfg['firewallRules']['firewallRules']):
return None
else:
return fw_cfg['firewallRules']['firewallRules'][i + 1]
return fw_cfg['firewallRules']['firewallRules'][i + 1]
def get_firewall_rule(self, context, id, edge_id):
rule_map = nsxv_db.get_nsxv_edge_firewallrule_binding(

View File

@ -86,8 +86,7 @@ def get_vdr_transit_network_plr_address():
# was "169.254.2.3"
if conf.DEFAULT_VDR_TRANSIT_NETWORK == cfg.CONF.nsxv.vdr_transit_network:
return conf.DEFAULT_PLR_ADDRESS
else:
return str(ip[2])
return str(ip[2])
def validate_vdr_transit_network():
@ -1293,7 +1292,7 @@ class EdgeManager(object):
if not ports:
LOG.debug('No metadata ports found for %s', org_router_id)
return
elif len(ports) > 1:
if len(ports) > 1:
LOG.debug('Expecting one metadata port for %s. Found %d ports',
org_router_id, len(ports))
@ -1516,35 +1515,34 @@ class EdgeManager(object):
}
address_groups['addressGroups'].append(address_group)
return True
else:
for ind, address_group in enumerate(
address_groups['addressGroups']):
if address_group['primaryAddress'] == old_ip:
# this is the one we should update
for ind, address_group in enumerate(
address_groups['addressGroups']):
if address_group['primaryAddress'] == old_ip:
# this is the one we should update
if new_ip:
address_group['primaryAddress'] = new_ip
else:
# delete this entry
address_groups['addressGroups'].pop(ind)
return True
# try to find a match in the secondary ips
if (address_group.get('secondaryAddresses') is not None):
secondary = address_group['secondaryAddresses']
secondary_ips = secondary['ipAddress']
if old_ip in secondary_ips:
# We should update the secondary addresses
if new_ip:
address_group['primaryAddress'] = new_ip
# replace the old with the new
secondary_ips.remove(old_ip)
secondary_ips.append(new_ip)
else:
# delete this entry
address_groups['addressGroups'].pop(ind)
return True
# try to find a match in the secondary ips
if (address_group.get('secondaryAddresses') is not None):
secondary = address_group['secondaryAddresses']
secondary_ips = secondary['ipAddress']
if old_ip in secondary_ips:
# We should update the secondary addresses
if new_ip:
# replace the old with the new
secondary_ips.remove(old_ip)
secondary_ips.append(new_ip)
if len(secondary_ips) == 1:
# delete the whole structure
del address_group['secondaryAddresses']
else:
# delete this entry
if len(secondary_ips) == 1:
# delete the whole structure
del address_group['secondaryAddresses']
else:
secondary_ips.remove(old_ip)
return True
secondary_ips.remove(old_ip)
return True
# The old ip was not found
return False
@ -1807,8 +1805,7 @@ class EdgeManager(object):
if router_ids == [router_id]:
self._free_edge_appliance(context, router_id)
return True
else:
nsxv_db.delete_nsxv_router_binding(context.session, router_id)
nsxv_db.delete_nsxv_router_binding(context.session, router_id)
def is_router_conflict_on_edge(self, context, router_id,
conflict_router_ids,
@ -2156,9 +2153,7 @@ def get_dhcp_binding_for_binding_id(nsxv_manager, edge_id, binding_id):
ver = nsxv_manager.vcns.get_version()
if c_utils.is_nsxv_dhcp_binding_supported(ver):
return _get_dhcp_binding(nsxv_manager, edge_id, binding_id)
else:
return _get_dhcp_binding_for_binding_id(nsxv_manager, edge_id,
binding_id)
return _get_dhcp_binding_for_binding_id(nsxv_manager, edge_id, binding_id)
def query_dhcp_service_config(nsxv_manager, edge_id):

View File

@ -344,10 +344,8 @@ class TaskManager(object):
LOG.info("TaskManager terminated")
def has_pending_task(self):
if self._tasks_queue or self._tasks or self._main_thread_exec_task:
return True
else:
return False
return bool(self._tasks_queue or self._tasks or
self._main_thread_exec_task)
def show_pending_tasks(self):
for task in self._tasks_queue:

View File

@ -878,8 +878,7 @@ class Vcns(object):
uri_path = uri_prefix
if is_async:
return (uri_path + "?async=true")
else:
return uri_path
return uri_path
def add_vm_to_exclude_list(self, vm_id):
uri = '%s/%s' % (EXCLUDELIST_PREFIX, vm_id)

View File

@ -1010,8 +1010,7 @@ class NsxV3Plugin(nsx_plugin_common.NsxPluginV3Base,
# This should not happen, but added here in case the network was
# created before this code was added.
return neutron_id
else:
return mappings[0]
return mappings[0]
def update_network(self, context, id, network):
original_net = super(NsxV3Plugin, self).get_network(context, id)
@ -1609,7 +1608,7 @@ class NsxV3Plugin(nsx_plugin_common.NsxPluginV3Base,
def _get_resource_type_for_device_id(self, device_owner, device_id):
if device_owner in const.ROUTER_INTERFACE_OWNERS:
return 'os-router-uuid'
elif device_owner.startswith(const.DEVICE_OWNER_COMPUTE_PREFIX):
if device_owner.startswith(const.DEVICE_OWNER_COMPUTE_PREFIX):
return 'os-instance-uuid'
def _update_port_on_backend(self, context, lport_id,

View File

@ -116,7 +116,7 @@ class EdgeFwaasV3DriverV2(base_driver.CommonEdgeFwaasV3Driver):
l4_protocol=l4_protocol,
source_ports=source_ports,
destination_ports=destination_ports)]
elif l4_protocol == consts.ICMPV4:
if l4_protocol == consts.ICMPV4:
# Add both icmp v4 & v6 services
return [
self.nsx_firewall.get_nsservice(

View File

@ -57,12 +57,11 @@ class NsxvIpamDriver(common.NsxAbstractIpamDriver, common.NsxIpamBase):
"""Return True if the network of the request is an ipv6 network"""
if isinstance(subnet_request, ipam_req.SpecificSubnetRequest):
return subnet_request.subnet_cidr.version == 6
else:
if subnet_request.allocation_pools:
for pool in subnet_request.allocation_pools:
if pool.version == 6:
return True
return False
if subnet_request.allocation_pools:
for pool in subnet_request.allocation_pools:
if pool.version == 6:
return True
return False
def _is_supported_net(self, subnet_request):
"""This driver supports only ipv4 external/provider networks"""

View File

@ -144,17 +144,16 @@ def update_router_lb_vip_advertisement(context, core_plugin, router_id):
def get_monitor_policy_client(lb_client, hm):
if hm['type'] == lb_const.LB_HEALTH_MONITOR_TCP:
return lb_client.lb_monitor_profile_tcp
elif hm['type'] == lb_const.LB_HEALTH_MONITOR_HTTP:
if hm['type'] == lb_const.LB_HEALTH_MONITOR_HTTP:
return lb_client.lb_monitor_profile_http
elif hm['type'] == lb_const.LB_HEALTH_MONITOR_HTTPS:
if hm['type'] == lb_const.LB_HEALTH_MONITOR_HTTPS:
return lb_client.lb_monitor_profile_https
elif hm['type'] == lb_const.LB_HEALTH_MONITOR_PING:
if hm['type'] == lb_const.LB_HEALTH_MONITOR_PING:
return lb_client.lb_monitor_profile_icmp
else:
msg = (_('Cannot create health monitor %(monitor)s with '
'type %(type)s') % {'monitor': hm['id'],
'type': hm['type']})
raise n_exc.InvalidInput(error_message=msg)
msg = (_('Cannot create health monitor %(monitor)s with '
'type %(type)s') % {'monitor': hm['id'],
'type': hm['type']})
raise n_exc.InvalidInput(error_message=msg)
def get_tags(plugin, resource_id, resource_type, project_id, project_name):
@ -243,11 +242,10 @@ def setup_session_persistence(nsxpolicy, pool, pool_tags, switch_type,
'pool_id': pool['id']})
pp_client.update(persistence_profile_id, **pp_kwargs)
return persistence_profile_id, None
else:
# Prepare removal of persistence profile
return (None, functools.partial(delete_persistence_profile,
nsxpolicy, profile_path))
elif pers_type:
# Prepare removal of persistence profile
return (None, functools.partial(delete_persistence_profile,
nsxpolicy, profile_path))
if pers_type:
# Create persistence profile
pp_id = "%s_%s" % (pool['id'], pers_id_suffix)
pp_kwargs['persistence_profile_id'] = pp_id
@ -293,8 +291,7 @@ def get_lb_nsx_lb_service(nsxpolicy, lb_id):
def get_service_lb_name(lb, router_id=None):
if router_id:
return utils.get_name_and_uuid('rtr', router_id)
else:
return utils.get_name_and_uuid(lb.get('name') or 'lb', lb.get('id'))
return utils.get_name_and_uuid(lb.get('name') or 'lb', lb.get('id'))
def get_service_lb_tag(lb_id):

View File

@ -37,10 +37,9 @@ class EdgeMemberManagerFromDict(base_mgr.NsxpLoadbalancerBaseManager):
filters=filters)
if floating_ips:
return floating_ips[0]
else:
msg = (_('Member IP %(fip)s is an external IP, and is expected to '
'be a floating IP') % {'fip': fip})
raise n_exc.BadRequest(resource='lbaas-vip', msg=msg)
msg = (_('Member IP %(fip)s is an external IP, and is expected to '
'be a floating IP') % {'fip': fip})
raise n_exc.BadRequest(resource='lbaas-vip', msg=msg)
def _get_info_from_fip(self, context, fip):
return self._get_fip_object(context, fip)['fixed_ip_address']

View File

@ -47,18 +47,16 @@ class EdgeLoadBalancerManagerFromDict(base_mgr.EdgeLoadbalancerBaseManager):
def _get_lb_flavor_size(self, context, flavor_id):
if not flavor_id:
return vcns_const.SERVICE_SIZE_MAPPING['lb']
else:
flavor = flavors_plugin.FlavorsPlugin.get_flavor(
self.flavor_plugin, context, flavor_id)
flavor_size = flavor['name']
if flavor_size.lower() in vcns_const.ALLOWED_EDGE_SIZES:
return flavor_size.lower()
else:
err_msg = (_("Invalid flavor size %(flavor)s, only %(sizes)s "
"are supported") %
{'flavor': flavor_size,
'sizes': vcns_const.ALLOWED_EDGE_SIZES})
raise n_exc.InvalidInput(error_message=err_msg)
flavor = flavors_plugin.FlavorsPlugin.get_flavor(
self.flavor_plugin, context, flavor_id)
flavor_size = flavor['name']
if flavor_size.lower() in vcns_const.ALLOWED_EDGE_SIZES:
return flavor_size.lower()
err_msg = (_("Invalid flavor size %(flavor)s, only %(sizes)s "
"are supported") %
{'flavor': flavor_size,
'sizes': vcns_const.ALLOWED_EDGE_SIZES})
raise n_exc.InvalidInput(error_message=err_msg)
def create(self, context, lb, completor):
sub_id = lb['vip_subnet_id']

View File

@ -65,17 +65,17 @@ def get_router_from_network(context, plugin, subnet_id):
def get_lb_flavor_size(flavor_plugin, context, flavor_id):
if not flavor_id:
return lb_const.DEFAULT_LB_SIZE
else:
flavor = flavors_plugin.FlavorsPlugin.get_flavor(
flavor_plugin, context, flavor_id)
flavor_size = flavor['name']
if flavor_size in lb_const.LB_FLAVOR_SIZES:
return flavor_size.upper()
else:
err_msg = (_("Invalid flavor size %(flavor)s, only 'small', "
"'medium', or 'large' are supported") %
{'flavor': flavor_size})
raise n_exc.InvalidInput(error_message=err_msg)
flavor = flavors_plugin.FlavorsPlugin.get_flavor(
flavor_plugin, context, flavor_id)
flavor_size = flavor['name']
if flavor_size in lb_const.LB_FLAVOR_SIZES:
return flavor_size.upper()
err_msg = (_("Invalid flavor size %(flavor)s, only 'small', "
"'medium', or 'large' are supported") %
{'flavor': flavor_size})
raise n_exc.InvalidInput(error_message=err_msg)
@log_helpers.log_method_call
@ -97,8 +97,7 @@ def validate_lb_subnet(context, plugin, subnet_id):
context, plugin, subnet_id)
if network.get('router:external') or valid_router:
return True
else:
return False
return False
@log_helpers.log_method_call
@ -125,14 +124,11 @@ def validate_lb_member_subnet(context, plugin, subnet_id, lb):
# Lb on non-external network. member must be on the same router
if lb_router_id == member_router_id:
return True
else:
return False
else:
# LB on external network. member subnet must have a router
if member_router_id:
return True
else:
return False
return False
# LB on external network. member subnet must have a router
if member_router_id:
return True
return False
def get_rule_match_conditions(policy):
@ -321,11 +317,10 @@ def setup_session_persistence(nsxlib, pool, pool_tags,
'pool_id': pool['id']})
pp_client.update(persistence_profile_id, **pp_kwargs)
return persistence_profile_id, None
else:
# Prepare removal of persistence profile
return (None, functools.partial(delete_persistence_profile,
nsxlib, persistence_profile_id))
elif pers_type:
# Prepare removal of persistence profile
return (None, functools.partial(delete_persistence_profile,
nsxlib, persistence_profile_id))
if pers_type:
# Create persistence profile
pp_data = pp_client.create(**pp_kwargs)
LOG.debug("Created persistence profile %(profile_id)s for "

View File

@ -37,10 +37,9 @@ class EdgeMemberManagerFromDict(base_mgr.Nsxv3LoadbalancerBaseManager):
if floating_ips:
return (floating_ips[0]['fixed_ip_address'],
floating_ips[0]['router_id'])
else:
msg = (_('Member IP %(fip)s is an external IP, and is expected to '
'be a floating IP') % {'fip': fip})
raise n_exc.BadRequest(resource='lbaas-vip', msg=msg)
msg = (_('Member IP %(fip)s is an external IP, and is expected to '
'be a floating IP') % {'fip': fip})
raise n_exc.BadRequest(resource='lbaas-vip', msg=msg)
def _get_updated_pool_members(self, context, lb_pool, member):
network = lb_utils.get_network_from_subnet(

View File

@ -158,10 +158,9 @@ class IPsecCommonValidator(vpn_validator.VpnReferenceValidator):
def _get_peer_cidrs(self, context, ipsec_site_conn):
if ipsec_site_conn['peer_cidrs']:
return ipsec_site_conn['peer_cidrs']
else:
# peer endpoint group
self.vpn_plugin.get_endpoint_info(context, ipsec_site_conn)
return ipsec_site_conn['peer_epg_cidrs']['endpoints']
# peer endpoint group
self.vpn_plugin.get_endpoint_info(context, ipsec_site_conn)
return ipsec_site_conn['peer_epg_cidrs']['endpoints']
def _check_policy_rules_overlap(self, context, ipsec_site_conn):
"""validate no overlapping policy rules

View File

@ -464,7 +464,7 @@ class NSXpIPsecVpnDriver(common_driver.NSXcommonIPsecVpnDriver):
# VPNaaS connection status should be ACTIVE or DOWN
if status == 'UP':
return 'ACTIVE'
elif status == 'DOWN' or status == 'DEGRADED':
if status == 'DOWN' or status == 'DEGRADED':
return 'DOWN'
except nsx_lib_exc.ResourceNotFound:
LOG.debug("Status for VPN session %s was not found",

View File

@ -421,7 +421,7 @@ class NSXv3IPsecVpnDriver(common_driver.NSXcommonIPsecVpnDriver):
# VPNaaS connection status should be ACTIVE or DOWN
if status == 'UP':
return 'ACTIVE'
elif status == 'DOWN' or status == 'DEGRADED':
if status == 'DOWN' or status == 'DEGRADED':
return 'DOWN'
def _delete_session(self, session_id):

View File

@ -44,7 +44,7 @@ def output_formatter(resource_name, resources_list, attrs):
tableout.add_row(resource_list)
return tableout
elif fmt == 'json':
if fmt == 'json':
js_output = {}
js_output[resource_name] = []
for resource in resources_list:

View File

@ -85,11 +85,10 @@ def query_yes_no(question, default="yes"):
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
if choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def list_handler(resource):

View File

@ -47,13 +47,12 @@ def import_projects(resource, event, trigger, **kwargs):
if not kwargs.get('property'):
LOG.error("Need to specify plugin and project parameters")
return
else:
properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
plugin = properties.get('plugin')
project = properties.get('project')
if not plugin or not project:
LOG.error("Need to specify plugin and project parameters")
return
properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
plugin = properties.get('plugin')
project = properties.get('project')
if not plugin or not project:
LOG.error("Need to specify plugin and project parameters")
return
if plugin not in projectpluginmap.VALID_TYPES:
LOG.error("The supported plugins are %s", projectpluginmap.VALID_TYPES)
return

View File

@ -108,24 +108,23 @@ def nsx_update_dhcp_edge_binding(resource, event, trigger, **kwargs):
if not kwargs.get('property'):
LOG.error("Need to specify edge-id parameter")
return
else:
properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
edge_id = properties.get('edge-id')
if not edge_id:
LOG.error("Need to specify edge-id parameter")
return
LOG.info("Updating NSXv Edge: %s", edge_id)
# Need to create a plugin object; so that we are able to
# do neutron list-ports.
with utils.NsxVPluginWrapper() as plugin:
nsxv_manager = vcns_driver.VcnsDriver(
edge_utils.NsxVCallbacks(plugin))
edge_manager = edge_utils.EdgeManager(nsxv_manager, plugin)
try:
edge_manager.update_dhcp_service_config(
neutron_db.context, edge_id)
except exceptions.ResourceNotFound:
LOG.error("Edge %s not found", edge_id)
properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
edge_id = properties.get('edge-id')
if not edge_id:
LOG.error("Need to specify edge-id parameter")
return
LOG.info("Updating NSXv Edge: %s", edge_id)
# Need to create a plugin object; so that we are able to
# do neutron list-ports.
with utils.NsxVPluginWrapper() as plugin:
nsxv_manager = vcns_driver.VcnsDriver(
edge_utils.NsxVCallbacks(plugin))
edge_manager = edge_utils.EdgeManager(nsxv_manager, plugin)
try:
edge_manager.update_dhcp_service_config(
neutron_db.context, edge_id)
except exceptions.ResourceNotFound:
LOG.error("Edge %s not found", edge_id)
def delete_old_dhcp_edge(context, old_edge_id, bindings):

View File

@ -180,9 +180,8 @@ def router_binding_obj_exist(context, binding, net_ids, rtr_ids, plr_tlr_ids):
router_id, vcns_const.DHCP_EDGE_PREFIX)
if _is_id_prefix_in_list(net_id_prefix, net_ids):
return True
else:
LOG.warning("Network for binding entry %s not found", router_id)
return False
LOG.warning("Network for binding entry %s not found", router_id)
return False
if router_id.startswith(vcns_const.PLR_EDGE_PREFIX):
# Look for the TLR that matches this PLR
@ -191,32 +190,28 @@ def router_binding_obj_exist(context, binding, net_ids, rtr_ids, plr_tlr_ids):
tlr_id = plr_tlr_ids[router_id]
if _is_id_prefix_in_list(tlr_id, rtr_ids):
return True
else:
LOG.warning("TLR Router %s for PLR binding entry %s not found",
tlr_id, router_id)
return False
else:
LOG.warning("TLR Router binding for PLR binding entry %s not "
"found", router_id)
LOG.warning("TLR Router %s for PLR binding entry %s not found",
tlr_id, router_id)
return False
LOG.warning("TLR Router binding for PLR binding entry %s not "
"found", router_id)
return False
if router_id.startswith(lb_common.RESOURCE_ID_PFX):
# should have a load balancer starting with this id on the same edge
if nsxv_db.get_nsxv_lbaas_loadbalancer_binding_by_edge(
context.session, binding.edge_id):
return True
else:
LOG.warning("Loadbalancer for binding entry %s not found",
router_id)
return False
LOG.warning("Loadbalancer for binding entry %s not found",
router_id)
return False
# regular router
# get the id. and look for a router with this id
if _is_id_prefix_in_list(router_id, rtr_ids):
return True
else:
LOG.warning("Router for binding entry %s not found", router_id)
return False
LOG.warning("Router for binding entry %s not found", router_id)
return False
def get_orphaned_edges():

View File

@ -227,14 +227,13 @@ def nsx_redo_metadata_cfg(resource, event, trigger, **kwargs):
if edge_id:
nsx_redo_metadata_cfg_for_edge(edgeapi.context, plugin, edge_id)
return
else:
# if the net-id property exist - recreate the edge for this network
az_name = properties.get('az-name')
if az_name:
nsx_redo_metadata_cfg_for_az(edgeapi.context, plugin, az_name)
return
LOG.error('Cannot parse properties %s', properties)
# if the net-id property exist - recreate the edge for this network
az_name = properties.get('az-name')
if az_name:
nsx_redo_metadata_cfg_for_az(edgeapi.context, plugin, az_name)
return
LOG.error('Cannot parse properties %s', properties)
return
nsx_redo_metadata_cfg_all(edgeapi.context, plugin)

View File

@ -183,9 +183,8 @@ def nsx_recreate_router_or_edge(resource, event, trigger, **kwargs):
if old_edge_id:
LOG.info("ReCreating NSXv Router Edge: %s", old_edge_id)
return nsx_recreate_router_edge(old_edge_id)
else:
LOG.info("ReCreating NSXv Router: %s", router_id)
return nsx_recreate_router(router_id)
LOG.info("ReCreating NSXv Router: %s", router_id)
return nsx_recreate_router(router_id)
@admin_utils.output_header

View File

@ -77,8 +77,7 @@ def get_missing_spoofguard_policy_mappings(reverse=None):
if reverse:
return nsxv_spoofguard_policies - neutron_spoofguard_policy_mappings
else:
return neutron_spoofguard_policy_mappings - nsxv_spoofguard_policies
return neutron_spoofguard_policy_mappings - nsxv_spoofguard_policies
@admin_utils.output_header

View File

@ -181,8 +181,7 @@ def ensure_migration_state_ready(nsxlib, with_abort=False):
send_migration_plan_action(nsxlib, 'abort')
return ensure_migration_state_ready(
nsxlib, with_abort=with_abort)
else:
return False
return False
return True
@ -1187,8 +1186,7 @@ def migrate_lb_profiles(nsxlib, nsxpolicy):
if (res.get('resource_type') ==
nsxlib_lb.PersistenceProfileTypes.SOURCE_IP):
return "%s_%s" % (policy_id, 'sourceip')
else:
return "%s_%s" % (policy_id, 'cookie')
return "%s_%s" % (policy_id, 'cookie')
_migrate_lb_resource(nsxlib, nsxpolicy,
lb_const.LB_POOL_TYPE,

View File

@ -63,8 +63,7 @@ def get_network_nsx_id(session, neutron_id):
# This should not happen, but added here in case the network was
# created before this code was added.
return neutron_id
else:
return mappings[0]
return mappings[0]
@admin_utils.output_header

View File

@ -407,12 +407,11 @@ def reuse_default_section(resource, event, trigger, **kwargs):
LOG.info('Neutron DB is already configured correctly with section '
'%s and NS group %s', section_id, nsgroup_id)
return True
else:
LOG.info('Deleting old DB mappings for section %s and NS group %s',
db_section_id, db_nsgroup_id)
nsx_db.delete_sg_mappings(
context, plugin_utils.NSX_V3_OS_DFW_UUID,
db_nsgroup_id, db_section_id)
LOG.info('Deleting old DB mappings for section %s and NS group %s',
db_section_id, db_nsgroup_id)
nsx_db.delete_sg_mappings(
context, plugin_utils.NSX_V3_OS_DFW_UUID,
db_nsgroup_id, db_section_id)
# Add mappings to the neutron DB
LOG.info('Creating new DB mappings for section %s and NS group %s',

View File

@ -136,16 +136,15 @@ def _validate_plugin_choice(selected_plugin, nsx_plugin):
sys.exit(1)
# use nsxv or nsxv3 plugins
return selected_plugin
else:
# use the TVD pluging
return nsx_plugin
else:
if selected_plugin:
LOG.error('Cannot select plugin. The current plugin is %s',
nsx_plugin)
sys.exit(1)
# use the TVD pluging
return nsx_plugin
if selected_plugin:
LOG.error('Cannot select plugin. The current plugin is %s',
nsx_plugin)
sys.exit(1)
return nsx_plugin
def main(argv=sys.argv[1:]):
_init_cfg()

View File

@ -316,9 +316,9 @@ def _get_choices():
plugin = get_plugin()
if plugin == 'nsxv3':
return nsxv3_resources_names
elif plugin == 'nsxv':
if plugin == 'nsxv':
return nsxv_resources_names
elif plugin == 'nsxtvd':
if plugin == 'nsxtvd':
return nsxtvd_resources_names
@ -326,9 +326,9 @@ def _get_resources():
plugin = get_plugin()
if plugin == 'nsxv3':
return 'NSX-V3 resources: %s' % (', '.join(nsxv3_resources_names))
elif plugin == 'nsxv':
if plugin == 'nsxv':
return 'NSX-V resources: %s' % (', '.join(nsxv_resources_names))
elif plugin == 'nsxtvd':
if plugin == 'nsxtvd':
return 'NSX-TVD resources: %s' % (', '.join(nsxtvd_resources_names))