From b6bd7e49d1cf185f363fb2722286ec5d9f4e4620 Mon Sep 17 00:00:00 2001 From: asarfaty Date: Wed, 30 Sep 2020 10:32:46 +0200 Subject: [PATCH] Remove some pylint exclusions Change-Id: I6909c10471039f1e68224679ceeb2867ab5a3a47 --- .pylintrc | 6 -- vmware_nsx/api_client/base.py | 2 +- vmware_nsx/api_client/eventlet_request.py | 3 +- vmware_nsx/api_client/request.py | 11 ++-- vmware_nsx/common/locking.py | 13 ++-- vmware_nsx/common/utils.py | 6 +- .../db/migration/alembic_migrations/env.py | 3 +- vmware_nsx/db/nsxv_db.py | 2 +- vmware_nsx/dhcp_meta/migration.py | 7 +-- vmware_nsx/dvs/dvs.py | 13 ++-- .../extensions/advancedserviceproviders.py | 3 +- vmware_nsx/extensions/api_replay.py | 3 +- .../edge_service_gateway_bgp_peer.py | 3 +- vmware_nsx/extensions/housekeeper.py | 3 +- vmware_nsx/extensions/lsn.py | 3 +- vmware_nsx/extensions/maclearning.py | 3 +- vmware_nsx/extensions/nsxpolicy.py | 3 +- vmware_nsx/extensions/projectpluginmap.py | 3 +- .../extensions/providersecuritygroup.py | 3 +- vmware_nsx/extensions/routertype.py | 3 +- .../secgroup_rule_local_ip_prefix.py | 3 +- vmware_nsx/extensions/securitygrouplogging.py | 3 +- vmware_nsx/extensions/securitygrouppolicy.py | 3 +- vmware_nsx/extensions/vnicindex.py | 3 +- vmware_nsx/nsxlib/mh/switch.py | 3 +- .../plugins/common/housekeeper/housekeeper.py | 9 ++- vmware_nsx/plugins/common_v3/plugin.py | 11 ++-- vmware_nsx/plugins/dvs/plugin.py | 7 +-- vmware_nsx/plugins/nsx/plugin.py | 35 +++++------ vmware_nsx/plugins/nsx/utils.py | 3 +- vmware_nsx/plugins/nsx_p/plugin.py | 19 +++--- .../nsx_v/drivers/shared_router_driver.py | 35 ++++++----- vmware_nsx/plugins/nsx_v/md_proxy.py | 3 +- vmware_nsx/plugins/nsx_v/plugin.py | 16 +++-- .../nsx_v/vshield/edge_firewall_driver.py | 30 ++++----- .../plugins/nsx_v/vshield/edge_utils.py | 61 +++++++++---------- .../plugins/nsx_v/vshield/tasks/tasks.py | 6 +- vmware_nsx/plugins/nsx_v/vshield/vcns.py | 3 +- vmware_nsx/plugins/nsx_v3/plugin.py | 5 +- .../fwaas/nsx_v3/edge_fwaas_driver_v2.py | 2 +- vmware_nsx/services/ipam/nsx_v/driver.py | 11 ++-- .../lbaas/nsx_p/implementation/lb_utils.py | 27 ++++---- .../lbaas/nsx_p/implementation/member_mgr.py | 7 +-- .../nsx_v/implementation/loadbalancer_mgr.py | 22 +++---- .../lbaas/nsx_v3/implementation/lb_utils.py | 47 +++++++------- .../lbaas/nsx_v3/implementation/member_mgr.py | 7 +-- .../vpnaas/common_v3/ipsec_validator.py | 7 +-- .../services/vpnaas/nsxp/ipsec_driver.py | 2 +- .../services/vpnaas/nsxv3/ipsec_driver.py | 2 +- .../shell/admin/plugins/common/formatters.py | 2 +- .../shell/admin/plugins/common/utils.py | 7 +-- .../admin/plugins/nsxtvd/resources/migrate.py | 13 ++-- .../plugins/nsxv/resources/dhcp_binding.py | 35 ++++++----- .../admin/plugins/nsxv/resources/edges.py | 29 ++++----- .../admin/plugins/nsxv/resources/metadata.py | 13 ++-- .../admin/plugins/nsxv/resources/routers.py | 5 +- .../nsxv/resources/spoofguard_policy.py | 3 +- .../plugins/nsxv3/resources/migration.py | 6 +- .../admin/plugins/nsxv3/resources/ports.py | 3 +- .../plugins/nsxv3/resources/securitygroups.py | 11 ++-- vmware_nsx/shell/nsxadmin.py | 15 +++-- vmware_nsx/shell/resources.py | 8 +-- 62 files changed, 276 insertions(+), 362 deletions(-) diff --git a/.pylintrc b/.pylintrc index 16245833e2..6d073eaa95 100644 --- a/.pylintrc +++ b/.pylintrc @@ -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, diff --git a/vmware_nsx/api_client/base.py b/vmware_nsx/api_client/base.py index a1cb71f9fa..55b0075380 100644 --- a/vmware_nsx/api_client/base.py +++ b/vmware_nsx/api_client/base.py @@ -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 diff --git a/vmware_nsx/api_client/eventlet_request.py b/vmware_nsx/api_client/eventlet_request.py index 81ddfd95c5..54f43c1d87 100644 --- a/vmware_nsx/api_client/eventlet_request.py +++ b/vmware_nsx/api_client/eventlet_request.py @@ -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.''' diff --git a/vmware_nsx/api_client/request.py b/vmware_nsx/api_client/request.py index 93fca2a382..a1fe1be415 100644 --- a/vmware_nsx/api_client/request.py +++ b/vmware_nsx/api_client/request.py @@ -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}) diff --git a/vmware_nsx/common/locking.py b/vmware_nsx/common/locking.py index 80c4eaf65b..c71c35184e 100644 --- a/vmware_nsx/common/locking.py +++ b/vmware_nsx/common/locking.py @@ -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): diff --git a/vmware_nsx/common/utils.py b/vmware_nsx/common/utils.py index d224e3209c..ebce78f7cf 100644 --- a/vmware_nsx/common/utils.py +++ b/vmware_nsx/common/utils.py @@ -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): diff --git a/vmware_nsx/db/migration/alembic_migrations/env.py b/vmware_nsx/db/migration/alembic_migrations/env.py index 3522d7c022..ecd2bd0e7d 100644 --- a/vmware_nsx/db/migration/alembic_migrations/env.py +++ b/vmware_nsx/db/migration/alembic_migrations/env.py @@ -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(): diff --git a/vmware_nsx/db/nsxv_db.py b/vmware_nsx/db/nsxv_db.py index 2cba440668..d43769586d 100644 --- a/vmware_nsx/db/nsxv_db.py +++ b/vmware_nsx/db/nsxv_db.py @@ -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). diff --git a/vmware_nsx/dhcp_meta/migration.py b/vmware_nsx/dhcp_meta/migration.py index c7853cc879..2df758c6cd 100644 --- a/vmware_nsx/dhcp_meta/migration.py +++ b/vmware_nsx/dhcp_meta/migration.py @@ -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.""" diff --git a/vmware_nsx/dvs/dvs.py b/vmware_nsx/dvs/dvs.py index 3071c37100..80f28538e8 100644 --- a/vmware_nsx/dvs/dvs.py +++ b/vmware_nsx/dvs/dvs.py @@ -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 diff --git a/vmware_nsx/extensions/advancedserviceproviders.py b/vmware_nsx/extensions/advancedserviceproviders.py index cd2bf4e043..a862110b52 100644 --- a/vmware_nsx/extensions/advancedserviceproviders.py +++ b/vmware_nsx/extensions/advancedserviceproviders.py @@ -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 {} diff --git a/vmware_nsx/extensions/api_replay.py b/vmware_nsx/extensions/api_replay.py index ad3c38a392..4871733f18 100644 --- a/vmware_nsx/extensions/api_replay.py +++ b/vmware_nsx/extensions/api_replay.py @@ -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 diff --git a/vmware_nsx/extensions/edge_service_gateway_bgp_peer.py b/vmware_nsx/extensions/edge_service_gateway_bgp_peer.py index 79811ef596..4d01ee20a4 100644 --- a/vmware_nsx/extensions/edge_service_gateway_bgp_peer.py +++ b/vmware_nsx/extensions/edge_service_gateway_bgp_peer.py @@ -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 {} diff --git a/vmware_nsx/extensions/housekeeper.py b/vmware_nsx/extensions/housekeeper.py index cab157dcd8..beda08230d 100644 --- a/vmware_nsx/extensions/housekeeper.py +++ b/vmware_nsx/extensions/housekeeper.py @@ -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): diff --git a/vmware_nsx/extensions/lsn.py b/vmware_nsx/extensions/lsn.py index 2fb35c5c96..1ec13b231e 100644 --- a/vmware_nsx/extensions/lsn.py +++ b/vmware_nsx/extensions/lsn.py @@ -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 {} diff --git a/vmware_nsx/extensions/maclearning.py b/vmware_nsx/extensions/maclearning.py index 54bdea325d..5a12445f46 100644 --- a/vmware_nsx/extensions/maclearning.py +++ b/vmware_nsx/extensions/maclearning.py @@ -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 {} diff --git a/vmware_nsx/extensions/nsxpolicy.py b/vmware_nsx/extensions/nsxpolicy.py index 11f70b45f2..9565503990 100644 --- a/vmware_nsx/extensions/nsxpolicy.py +++ b/vmware_nsx/extensions/nsxpolicy.py @@ -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): diff --git a/vmware_nsx/extensions/projectpluginmap.py b/vmware_nsx/extensions/projectpluginmap.py index ce4e0b115c..40f1644b68 100644 --- a/vmware_nsx/extensions/projectpluginmap.py +++ b/vmware_nsx/extensions/projectpluginmap.py @@ -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): diff --git a/vmware_nsx/extensions/providersecuritygroup.py b/vmware_nsx/extensions/providersecuritygroup.py index 558270c0f2..4b94356c72 100644 --- a/vmware_nsx/extensions/providersecuritygroup.py +++ b/vmware_nsx/extensions/providersecuritygroup.py @@ -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 {} diff --git a/vmware_nsx/extensions/routertype.py b/vmware_nsx/extensions/routertype.py index 2a55399695..0525300e8d 100644 --- a/vmware_nsx/extensions/routertype.py +++ b/vmware_nsx/extensions/routertype.py @@ -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 {} diff --git a/vmware_nsx/extensions/secgroup_rule_local_ip_prefix.py b/vmware_nsx/extensions/secgroup_rule_local_ip_prefix.py index 0c99080588..88f1088746 100644 --- a/vmware_nsx/extensions/secgroup_rule_local_ip_prefix.py +++ b/vmware_nsx/extensions/secgroup_rule_local_ip_prefix.py @@ -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 {} diff --git a/vmware_nsx/extensions/securitygrouplogging.py b/vmware_nsx/extensions/securitygrouplogging.py index 951e28629a..2f77c40905 100644 --- a/vmware_nsx/extensions/securitygrouplogging.py +++ b/vmware_nsx/extensions/securitygrouplogging.py @@ -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 {} diff --git a/vmware_nsx/extensions/securitygrouppolicy.py b/vmware_nsx/extensions/securitygrouppolicy.py index f00e70b848..4796e9380c 100644 --- a/vmware_nsx/extensions/securitygrouppolicy.py +++ b/vmware_nsx/extensions/securitygrouppolicy.py @@ -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 {} diff --git a/vmware_nsx/extensions/vnicindex.py b/vmware_nsx/extensions/vnicindex.py index 55e752ef2b..90c5434d8c 100644 --- a/vmware_nsx/extensions/vnicindex.py +++ b/vmware_nsx/extensions/vnicindex.py @@ -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 {} diff --git a/vmware_nsx/nsxlib/mh/switch.py b/vmware_nsx/nsxlib/mh/switch.py index 05b06c1714..a4ff980ade 100644 --- a/vmware_nsx/nsxlib/mh/switch.py +++ b/vmware_nsx/nsxlib/mh/switch.py @@ -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 diff --git a/vmware_nsx/plugins/common/housekeeper/housekeeper.py b/vmware_nsx/plugins/common/housekeeper/housekeeper.py index f8503bfcc1..470cbfde05 100644 --- a/vmware_nsx/plugins/common/housekeeper/housekeeper.py +++ b/vmware_nsx/plugins/common/housekeeper/housekeeper.py @@ -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 = {} diff --git a/vmware_nsx/plugins/common_v3/plugin.py b/vmware_nsx/plugins/common_v3/plugin.py index 8eb04646eb..6b245d7a46 100644 --- a/vmware_nsx/plugins/common_v3/plugin.py +++ b/vmware_nsx/plugins/common_v3/plugin.py @@ -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""" diff --git a/vmware_nsx/plugins/dvs/plugin.py b/vmware_nsx/plugins/dvs/plugin.py index 1812ce0bfa..48798dcd31 100644 --- a/vmware_nsx/plugins/dvs/plugin.py +++ b/vmware_nsx/plugins/dvs/plugin.py @@ -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)): diff --git a/vmware_nsx/plugins/nsx/plugin.py b/vmware_nsx/plugins/nsx/plugin.py index b252417892..b3b32284b3 100644 --- a/vmware_nsx/plugins/nsx/plugin.py +++ b/vmware_nsx/plugins/nsx/plugin.py @@ -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, diff --git a/vmware_nsx/plugins/nsx/utils.py b/vmware_nsx/plugins/nsx/utils.py index 8bf68f3a58..c941004cac 100644 --- a/vmware_nsx/plugins/nsx/utils.py +++ b/vmware_nsx/plugins/nsx/utils.py @@ -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) diff --git a/vmware_nsx/plugins/nsx_p/plugin.py b/vmware_nsx/plugins/nsx_p/plugin.py index f4fec9c6f5..cddc59cfa4 100644 --- a/vmware_nsx/plugins/nsx_p/plugin.py +++ b/vmware_nsx/plugins/nsx_p/plugin.py @@ -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 diff --git a/vmware_nsx/plugins/nsx_v/drivers/shared_router_driver.py b/vmware_nsx/plugins/nsx_v/drivers/shared_router_driver.py index 4ba4c31964..9e2b024c18 100644 --- a/vmware_nsx/plugins/nsx_v/drivers/shared_router_driver.py +++ b/vmware_nsx/plugins/nsx_v/drivers/shared_router_driver.py @@ -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) diff --git a/vmware_nsx/plugins/nsx_v/md_proxy.py b/vmware_nsx/plugins/nsx_v/md_proxy.py index 1ec6f1c2a5..c8201cf5ed 100644 --- a/vmware_nsx/plugins/nsx_v/md_proxy.py +++ b/vmware_nsx/plugins/nsx_v/md_proxy.py @@ -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( diff --git a/vmware_nsx/plugins/nsx_v/plugin.py b/vmware_nsx/plugins/nsx_v/plugin.py index 0933c30f8b..bcdc805932 100644 --- a/vmware_nsx/plugins/nsx_v/plugin.py +++ b/vmware_nsx/plugins/nsx_v/plugin.py @@ -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( diff --git a/vmware_nsx/plugins/nsx_v/vshield/edge_firewall_driver.py b/vmware_nsx/plugins/nsx_v/vshield/edge_firewall_driver.py index d916548ea9..3f21564104 100644 --- a/vmware_nsx/plugins/nsx_v/vshield/edge_firewall_driver.py +++ b/vmware_nsx/plugins/nsx_v/vshield/edge_firewall_driver.py @@ -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( diff --git a/vmware_nsx/plugins/nsx_v/vshield/edge_utils.py b/vmware_nsx/plugins/nsx_v/vshield/edge_utils.py index a4caf8baad..18306d361e 100644 --- a/vmware_nsx/plugins/nsx_v/vshield/edge_utils.py +++ b/vmware_nsx/plugins/nsx_v/vshield/edge_utils.py @@ -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): diff --git a/vmware_nsx/plugins/nsx_v/vshield/tasks/tasks.py b/vmware_nsx/plugins/nsx_v/vshield/tasks/tasks.py index f2f7d4e3bb..2b01442899 100644 --- a/vmware_nsx/plugins/nsx_v/vshield/tasks/tasks.py +++ b/vmware_nsx/plugins/nsx_v/vshield/tasks/tasks.py @@ -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: diff --git a/vmware_nsx/plugins/nsx_v/vshield/vcns.py b/vmware_nsx/plugins/nsx_v/vshield/vcns.py index 9e839e9e11..b7c9e8f473 100644 --- a/vmware_nsx/plugins/nsx_v/vshield/vcns.py +++ b/vmware_nsx/plugins/nsx_v/vshield/vcns.py @@ -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) diff --git a/vmware_nsx/plugins/nsx_v3/plugin.py b/vmware_nsx/plugins/nsx_v3/plugin.py index cdd3676fc9..670e9a8421 100644 --- a/vmware_nsx/plugins/nsx_v3/plugin.py +++ b/vmware_nsx/plugins/nsx_v3/plugin.py @@ -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, diff --git a/vmware_nsx/services/fwaas/nsx_v3/edge_fwaas_driver_v2.py b/vmware_nsx/services/fwaas/nsx_v3/edge_fwaas_driver_v2.py index 1115d60cbf..ec5f73c16d 100644 --- a/vmware_nsx/services/fwaas/nsx_v3/edge_fwaas_driver_v2.py +++ b/vmware_nsx/services/fwaas/nsx_v3/edge_fwaas_driver_v2.py @@ -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( diff --git a/vmware_nsx/services/ipam/nsx_v/driver.py b/vmware_nsx/services/ipam/nsx_v/driver.py index 7add0da2ab..a5793ff787 100644 --- a/vmware_nsx/services/ipam/nsx_v/driver.py +++ b/vmware_nsx/services/ipam/nsx_v/driver.py @@ -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""" diff --git a/vmware_nsx/services/lbaas/nsx_p/implementation/lb_utils.py b/vmware_nsx/services/lbaas/nsx_p/implementation/lb_utils.py index 70195816bc..6a417404aa 100644 --- a/vmware_nsx/services/lbaas/nsx_p/implementation/lb_utils.py +++ b/vmware_nsx/services/lbaas/nsx_p/implementation/lb_utils.py @@ -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): diff --git a/vmware_nsx/services/lbaas/nsx_p/implementation/member_mgr.py b/vmware_nsx/services/lbaas/nsx_p/implementation/member_mgr.py index 438af68c37..82f8bec5f8 100644 --- a/vmware_nsx/services/lbaas/nsx_p/implementation/member_mgr.py +++ b/vmware_nsx/services/lbaas/nsx_p/implementation/member_mgr.py @@ -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'] diff --git a/vmware_nsx/services/lbaas/nsx_v/implementation/loadbalancer_mgr.py b/vmware_nsx/services/lbaas/nsx_v/implementation/loadbalancer_mgr.py index 333a24c1d3..00c0e09164 100644 --- a/vmware_nsx/services/lbaas/nsx_v/implementation/loadbalancer_mgr.py +++ b/vmware_nsx/services/lbaas/nsx_v/implementation/loadbalancer_mgr.py @@ -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'] diff --git a/vmware_nsx/services/lbaas/nsx_v3/implementation/lb_utils.py b/vmware_nsx/services/lbaas/nsx_v3/implementation/lb_utils.py index 7e688e7dd1..9c0194b85e 100644 --- a/vmware_nsx/services/lbaas/nsx_v3/implementation/lb_utils.py +++ b/vmware_nsx/services/lbaas/nsx_v3/implementation/lb_utils.py @@ -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 " diff --git a/vmware_nsx/services/lbaas/nsx_v3/implementation/member_mgr.py b/vmware_nsx/services/lbaas/nsx_v3/implementation/member_mgr.py index 4421c62eef..3b8a6cca33 100644 --- a/vmware_nsx/services/lbaas/nsx_v3/implementation/member_mgr.py +++ b/vmware_nsx/services/lbaas/nsx_v3/implementation/member_mgr.py @@ -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( diff --git a/vmware_nsx/services/vpnaas/common_v3/ipsec_validator.py b/vmware_nsx/services/vpnaas/common_v3/ipsec_validator.py index 5d8c8757f7..6cdaf690fd 100644 --- a/vmware_nsx/services/vpnaas/common_v3/ipsec_validator.py +++ b/vmware_nsx/services/vpnaas/common_v3/ipsec_validator.py @@ -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 diff --git a/vmware_nsx/services/vpnaas/nsxp/ipsec_driver.py b/vmware_nsx/services/vpnaas/nsxp/ipsec_driver.py index cdbd7136f7..998628b288 100644 --- a/vmware_nsx/services/vpnaas/nsxp/ipsec_driver.py +++ b/vmware_nsx/services/vpnaas/nsxp/ipsec_driver.py @@ -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", diff --git a/vmware_nsx/services/vpnaas/nsxv3/ipsec_driver.py b/vmware_nsx/services/vpnaas/nsxv3/ipsec_driver.py index dc87ecc497..0826093049 100644 --- a/vmware_nsx/services/vpnaas/nsxv3/ipsec_driver.py +++ b/vmware_nsx/services/vpnaas/nsxv3/ipsec_driver.py @@ -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): diff --git a/vmware_nsx/shell/admin/plugins/common/formatters.py b/vmware_nsx/shell/admin/plugins/common/formatters.py index 6757a41c76..3bed217120 100644 --- a/vmware_nsx/shell/admin/plugins/common/formatters.py +++ b/vmware_nsx/shell/admin/plugins/common/formatters.py @@ -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: diff --git a/vmware_nsx/shell/admin/plugins/common/utils.py b/vmware_nsx/shell/admin/plugins/common/utils.py index 3520b0fd00..5c91e65119 100644 --- a/vmware_nsx/shell/admin/plugins/common/utils.py +++ b/vmware_nsx/shell/admin/plugins/common/utils.py @@ -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): diff --git a/vmware_nsx/shell/admin/plugins/nsxtvd/resources/migrate.py b/vmware_nsx/shell/admin/plugins/nsxtvd/resources/migrate.py index a61d6d939a..da1fa8a685 100644 --- a/vmware_nsx/shell/admin/plugins/nsxtvd/resources/migrate.py +++ b/vmware_nsx/shell/admin/plugins/nsxtvd/resources/migrate.py @@ -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 diff --git a/vmware_nsx/shell/admin/plugins/nsxv/resources/dhcp_binding.py b/vmware_nsx/shell/admin/plugins/nsxv/resources/dhcp_binding.py index b0c0b0ceda..c2dbc5fb85 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv/resources/dhcp_binding.py +++ b/vmware_nsx/shell/admin/plugins/nsxv/resources/dhcp_binding.py @@ -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): diff --git a/vmware_nsx/shell/admin/plugins/nsxv/resources/edges.py b/vmware_nsx/shell/admin/plugins/nsxv/resources/edges.py index 885f91e9bb..609ac98940 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv/resources/edges.py +++ b/vmware_nsx/shell/admin/plugins/nsxv/resources/edges.py @@ -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(): diff --git a/vmware_nsx/shell/admin/plugins/nsxv/resources/metadata.py b/vmware_nsx/shell/admin/plugins/nsxv/resources/metadata.py index dee84d9ddf..f53e2bc501 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv/resources/metadata.py +++ b/vmware_nsx/shell/admin/plugins/nsxv/resources/metadata.py @@ -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) diff --git a/vmware_nsx/shell/admin/plugins/nsxv/resources/routers.py b/vmware_nsx/shell/admin/plugins/nsxv/resources/routers.py index efb4740caf..bc498791fd 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv/resources/routers.py +++ b/vmware_nsx/shell/admin/plugins/nsxv/resources/routers.py @@ -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 diff --git a/vmware_nsx/shell/admin/plugins/nsxv/resources/spoofguard_policy.py b/vmware_nsx/shell/admin/plugins/nsxv/resources/spoofguard_policy.py index 118ab5907f..97fba3a9b9 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv/resources/spoofguard_policy.py +++ b/vmware_nsx/shell/admin/plugins/nsxv/resources/spoofguard_policy.py @@ -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 diff --git a/vmware_nsx/shell/admin/plugins/nsxv3/resources/migration.py b/vmware_nsx/shell/admin/plugins/nsxv3/resources/migration.py index 8857c31cb5..fdab08af93 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv3/resources/migration.py +++ b/vmware_nsx/shell/admin/plugins/nsxv3/resources/migration.py @@ -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, diff --git a/vmware_nsx/shell/admin/plugins/nsxv3/resources/ports.py b/vmware_nsx/shell/admin/plugins/nsxv3/resources/ports.py index 2f9aaec929..e6f78d6108 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv3/resources/ports.py +++ b/vmware_nsx/shell/admin/plugins/nsxv3/resources/ports.py @@ -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 diff --git a/vmware_nsx/shell/admin/plugins/nsxv3/resources/securitygroups.py b/vmware_nsx/shell/admin/plugins/nsxv3/resources/securitygroups.py index 0d0fa33bad..52d4ab6a11 100644 --- a/vmware_nsx/shell/admin/plugins/nsxv3/resources/securitygroups.py +++ b/vmware_nsx/shell/admin/plugins/nsxv3/resources/securitygroups.py @@ -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', diff --git a/vmware_nsx/shell/nsxadmin.py b/vmware_nsx/shell/nsxadmin.py index 6fd575c3ba..d7e0fd187c 100644 --- a/vmware_nsx/shell/nsxadmin.py +++ b/vmware_nsx/shell/nsxadmin.py @@ -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() diff --git a/vmware_nsx/shell/resources.py b/vmware_nsx/shell/resources.py index 6fda8a9f7e..7ec9d8c213 100644 --- a/vmware_nsx/shell/resources.py +++ b/vmware_nsx/shell/resources.py @@ -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))