from quantum import manager
from quantum.openstack.common import importutils
from quantum.openstack.common import jsonutils
-from quantum.openstack.common import log as logging
from quantum.openstack.common import lockutils
+from quantum.openstack.common import log as logging
from quantum.openstack.common import loopingcall
from quantum.openstack.common.rpc import proxy
from quantum.openstack.common import service
self._populate_networks_cache()
def _populate_networks_cache(self):
- """Populate the networks cache when the DHCP-agent starts"""
+ """Populate the networks cache when the DHCP-agent starts."""
try:
existing_networks = self.dhcp_driver_cls.existing_dhcp_networks(
try:
self.plugin_rpc.update_lease_expiration(network_id, ip_address,
time_remaining)
- except:
+ except Exception:
self.needs_resync = True
LOG.exception(_('Unable to update lease'))
for network_id in active_networks:
self.refresh_dhcp_helper(network_id)
- except:
+ except Exception:
self.needs_resync = True
LOG.exception(_('Unable to sync network state.'))
"""Enable DHCP for a network that meets enabling criteria."""
try:
network = self.plugin_rpc.get_network_info(network_id)
- except:
+ except Exception:
self.needs_resync = True
LOG.exception(_('Network %s RPC info call failed.'), network_id)
return
try:
network = self.plugin_rpc.get_network_info(network_id)
- except:
+ except Exception:
self.needs_resync = True
LOG.exception(_('Network %s RPC info call failed.'), network_id)
return
try:
self.driver = importutils.import_object(conf.interface_driver,
conf)
- except:
+ except Exception:
msg = _("Error importing interface driver "
"'%s'") % conf.interface_driver
raise SystemExit(msg)
class FirewallDriver(object):
- """ Firewall Driver base class.
+ """Firewall Driver base class.
Defines methods that any driver providing security groups
and provider firewall functionality should implement.
raise NotImplementedError()
def remove_port_filter(self, port):
- """Stop filtering port"""
+ """Stop filtering port."""
raise NotImplementedError()
def filter_defer_apply_on(self):
- """Defer application of filtering rule"""
+ """Defer application of filtering rule."""
pass
def filter_defer_apply_off(self):
- """Turn off deferral of rules and apply the rules now"""
+ """Turn off deferral of rules and apply the rules now."""
pass
@property
def ports(self):
- """ returns filterd ports"""
+ """Returns filtered ports."""
pass
@contextlib.contextmanager
def defer_apply(self):
- """defer apply context"""
+ """Defer apply context."""
self.filter_defer_apply_on()
try:
yield
class NoopFirewallDriver(FirewallDriver):
- """ Noop Firewall Driver.
+ """Noop Firewall Driver.
Firewall driver which does nothing.
This driver is for disabling the firewall functionality.
try:
self.driver = importutils.import_object(self.conf.interface_driver,
self.conf)
- except:
+ except Exception:
msg = _("Error importing interface driver "
"'%s'") % self.conf.interface_driver
raise SystemExit(msg)
try:
self._destroy_router_namespace(ns)
- except:
+ except Exception:
LOG.exception(_("Failed deleting namespace '%s'"), ns)
def _destroy_router_namespace(self, namespace):
bridge=self.conf.external_network_bridge,
namespace=namespace,
prefix=EXTERNAL_DEV_PREFIX)
- #(TODO) Address the failure for the deletion of the namespace
+ #TODO(garyk) Address the failure for the deletion of the namespace
def _create_router_namespace(self, ri):
ip_wrapper_root = ip_lib.IPWrapper(self.root_helper)
ip_wrapper.netns.execute(['sysctl', '-w', 'net.ipv4.ip_forward=1'])
def _fetch_external_net_id(self):
- """Find UUID of single external network for this agent"""
+ """Find UUID of single external network for this agent."""
if self.conf.gateway_external_network_id:
return self.conf.gateway_external_network_id
try:
os.remove(str(self.pidfile))
def start(self):
- """ Start the daemon """
+ """Start the daemon."""
if self.pidfile.is_running():
self.pidfile.unlock()
@classmethod
def existing_dhcp_networks(cls, conf, root_helper):
- """Return a list of existing networks ids (ones we have configs for)"""
+ """Return a list of existing networks ids that we have configs for."""
raise NotImplementedError
@classmethod
def existing_dhcp_networks(cls, conf, root_helper):
- """Return a list of existing networks ids (ones we have configs for)"""
+ """Return a list of existing networks ids that we have configs for."""
confs_dir = os.path.abspath(os.path.normpath(conf.dhcp_confs))
if subnet.ip_version == 4:
mode = 'static'
else:
- # TODO (mark): how do we indicate other options
+ # TODO(mark): how do we indicate other options
# ra-only, slaac, ra-nameservers, and ra-stateless.
mode = 'static'
cmd.append('--dhcp-range=set:%s,%s,%s,%ss' %
for device_route_line in device_route_list_lines:
try:
subnet = device_route_line.split()[0]
- except:
+ except Exception:
continue
subnet_route_list_lines = self._run('list', 'proto', 'kernel',
'match', subnet).split('\n')
while(i.next() != 'src'):
pass
src = i.next()
- except:
+ except Exception:
src = ''
if device != interface_name:
device_list.append((device, src))
self.iptables.apply()
def _setup_chains(self):
- """Setup ingress and egress chain for a port. """
+ """Setup ingress and egress chain for a port."""
self._add_chain_by_name_v4v6(SG_CHAIN)
for port in self.filtered_ports.values():
self._setup_chain(port, INGRESS_DIRECTION)
self.iptables.ipv6['filter'].add_rule(SG_CHAIN, '-j ACCEPT')
def _remove_chains(self):
- """Remove ingress and egress chain for a port"""
+ """Remove ingress and egress chain for a port."""
for port in self.filtered_ports.values():
self._remove_chain(port, INGRESS_DIRECTION)
self._remove_chain(port, EGRESS_DIRECTION)
def collect_quantum_ports(bridges, root_helper):
- """Collect ports created by Quantum from OVS"""
+ """Collect ports created by Quantum from OVS."""
ports = []
for bridge in bridges:
ovs = ovs_lib.OVSBridge(bridge, root_helper)
sg_agent = None
def security_groups_rule_updated(self, context, **kwargs):
- """ callback for security group rule update
+ """Callback for security group rule update.
:param security_groups: list of updated security_groups
"""
self.sg_agent.security_groups_rule_updated(security_groups)
def security_groups_member_updated(self, context, **kwargs):
- """ callback for security group member update
+ """Callback for security group member update.
:param security_groups: list of updated security_groups
"""
self.sg_agent.security_groups_member_updated(security_groups)
def security_groups_provider_updated(self, context, **kwargs):
- """ callback for security group provider update
-
- """
+ """Callback for security group provider update."""
LOG.debug(_("Provider rule updated"))
self.sg_agent.security_groups_provider_updated()
topics.UPDATE)
def security_groups_rule_updated(self, context, security_groups):
- """ notify rule updated security groups """
+ """Notify rule updated security groups."""
if not security_groups:
return
self.fanout_cast(context,
topic=self._get_security_group_topic())
def security_groups_member_updated(self, context, security_groups):
- """ notify member updated security groups """
+ """Notify member updated security groups."""
if not security_groups:
return
self.fanout_cast(context,
topic=self._get_security_group_topic())
def security_groups_provider_updated(self, context):
- """ notify provider updated security groups """
+ """Notify provider updated security groups."""
self.fanout_cast(context,
self.make_msg('security_groups_provider_updated'),
version=SG_RPC_VERSION,
def list_args(request, arg):
- """Extracts the list of arg from request"""
+ """Extracts the list of arg from request."""
return [v for v in request.GET.getall(arg) if v]
class QuantumController(object):
- """ Base controller class for Quantum API """
+ """Base controller class for Quantum API."""
# _resource_name will be redefined in sub concrete controller
_resource_name = None
super(QuantumController, self).__init__()
def _prepare_request_body(self, body, params):
- """ verifies required parameters are in request body.
+ """Verifies required parameters are in request body.
sets default value for missing optional parameters.
body argument must be the deserialized body
def _check_extension(self, extension):
"""Checks if any of plugins supports extension and implements the
- extension contract."""
+ extension contract.
+ """
extension_is_valid = super(PluginAwareExtensionManager,
self)._check_extension(extension)
return (extension_is_valid and
dhcp_agent in dhcp_agents]
def _notification_host(self, context, method, payload, host):
- """Notify the agent on host"""
+ """Notify the agent on host."""
self.cast(
context, self.make_msg(method,
payload=payload),
topic='%s.%s' % (topics.DHCP_AGENT, host))
def _notification(self, context, method, payload, network_id):
- """Notify all the agents that are hosting the network"""
+ """Notify all the agents that are hosting the network."""
plugin = manager.QuantumManager.get_plugin()
if (method != 'network_delete_end' and utils.is_extension_supported(
plugin, constants.AGENT_SCHEDULER_EXT_ALIAS)):
self._notification_fanout(context, method, payload)
def _notification_fanout(self, context, method, payload):
- """Fanout the payload to all dhcp agents"""
+ """Fanout the payload to all dhcp agents."""
self.fanout_cast(
context, self.make_msg(method,
payload=payload),
topic=topic, default_version=self.BASE_RPC_API_VERSION)
def _notification_host(self, context, method, payload, host):
- """Notify the agent that is hosting the router"""
+ """Notify the agent that is hosting the router."""
LOG.debug(_('Nofity agent at %(host)s the message '
'%(method)s'), {'host': host,
'method': method})
topic='%s.%s' % (l3_agent.topic, l3_agent.host))
def _notification(self, context, method, routers, operation, data):
- """Notify all the agents that are hosting the routers"""
+ """Notify all the agents that are hosting the routers."""
plugin = manager.QuantumManager.get_plugin()
if utils.is_extension_supported(
plugin, constants.AGENT_SCHEDULER_EXT_ALIAS):
topic=topics.L3_AGENT)
def _notification_fanout(self, context, method, router_id):
- """Fanout the deleted router to all L3 agents"""
+ """Fanout the deleted router to all L3 agents."""
LOG.debug(_('Fanout notify agent at %(topic)s the message '
'%(method)s on router %(router_id)s'),
{'topic': topics.DHCP_AGENT,
def _verify_dict_keys(expected_keys, target_dict, strict=True):
- """ Allows to verify keys in a dictionary.
+ """Allows to verify keys in a dictionary.
:param expected_keys: A list of keys expected to be present.
:param target_dict: The dictionary which should be verified.
:param strict: Specifies whether additional keys are allowed to be present.
return api_common.NoSortingHelper(request, self._attr_info)
def _items(self, request, do_authz=False, parent_id=None):
- """Retrieves and formats a list of elements of the requested entity"""
+ """Retrieves and formats a list of elements of the requested entity."""
# NOTE(salvatore-orlando): The following ensures that fields which
# are needed for authZ policy validation are not stripped away by the
# plugin before returning.
def _item(self, request, id, do_authz=False, field_list=None,
parent_id=None):
- """Retrieves and formats a single element of the requested entity"""
+ """Retrieves and formats a single element of the requested entity."""
kwargs = {'fields': field_list}
action = self._plugin_handlers[self.SHOW]
if parent_id:
self._dhcp_agent_notifier.notify(context, data, methodname)
def index(self, request, **kwargs):
- """Returns a list of the requested entity"""
+ """Returns a list of the requested entity."""
parent_id = kwargs.get(self._parent_id_name)
return self._items(request, True, parent_id)
def show(self, request, id, **kwargs):
- """Returns detailed information about the requested entity"""
+ """Returns detailed information about the requested entity."""
try:
# NOTE(salvatore-orlando): The following ensures that fields
# which are needed for authZ policy validation are not stripped
raise ex
def create(self, request, body=None, **kwargs):
- """Creates a new instance of the requested entity"""
+ """Creates a new instance of the requested entity."""
parent_id = kwargs.get(self._parent_id_name)
notifier_api.notify(request.context,
self._publisher_id,
return notify({self._resource: self._view(obj)})
def delete(self, request, id, **kwargs):
- """Deletes the specified entity"""
+ """Deletes the specified entity."""
notifier_api.notify(request.context,
self._publisher_id,
self._resource + '.delete.start',
notifier_method)
def update(self, request, id, body=None, **kwargs):
- """Updates the specified entity's attributes"""
+ """Updates the specified entity's attributes."""
parent_id = kwargs.get(self._parent_id_name)
try:
payload = body.copy()
@staticmethod
def prepare_request_body(context, body, is_create, resource, attr_info,
allow_bulk=False):
- """ verifies required attributes are in request body, and that
+ """Verifies required attributes are in request body, and that
an attribute is only specified if it is allowed for the given
operation (create/update).
Attribute with default values are considered to be
class PluginRpcDispatcher(dispatcher.RpcDispatcher):
"""This class is used to convert RPC common context into
- Quantum Context."""
+ Quantum Context.
+ """
def __init__(self, callbacks):
super(PluginRpcDispatcher, self).__init__(callbacks)
except curses.error:
curses.setupterm()
return curses.tigetnum("colors") > 2
- except:
+ except Exception:
raise
# guess false in case of error
return False
def compare_elements(a, b):
- """ compare elements if a and b have same elements
+ """Compare elements if a and b have same elements.
This method doesn't consider ordering
"""
class Agent(model_base.BASEV2, models_v2.HasId):
- """Represents agents running in quantum deployments"""
+ """Represents agents running in quantum deployments."""
# L3 agent, DHCP agent, OVS agent, LinuxBridge
agent_type = sa.Column(sa.String(255), nullable=False)
START_TIME = timeutils.utcnow()
def report_state(self, context, **kwargs):
- """Report state from agent to server. """
+ """Report state from agent to server."""
time = kwargs['time']
time = timeutils.parse_strtime(time)
if self.START_TIME > time:
class NetworkDhcpAgentBinding(model_base.BASEV2):
- """Represents binding between quantum networks and DHCP agents"""
+ """Represents binding between quantum networks and DHCP agents."""
network_id = sa.Column(sa.String(36),
sa.ForeignKey("networks.id", ondelete='CASCADE'),
primary_key=True)
class RouterL3AgentBinding(model_base.BASEV2, models_v2.HasId):
- """Represents binding between quantum routers and L3 agents"""
+ """Represents binding between quantum routers and L3 agents."""
router_id = sa.Column(sa.String(36),
sa.ForeignKey("routers.id", ondelete='CASCADE'))
l3_agent = orm.relation(agents_db.Agent)
def remove_router_from_l3_agent(self, context, id, router_id):
"""Remove the router from l3 agent. After it, the router
will be non-hosted until there is update which
- lead to re schedule or be added to another agent manually."""
+ lead to re schedule or be added to another agent manually.
+ """
agent = self._get_agent(context, id)
with context.session.begin(subtransactions=True):
query = context.session.query(RouterL3AgentBinding)
return l3_agents
def get_l3_agent_candidates(self, sync_router, l3_agents):
- """Get the valid l3 agents for the router from a list of l3_agents"""
+ """Get the valid l3 agents for the router from a list of l3_agents."""
candidates = []
for l3_agent in l3_agents:
if not l3_agent.admin_state_up:
if not sql_connection:
LOG.warn(_("Option 'sql_connection' not specified "
"in any config file - using default "
- "value '%s'" % SQL_CONNECTION_DEFAULT))
+ "value '%s'") % SQL_CONNECTION_DEFAULT)
sql_connection = SQL_CONNECTION_DEFAULT
connection_dict = sql.engine.url.make_url(sql_connection)
engine_args = {
def get_session(autocommit=True, expire_on_commit=False):
- """Helper method to grab session"""
+ """Helper method to grab session."""
global _MAKER, _ENGINE
if not _MAKER:
assert _ENGINE
def register_models(base=BASE):
- """Register Models and create properties"""
+ """Register Models and create properties."""
global _ENGINE
assert _ENGINE
try:
def unregister_models(base=BASE):
- """Unregister Models, useful clearing out data before testing"""
+ """Unregister Models, useful clearing out data before testing."""
global _ENGINE
assert _ENGINE
base.metadata.drop_all(_ENGINE)
class QuantumDbPluginV2(quantum_plugin_base_v2.QuantumPluginBaseV2):
- """ A class that implements the v2 Quantum plugin interface
+ """A class that implements the v2 Quantum plugin interface
using SQLAlchemy models. Whenever a non-read call happens
the plugin will call an event handler class method (e.g.,
network_created()). The result is that this class can be
@classmethod
def register_model_query_hook(cls, model, name, query_hook, filter_hook,
result_filters=None):
- """ register an hook to be invoked when a query is executed.
+ """Register a hook to be invoked when a query is executed.
Add the hooks to the _model_query_hooks dict. Models are the keys
of this dict, whereas the value is another dict mapping hook names to
return self._create_bulk('network', context, networks)
def create_network(self, context, network):
- """ handle creation of a single network """
+ """Handle creation of a single network."""
# single request processing
n = network['network']
# NOTE(jkoelker) Get the tenant_id outside of the session to avoid
return self._create_bulk('subnet', context, subnets)
def _validate_ip_version(self, ip_version, addr, name):
- """Check IP field of a subnet match specified ip version"""
+ """Check IP field of a subnet match specified ip version."""
ip = netaddr.IPNetwork(addr)
if ip.version != ip_version:
msg = _("%(name)s '%(addr)s' does not match "
raise q_exc.InvalidInput(error_message=msg)
def _validate_subnet(self, s):
- """Validate a subnet spec"""
+ """Validate a subnet spec."""
# This method will validate attributes which may change during
# create_subnet() and update_subnet().
def update_subnet(self, context, id, subnet):
"""Update the subnet with new info. The change however will not be
realized until the client renew the dns lease or we support
- gratuitous DHCP offers"""
+ gratuitous DHCP offers
+ """
s = subnet['subnet']
db_subnet = self._get_subnet(context, id)
class ExtraRoute_db_mixin(l3_db.L3_NAT_db_mixin):
- """ Mixin class to support extra route configuration on router"""
+ """Mixin class to support extra route configuration on router."""
def update_router(self, context, id, router):
r = router['router']
with context.session.begin(subtransactions=True):
class L3_NAT_db_mixin(l3.RouterPluginBase):
- """Mixin class to add L3/NAT router methods to db_plugin_base_v2"""
+ """Mixin class to add L3/NAT router methods to db_plugin_base_v2."""
def _network_model_hook(self, context, original_model, query):
query = query.outerjoin(ExternalNetwork,
filters=filters)
def prevent_l3_port_deletion(self, context, port_id):
- """ Checks to make sure a port is allowed to be deleted, raising
+ """Checks to make sure a port is allowed to be deleted, raising
an exception if this is not the case. This should be called by
any plugin when the API requests the deletion of a port, since
some ports for L3 are not intended to be deleted directly via a
class PoolStatistics(model_base.BASEV2):
- """Represents pool statistics """
+ """Represents pool statistics."""
pool_id = sa.Column(sa.String(36), sa.ForeignKey("pools.id"),
primary_key=True)
bytes_in = sa.Column(sa.Integer, nullable=False)
return self._fields(res, fields)
def _check_session_persistence_info(self, info):
- """ Performs sanity check on session persistence info.
+ """Performs sanity check on session persistence info.
:param info: Session persistence info
"""
if info['type'] == 'APP_COOKIE':
return n, getattr(self, n)
def update(self, values):
- """Make the model object behave like a dict"""
+ """Make the model object behave like a dict."""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict.
- Includes attributes from joins."""
+ Includes attributes from joins.
+ """
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
return local.iteritems()
def __repr__(self):
- """sqlalchemy based automatic __repr__ method"""
+ """sqlalchemy based automatic __repr__ method."""
items = ['%s=%r' % (col.name, getattr(self, col.name))
for col in self.__table__.columns]
return "<%s.%s[object at %x] {%s}>" % (self.__class__.__module__,
class SecurityGroupPortBinding(model_base.BASEV2):
- """Represents binding between quantum ports and security profiles"""
+ """Represents binding between quantum ports and security profiles."""
port_id = sa.Column(sa.String(36),
sa.ForeignKey("ports.id",
ondelete='CASCADE'),
def _check_update_deletes_security_groups(self, port):
"""Return True if port has as a security group and it's value
- is either [] or not is_attr_set, otherwise return False"""
+ is either [] or not is_attr_set, otherwise return False
+ """
if (ext_sg.SECURITYGROUPS in port['port'] and
not (attr.is_attr_set(port['port'][ext_sg.SECURITYGROUPS])
and port['port'][ext_sg.SECURITYGROUPS] != [])):
def _check_update_has_security_groups(self, port):
"""Return True if port has as a security group and False if the
- security_group field is is_attr_set or []."""
+ security_group field is is_attr_set or [].
+ """
if (ext_sg.SECURITYGROUPS in port['port'] and
(attr.is_attr_set(port['port'][ext_sg.SECURITYGROUPS]) and
port['port'][ext_sg.SECURITYGROUPS] != [])):
def update_security_group_on_port(self, context, id, port,
original_port, updated_port):
- """ update security groups on port
+ """Update security groups on port.
This method returns a flag which indicates request notification
is required and does not perform notification itself.
def is_security_group_member_updated(self, context,
original_port, updated_port):
- """ check security group member updated or not
+ """Check security group member updated or not.
This method returns a flag which indicates request notification
is required and does not perform notification itself.
return need_notify
def notify_security_groups_member_updated(self, context, port):
- """ notify update event of security group members
+ """Notify update event of security group members.
The agent setups the iptables rule to allow
ingress packet from the dhcp server (as a part of provider rules),
"""
def security_group_rules_for_devices(self, context, **kwargs):
- """ return security group rules for each port
+ """Return security group rules for each port.
also convert remote_group_id rule
to source_ip_prefix and dest_ip_prefix rule
def parse_service_definition_opt():
- """ parse service definition opts and returns result """
+ """Parse service definition opts and returns result."""
results = []
svc_def_opt = cfg.CONF.DEFAULT_SERVICETYPE.service_definition
try:
class ServiceType(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
- """ Service Type Object Model """
+ """Service Type Object Model."""
name = sa.Column(sa.String(255))
description = sa.Column(sa.String(255))
default = sa.Column(sa.Boolean(), nullable=False, default=False)
num_instances = sa.Column(sa.Integer(), default=0)
def as_dict(self):
- """ Convert a row into a dict """
+ """Convert a row into a dict."""
ret_dict = {}
for c in self.__table__.columns:
ret_dict[c.name] = getattr(self, c.name)
class ServiceTypeManager(object):
- """ Manage service type objects in Quantum database """
+ """Manage service type objects in Quantum database."""
_instance = None
return res
def get_service_type(self, context, id, fields=None):
- """ Retrieve a service type record """
+ """Retrieve a service type record."""
return self._make_svc_type_dict(context,
self._get_service_type(context, id),
fields)
def get_service_types(self, context, fields=None, filters=None):
- """ Retrieve a possibly filtered list of service types """
+ """Retrieve a possibly filtered list of service types."""
query = context.session.query(ServiceType)
if filters:
for key, value in filters.iteritems():
for svc_type in query.all()]
def create_service_type(self, context, service_type):
- """ Create a new service type """
+ """Create a new service type."""
svc_type_data = service_type['service_type']
svc_type_db = self._create_service_type(context, svc_type_data)
LOG.debug(_("Created service type object:%s"), svc_type_db['id'])
return self._make_svc_type_dict(context, svc_type_db)
def update_service_type(self, context, id, service_type):
- """ Update a service type """
+ """Update a service type."""
svc_type_data = service_type['service_type']
svc_type_db = self._update_service_type(context, id,
svc_type_data)
return self._make_svc_type_dict(context, svc_type_db)
def delete_service_type(self, context, id):
- """ Delete a service type """
+ """Delete a service type."""
# Verify that the service type is not in use.
svc_type_db = self._get_service_type(context, id)
if svc_type_db['num_instances'] > 0:
context.session.delete(svc_type_db)
def increase_service_type_refcount(self, context, id):
- """ Increase references count for a service type object
+ """Increase references count for a service type object
This method should be invoked by plugins using the service
type concept everytime an instance of an object associated
return svc_type_db['num_instances']
def decrease_service_type_refcount(self, context, id):
- """ Decrease references count for a service type object
+ """Decrease references count for a service type object
This method should be invoked by plugins using the service
type concept everytime an instance of an object associated
class DeleteProbe(ProbeCommand):
- """Delete probe - delete port then uplug """
+ """Delete probe - delete port then uplug."""
log = logging.getLogger(__name__ + '.DeleteProbe')
class ListProbe(QuantumCommand, lister.Lister):
- """ List probes """
+ """List probes."""
log = logging.getLogger(__name__ + '.ListProbe')
_formatters = {'fixed_ips': _format_fixed_ips, }
class ClearProbe(ProbeCommand):
- """Clear All probes """
+ """Clear All probes."""
log = logging.getLogger(__name__ + '.ClearProbe')
namespace=namespace)
try:
ip.netns.delete(namespace)
- except:
+ except Exception:
LOG.warn(_('Failed to delete namespace %s'), namespace)
else:
self.driver.unplug(self.driver.get_device_name(port),
class Agent(object):
- """Agent management extension"""
+ """Agent management extension."""
@classmethod
def get_name(cls):
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
my_plurals = [(key, key[:-1]) for key in RESOURCE_ATTRIBUTE_MAP.keys()]
attr.PLURALS.update(dict(my_plurals))
plugin = manager.QuantumManager.get_plugin()
class AgentPluginBase(object):
- """ REST API to operate the Agent.
+ """REST API to operate the Agent.
All of method must be in an admin context.
"""
def create_agent(self, context, agent):
- """ Create agent.
+ """Create agent.
This operation is not allow in REST API.
@raise exceptions.BadRequest:
@classmethod
def get_resources(cls):
- """Returns Ext Resources """
+ """Returns Ext Resources."""
exts = []
parent = dict(member_name="agent",
collection_name="agents")
class AgentSchedulerPluginBase(object):
- """ REST API to operate the agent scheduler.
+ """REST API to operate the agent scheduler.
All of method must be in an admin context.
"""
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
my_plurals = [(key, key[:-1]) for key in RESOURCE_ATTRIBUTE_MAP.keys()]
attr.PLURALS.update(dict(my_plurals))
exts = []
class Quotasv2(extensions.ExtensionDescriptor):
- """Quotas management support"""
+ """Quotas management support."""
@classmethod
def get_name(cls):
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
controller = resource.Resource(
QuotaSetsController(QuantumManager.get_plugin()),
faults=base.FAULT_MAP)
class Securitygroup(extensions.ExtensionDescriptor):
- """ Security group extension"""
+ """Security group extension."""
@classmethod
def get_name(cls):
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
my_plurals = [(key, key[:-1]) for key in RESOURCE_ATTRIBUTE_MAP.keys()]
attr.PLURALS.update(dict(my_plurals))
exts = []
def _validate_servicetype_ref(data, valid_values=None):
- """ Verify the service type id exists """
+ """Verify the service type id exists."""
svc_type_id = data
svctype_mgr = servicetype_db.ServiceTypeManager.get_instance()
try:
def _validate_service_defs(data, valid_values=None):
- """ Validate the list of service definitions. """
+ """Validate the list of service definitions."""
try:
if not data:
return _("No service type definition was provided. At least a "
@classmethod
def get_resources(cls):
- """ Returns Extended Resource for service type management """
+ """Returns Extended Resource for service type management."""
my_plurals = [(key.replace('-', '_'),
key[:-1].replace('-', '_')) for
key in RESOURCE_ATTRIBUTE_MAP.keys()]
# core plugin as a part of plugin collection simplifies
# checking extensions
- # TODO (enikanorov): make core plugin the same as
+ # TODO(enikanorov): make core plugin the same as
# the rest of service plugins
self.service_plugins = {constants.CORE: self.plugin}
self._load_service_plugins()
try:
self._send_update_network(orig_net)
except RemoteRestError:
- # TODO (Sumit): rollback deletion of subnet
+ # TODO(Sumit): rollback deletion of subnet
raise
def create_router(self, context, router):
if request_data:
try:
request_data = json.loads(request_data)
- except:
+ except Exception:
# OK for it not to be json! Ignore it
pass
if body:
try:
body_data = json.loads(body)
- except:
+ except Exception:
# OK for it not to be json! Ignore it
pass
# Varma Bhupatiraju (vbhupati@#brocade.com)
#
# (Some parts adapted from LinuxBridge Plugin)
-# TODO (shiv) need support for security groups
+# TODO(shiv) need support for security groups
"""
LOG.debug(_("Connect failed to switch: %s"), e)
raise
- LOG.debug(_("Connect success to host %s:%d"), host, SSH_PORT)
+ LOG.debug(_("Connect success to host %(host)s:%(ssh_port)d"),
+ dict(host=host, ssh_port=SSH_PORT))
return mgr
def create_network(self, host, username, password, net_id):
import logging as LOG
-from quantum.plugins.cisco.common import config
from quantum.plugins.cisco.common import cisco_constants as const
from quantum.plugins.cisco.common import cisco_exceptions as cexc
+from quantum.plugins.cisco.common import config
from quantum.plugins.cisco.db import network_db_v2 as cdb
class Store(object):
- """Credential Store"""
+ """Credential Store."""
@staticmethod
def initialize():
@staticmethod
def put_credential(cred_name, username, password):
- """Set the username and password"""
+ """Set the username and password."""
cdb.add_credential(TENANT, cred_name, username, password)
@staticmethod
def get_username(cred_name):
- """Get the username"""
+ """Get the username."""
credential = cdb.get_credential_name(TENANT, cred_name)
return credential[const.CREDENTIAL_USERNAME]
@staticmethod
def get_password(cred_name):
- """Get the password"""
+ """Get the password."""
credential = cdb.get_credential_name(TENANT, cred_name)
return credential[const.CREDENTIAL_PASSWORD]
@staticmethod
def get_credential(cred_name):
- """Get the username and password"""
+ """Get the username and password."""
cdb.get_credential_name(TENANT, cred_name)
return {const.USERNAME: const.CREDENTIAL_USERNAME,
const.PASSWORD: const.CREDENTIAL_PASSWORD}
@staticmethod
def delete_credential(cred_name):
- """Delete a credential"""
+ """Delete a credential."""
cdb.remove_credential(TENANT, cred_name)
class NoMoreNics(exceptions.QuantumException):
- """No more dynamic nics are available in the system"""
+ """No more dynamic nics are available in the system."""
message = _("Unable to complete operation. No more dynamic nics are "
"available in the system.")
class NetworksLimit(exceptions.QuantumException):
- """Total number of network objects limit has been hit"""
+ """Total number of network objects limit has been hit."""
message = _("Unable to create new network. Number of networks"
"for the system has exceeded the limit")
class NetworkVlanBindingAlreadyExists(exceptions.QuantumException):
- """Binding cannot be created, since it already exists"""
+ """Binding cannot be created, since it already exists."""
message = _("NetworkVlanBinding for %(vlan_id)s and network "
"%(network_id)s already exists")
class VlanIDNotFound(exceptions.QuantumException):
- """VLAN ID cannot be found"""
+ """VLAN ID cannot be found."""
message = _("Vlan ID %(vlan_id)s not found")
class VlanIDNotAvailable(exceptions.QuantumException):
- """No VLAN ID available"""
+ """No VLAN ID available."""
message = _("No Vlan ID available")
class QosNotFound(exceptions.QuantumException):
- """QoS level with this ID cannot be found"""
+ """QoS level with this ID cannot be found."""
message = _("QoS level %(qos_id)s could not be found "
"for tenant %(tenant_id)s")
class QoSLevelInvalidDelete(exceptions.QuantumException):
- """QoS is associated with a port profile, hence cannot be deleted"""
+ """QoS is associated with a port profile, hence cannot be deleted."""
message = _("QoS level %(qos_id)s could not be deleted "
"for tenant %(tenant_id)s since association exists")
class QosNameAlreadyExists(exceptions.QuantumException):
- """QoS Name already exists"""
+ """QoS Name already exists."""
message = _("QoS level with name %(qos_name)s already exists "
"for tenant %(tenant_id)s")
class CredentialNotFound(exceptions.QuantumException):
- """Credential with this ID cannot be found"""
+ """Credential with this ID cannot be found."""
message = _("Credential %(credential_id)s could not be found "
"for tenant %(tenant_id)s")
class CredentialNameNotFound(exceptions.QuantumException):
- """Credential Name could not be found"""
+ """Credential Name could not be found."""
message = _("Credential %(credential_name)s could not be found "
"for tenant %(tenant_id)s")
class CredentialAlreadyExists(exceptions.QuantumException):
- """Credential ID already exists"""
+ """Credential ID already exists."""
message = _("Credential %(credential_id)s already exists "
"for tenant %(tenant_id)s")
class NexusPortBindingNotFound(exceptions.QuantumException):
- """NexusPort Binding is not present"""
+ """NexusPort Binding is not present."""
message = _("Nexus Port Binding %(port_id)s is not present")
class NexusPortBindingAlreadyExists(exceptions.QuantumException):
- """NexusPort Binding alredy exists"""
+ """NexusPort Binding alredy exists."""
message = _("Nexus Port Binding %(port_id)s already exists")
class UcsmBindingNotFound(exceptions.QuantumException):
- """Ucsm Binding is not present"""
+ """Ucsm Binding is not present."""
message = _("Ucsm Binding with ip %(ucsm_ip)s is not present")
class UcsmBindingAlreadyExists(exceptions.QuantumException):
- """Ucsm Binding already exists"""
+ """Ucsm Binding already exists."""
message = _("Ucsm Binding with ip %(ucsm_ip)s already exists")
class DynamicVnicNotFound(exceptions.QuantumException):
- """Ucsm Binding is not present"""
+ """Ucsm Binding is not present."""
message = _("Dyanmic Vnic %(vnic_id)s is not present")
class DynamicVnicAlreadyExists(exceptions.QuantumException):
- """Ucsm Binding already exists"""
+ """Ucsm Binding already exists."""
message = _("Dynamic Vnic with name %(device_name)s already exists")
class BladeNotFound(exceptions.QuantumException):
- """Blade is not present"""
+ """Blade is not present."""
message = _("Blade %(blade_id)s is not present")
class BladeAlreadyExists(exceptions.QuantumException):
- """Blade already exists"""
+ """Blade already exists."""
message = _("Blade with mgmt_ip %(mgmt_ip)s already exists")
class PortVnicBindingAlreadyExists(exceptions.QuantumException):
- """PortVnic Binding already exists"""
+ """PortVnic Binding already exists."""
message = _("PortVnic Binding %(port_id)s already exists")
class PortVnicNotFound(exceptions.QuantumException):
- """PortVnic Binding is not present"""
+ """PortVnic Binding is not present."""
message = _("PortVnic Binding %(port_id)s is not present")
class Fault(webob.exc.HTTPException):
- """Error codes for API faults"""
+ """Error codes for API faults."""
_fault_names = {
400: "malformedRequest",
@webob.dec.wsgify(RequestClass=wsgi.Request)
def __call__(self, req):
"""Generate a WSGI response based on the
- exception passed to constructor."""
+ exception passed to constructor.
+ """
# Replace the body with fault details.
code = self.wrapped_exc.status_int
fault_name = self._fault_names.get(code, "quantumServiceFault")
def make_net_dict(net_id, net_name, ports):
- """Helper funciton"""
+ """Helper funciton."""
res = {const.NET_ID: net_id, const.NET_NAME: net_name}
res[const.NET_PORTS] = ports
return res
def make_port_dict(port_id, port_state, net_id, attachment):
- """Helper funciton"""
+ """Helper funciton."""
res = {const.PORT_ID: port_id, const.PORT_STATE: port_state}
res[const.NET_ID] = net_id
res[const.ATTACHMENT] = attachment
class CiscoConfigOptions():
- """ Cisco Configuration Options Class """
+ """Cisco Configuration Options Class."""
def __init__(self):
self._create_nexus_dictionary()
def get_session(autocommit=True, expire_on_commit=False):
- """Helper method to grab session"""
+ """Helper method to grab session."""
global _MAKER, _ENGINE
if not _MAKER:
assert _ENGINE
def register_models():
- """Register Models and create properties"""
+ """Register Models and create properties."""
global _ENGINE
assert _ENGINE
BASE.metadata.create_all(_ENGINE)
def unregister_models():
- """Unregister Models, useful clearing out data before testing"""
+ """Unregister Models, useful clearing out data before testing."""
global _ENGINE
assert _ENGINE
BASE.metadata.drop_all(_ENGINE)
def initialize():
- """Establish database connection and load models"""
+ """Establish database connection and load models."""
db.configure_db()
def create_vlanids():
- """Prepopulates the vlan_bindings table"""
+ """Prepopulates the vlan_bindings table."""
LOG.debug(_("create_vlanids() called"))
session = db.get_session()
try:
def get_all_vlanids():
- """Gets all the vlanids"""
+ """Gets all the vlanids."""
LOG.debug(_("get_all_vlanids() called"))
session = db.get_session()
try:
def is_vlanid_used(vlan_id):
- """Checks if a vlanid is in use"""
+ """Checks if a vlanid is in use."""
LOG.debug(_("is_vlanid_used() called"))
session = db.get_session()
try:
def release_vlanid(vlan_id):
- """Sets the vlanid state to be unused"""
+ """Sets the vlanid state to be unused."""
LOG.debug(_("release_vlanid() called"))
session = db.get_session()
try:
def delete_vlanid(vlan_id):
- """Deletes a vlanid entry from db"""
+ """Deletes a vlanid entry from db."""
LOG.debug(_("delete_vlanid() called"))
session = db.get_session()
try:
def reserve_vlanid():
- """Reserves the first unused vlanid"""
+ """Reserves the first unused vlanid."""
LOG.debug(_("reserve_vlanid() called"))
session = db.get_session()
try:
def get_all_vlanids_used():
- """Gets all the vlanids used"""
+ """Gets all the vlanids used."""
LOG.debug(_("get_all_vlanids() called"))
session = db.get_session()
try:
def get_all_vlan_bindings():
- """Lists all the vlan to network associations"""
+ """Lists all the vlan to network associations."""
LOG.debug(_("get_all_vlan_bindings() called"))
session = db.get_session()
try:
def get_vlan_binding(netid):
- """Lists the vlan given a network_id"""
+ """Lists the vlan given a network_id."""
LOG.debug(_("get_vlan_binding() called"))
session = db.get_session()
try:
def add_vlan_binding(vlanid, vlanname, netid):
- """Adds a vlan to network association"""
+ """Adds a vlan to network association."""
LOG.debug(_("add_vlan_binding() called"))
session = db.get_session()
try:
def remove_vlan_binding(netid):
- """Removes a vlan to network association"""
+ """Removes a vlan to network association."""
LOG.debug(_("remove_vlan_binding() called"))
session = db.get_session()
try:
def update_vlan_binding(netid, newvlanid=None, newvlanname=None):
- """Updates a vlan to network association"""
+ """Updates a vlan to network association."""
LOG.debug(_("update_vlan_binding() called"))
session = db.get_session()
try:
def get_all_qoss(tenant_id):
- """Lists all the qos to tenant associations"""
+ """Lists all the qos to tenant associations."""
LOG.debug(_("get_all_qoss() called"))
session = db.get_session()
try:
def get_qos(tenant_id, qos_id):
- """Lists the qos given a tenant_id and qos_id"""
+ """Lists the qos given a tenant_id and qos_id."""
LOG.debug(_("get_qos() called"))
session = db.get_session()
try:
def add_qos(tenant_id, qos_name, qos_desc):
- """Adds a qos to tenant association"""
+ """Adds a qos to tenant association."""
LOG.debug(_("add_qos() called"))
session = db.get_session()
try:
def remove_qos(tenant_id, qos_id):
- """Removes a qos to tenant association"""
+ """Removes a qos to tenant association."""
session = db.get_session()
try:
qos = (session.query(l2network_models.QoS).
def update_qos(tenant_id, qos_id, new_qos_name=None):
- """Updates a qos to tenant association"""
+ """Updates a qos to tenant association."""
session = db.get_session()
try:
qos = (session.query(l2network_models.QoS).
def get_all_credentials(tenant_id):
- """Lists all the creds for a tenant"""
+ """Lists all the creds for a tenant."""
session = db.get_session()
try:
creds = (session.query(l2network_models.Credential).
def get_credential(tenant_id, credential_id):
- """Lists the creds for given a cred_id and tenant_id"""
+ """Lists the creds for given a cred_id and tenant_id."""
session = db.get_session()
try:
cred = (session.query(l2network_models.Credential).
def get_credential_name(tenant_id, credential_name):
- """Lists the creds for given a cred_name and tenant_id"""
+ """Lists the creds for given a cred_name and tenant_id."""
session = db.get_session()
try:
cred = (session.query(l2network_models.Credential).
def add_credential(tenant_id, credential_name, user_name, password):
- """Adds a qos to tenant association"""
+ """Adds a qos to tenant association."""
session = db.get_session()
try:
cred = (session.query(l2network_models.Credential).
def remove_credential(tenant_id, credential_id):
- """Removes a credential from a tenant"""
+ """Removes a credential from a tenant."""
session = db.get_session()
try:
cred = (session.query(l2network_models.Credential).
def update_credential(tenant_id, credential_id,
new_user_name=None, new_password=None):
- """Updates a credential for a tenant"""
+ """Updates a credential for a tenant."""
session = db.get_session()
try:
cred = (session.query(l2network_models.Credential).
__table_args__ = {'mysql_engine': 'InnoDB'}
def __setitem__(self, key, value):
- """Internal Dict set method"""
+ """Internal Dict set method."""
setattr(self, key, value)
def __getitem__(self, key):
- """Internal Dict get method"""
+ """Internal Dict get method."""
return getattr(self, key)
def get(self, key, default=None):
- """Dict get method"""
+ """Dict get method."""
return getattr(self, key, default)
def __iter__(self):
- """Iterate over table columns"""
+ """Iterate over table columns."""
self._i = iter(object_mapper(self).columns)
return self
def next(self):
- """Next method for the iterator"""
+ """Next method for the iterator."""
n = self._i.next().name
return n, getattr(self, n)
def update(self, values):
- """Make the model object behave like a dict"""
+ """Make the model object behave like a dict."""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict"
- Includes attributes from joins."""
+ Includes attributes from joins.
+ """
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
class VlanID(BASE, L2NetworkBase):
- """Represents a vlan_id usage"""
+ """Represents a vlan_id usage."""
__tablename__ = 'vlan_ids'
vlan_id = Column(Integer, primary_key=True)
class VlanBinding(BASE, L2NetworkBase):
- """Represents a binding of vlan_id to network_id"""
+ """Represents a binding of vlan_id to network_id."""
__tablename__ = 'vlan_bindings'
vlan_id = Column(Integer, primary_key=True)
class QoS(BASE, L2NetworkBase):
- """Represents QoS for a tenant"""
+ """Represents QoS for a tenant."""
__tablename__ = 'qoss'
qos_id = Column(String(255))
class Credential(BASE, L2NetworkBase):
- """Represents credentials for a tenant"""
+ """Represents credentials for a tenant."""
__tablename__ = 'credentials'
credential_id = Column(String(255))
return n, getattr(self, n)
def update(self, values):
- """Make the model object behave like a dict"""
+ """Make the model object behave like a dict."""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict.
- Includes attributes from joins."""
+ Includes attributes from joins.
+ """
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
class Port(BASE, QuantumBase):
- """Represents a port on a quantum network"""
+ """Represents a port on a quantum network."""
__tablename__ = 'ports'
uuid = Column(String(255), primary_key=True)
class Network(BASE, QuantumBase):
- """Represents a quantum network"""
+ """Represents a quantum network."""
__tablename__ = 'networks'
uuid = Column(String(255), primary_key=True)
def create_vlanids():
- """Prepopulates the vlan_bindings table"""
+ """Prepopulates the vlan_bindings table."""
LOG.debug(_("create_vlanids() called"))
session = db.get_session()
try:
def get_all_vlanids():
- """Gets all the vlanids"""
+ """Gets all the vlanids."""
LOG.debug(_("get_all_vlanids() called"))
session = db.get_session()
try:
def is_vlanid_used(vlan_id):
- """Checks if a vlanid is in use"""
+ """Checks if a vlanid is in use."""
LOG.debug(_("is_vlanid_used() called"))
session = db.get_session()
try:
def release_vlanid(vlan_id):
- """Sets the vlanid state to be unused"""
+ """Sets the vlanid state to be unused."""
LOG.debug(_("release_vlanid() called"))
session = db.get_session()
try:
def delete_vlanid(vlan_id):
- """Deletes a vlanid entry from db"""
+ """Deletes a vlanid entry from db."""
LOG.debug(_("delete_vlanid() called"))
session = db.get_session()
try:
def reserve_vlanid():
- """Reserves the first unused vlanid"""
+ """Reserves the first unused vlanid."""
LOG.debug(_("reserve_vlanid() called"))
session = db.get_session()
try:
def get_all_vlanids_used():
- """Gets all the vlanids used"""
+ """Gets all the vlanids used."""
LOG.debug(_("get_all_vlanids() called"))
session = db.get_session()
try:
def get_all_vlan_bindings():
- """Lists all the vlan to network associations"""
+ """Lists all the vlan to network associations."""
LOG.debug(_("get_all_vlan_bindings() called"))
session = db.get_session()
try:
def get_vlan_binding(netid):
- """Lists the vlan given a network_id"""
+ """Lists the vlan given a network_id."""
LOG.debug(_("get_vlan_binding() called"))
session = db.get_session()
try:
def add_vlan_binding(vlanid, vlanname, netid):
- """Adds a vlan to network association"""
+ """Adds a vlan to network association."""
LOG.debug(_("add_vlan_binding() called"))
session = db.get_session()
try:
def remove_vlan_binding(netid):
- """Removes a vlan to network association"""
+ """Removes a vlan to network association."""
LOG.debug(_("remove_vlan_binding() called"))
session = db.get_session()
try:
def update_vlan_binding(netid, newvlanid=None, newvlanname=None):
- """Updates a vlan to network association"""
+ """Updates a vlan to network association."""
LOG.debug(_("update_vlan_binding() called"))
session = db.get_session()
try:
def get_all_qoss(tenant_id):
- """Lists all the qos to tenant associations"""
+ """Lists all the qos to tenant associations."""
LOG.debug(_("get_all_qoss() called"))
session = db.get_session()
try:
def get_qos(tenant_id, qos_id):
- """Lists the qos given a tenant_id and qos_id"""
+ """Lists the qos given a tenant_id and qos_id."""
LOG.debug(_("get_qos() called"))
session = db.get_session()
try:
def add_qos(tenant_id, qos_name, qos_desc):
- """Adds a qos to tenant association"""
+ """Adds a qos to tenant association."""
LOG.debug(_("add_qos() called"))
session = db.get_session()
try:
def remove_qos(tenant_id, qos_id):
- """Removes a qos to tenant association"""
+ """Removes a qos to tenant association."""
session = db.get_session()
try:
qos = (session.query(network_models_v2.QoS).
def update_qos(tenant_id, qos_id, new_qos_name=None):
- """Updates a qos to tenant association"""
+ """Updates a qos to tenant association."""
session = db.get_session()
try:
qos = (session.query(network_models_v2.QoS).
def get_all_credentials(tenant_id):
- """Lists all the creds for a tenant"""
+ """Lists all the creds for a tenant."""
session = db.get_session()
try:
creds = (session.query(network_models_v2.Credential).
def get_credential(tenant_id, credential_id):
- """Lists the creds for given a cred_id and tenant_id"""
+ """Lists the creds for given a cred_id and tenant_id."""
session = db.get_session()
try:
cred = (session.query(network_models_v2.Credential).
def get_credential_name(tenant_id, credential_name):
- """Lists the creds for given a cred_name and tenant_id"""
+ """Lists the creds for given a cred_name and tenant_id."""
session = db.get_session()
try:
cred = (session.query(network_models_v2.Credential).
def add_credential(tenant_id, credential_name, user_name, password):
- """Adds a qos to tenant association"""
+ """Adds a qos to tenant association."""
session = db.get_session()
try:
cred = (session.query(network_models_v2.Credential).
def remove_credential(tenant_id, credential_id):
- """Removes a credential from a tenant"""
+ """Removes a credential from a tenant."""
session = db.get_session()
try:
cred = (session.query(network_models_v2.Credential).
def update_credential(tenant_id, credential_id,
new_user_name=None, new_password=None):
- """Updates a credential for a tenant"""
+ """Updates a credential for a tenant."""
session = db.get_session()
try:
cred = (session.query(network_models_v2.Credential).
#__table_args__ = {'mysql_engine': 'InnoDB'}
def __setitem__(self, key, value):
- """Internal Dict set method"""
+ """Internal Dict set method."""
setattr(self, key, value)
def __getitem__(self, key):
- """Internal Dict get method"""
+ """Internal Dict get method."""
return getattr(self, key)
def get(self, key, default=None):
- """Dict get method"""
+ """Dict get method."""
return getattr(self, key, default)
def __iter__(self):
- """Iterate over table columns"""
+ """Iterate over table columns."""
self._i = iter(object_mapper(self).columns)
return self
def next(self):
- """Next method for the iterator"""
+ """Next method for the iterator."""
n = self._i.next().name
return n, getattr(self, n)
def update(self, values):
- """Make the model object behave like a dict"""
+ """Make the model object behave like a dict."""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict"
- Includes attributes from joins."""
+ Includes attributes from joins.
+ """
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
class VlanID(model_base.BASEV2, L2NetworkBase):
- """Represents a vlan_id usage"""
+ """Represents a vlan_id usage."""
__tablename__ = 'cisco_vlan_ids'
vlan_id = Column(Integer, primary_key=True)
class Vlan_Binding(model_base.BASEV2, L2NetworkBase):
- """Represents a binding of vlan_id to network_id"""
+ """Represents a binding of vlan_id to network_id."""
__tablename__ = 'cisco_vlan_bindings'
vlan_id = Column(Integer, primary_key=True)
class QoS(model_base.BASEV2, L2NetworkBase):
- """Represents QoS for a tenant"""
+ """Represents QoS for a tenant."""
__tablename__ = 'qoss'
qos_id = Column(String(255))
class Credential(model_base.BASEV2, L2NetworkBase):
- """Represents credentials for a tenant"""
+ """Represents credentials for a tenant."""
__tablename__ = 'credentials'
credential_id = Column(String(255))
def get_all_nexusport_bindings():
- """Lists all the nexusport bindings"""
+ """Lists all the nexusport bindings."""
LOG.debug(_("get_all_nexusport_bindings() called"))
session = db.get_session()
try:
def get_nexusport_binding(port_id, vlan_id, switch_ip, instance_id):
- """Lists a nexusport binding"""
+ """Lists a nexusport binding."""
LOG.debug(_("get_nexusport_binding() called"))
session = db.get_session()
try:
def get_nexusvlan_binding(vlan_id, switch_ip):
- """Lists a vlan and switch binding"""
+ """Lists a vlan and switch binding."""
LOG.debug(_("get_nexusvlan_binding() called"))
session = db.get_session()
try:
def add_nexusport_binding(port_id, vlan_id, switch_ip, instance_id):
- """Adds a nexusport binding"""
+ """Adds a nexusport binding."""
LOG.debug(_("add_nexusport_binding() called"))
session = db.get_session()
binding = nexus_models_v2.NexusPortBinding(
def remove_nexusport_binding(port_id, vlan_id, switch_ip, instance_id):
- """Removes a nexusport binding"""
+ """Removes a nexusport binding."""
LOG.debug(_("remove_nexusport_binding() called"))
session = db.get_session()
try:
def update_nexusport_binding(port_id, new_vlan_id):
- """Updates nexusport binding"""
+ """Updates nexusport binding."""
LOG.debug(_("update_nexusport_binding called"))
session = db.get_session()
try:
def get_nexusvm_binding(vlan_id, instance_id):
- """Lists nexusvm bindings"""
+ """Lists nexusvm bindings."""
LOG.debug(_("get_nexusvm_binding() called"))
session = db.get_session()
try:
def get_port_vlan_switch_binding(port_id, vlan_id, switch_ip):
- """Lists nexusvm bindings"""
+ """Lists nexusvm bindings."""
LOG.debug(_("get_port_vlan_switch_binding() called"))
session = db.get_session()
try:
class NexusPortBinding(model_base.BASEV2, L2NetworkBase):
- """Represents a binding of VM's to nexus ports"""
+ """Represents a binding of VM's to nexus ports."""
__tablename__ = "nexusport_bindings"
id = Column(Integer, primary_key=True, autoincrement=True)
def get_view_builder(req):
- """get view builder """
+ """get view builder."""
base_url = req.application_url
return ViewBuilder(base_url)
def get_view_builder(req):
- """get view builder"""
+ """get view builder."""
base_url = req.application_url
return ViewBuilder(base_url)
class Credential(extensions.ExtensionDescriptor):
- """extension class Credential"""
+ """extension class Credential."""
@classmethod
def get_name(cls):
- """ Returns Ext Resource Name """
+ """Returns Ext Resource Name."""
return "Cisco Credential"
@classmethod
def get_alias(cls):
- """ Returns Ext Resource Alias """
+ """Returns Ext Resource Alias."""
return "Cisco Credential"
@classmethod
def get_description(cls):
- """ Returns Ext Resource Description """
+ """Returns Ext Resource Description."""
return "Credential include username and password"
@classmethod
def get_namespace(cls):
- """ Returns Ext Resource Namespace """
+ """Returns Ext Resource Namespace."""
return "http://docs.ciscocloud.com/api/ext/credential/v1.0"
@classmethod
def get_updated(cls):
- """ Returns Ext Resource Update Time """
+ """Returns Ext Resource Update Time."""
return "2011-07-25T13:25:27-06:00"
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
parent_resource = dict(member_name="tenant",
collection_name="extensions/csco/tenants")
controller = CredentialController(QuantumManager.get_plugin())
class CredentialController(common.QuantumController, wsgi.Controller):
- """ credential API controller
- based on QuantumController """
+ """Credential API controller based on QuantumController."""
_credential_ops_param_list = [
{'param-name': 'credential_name', 'required': True},
self._plugin = plugin
def index(self, request, tenant_id):
- """ Returns a list of credential ids """
+ """Returns a list of credential ids."""
return self._items(request, tenant_id, is_detail=False)
def _items(self, request, tenant_id, is_detail):
- """ Returns a list of credentials. """
+ """Returns a list of credentials."""
credentials = self._plugin.get_all_credentials(tenant_id)
builder = credential_view.get_view_builder(request)
result = [builder.build(credential, is_detail)['credential']
# pylint: disable-msg=E1101,W0613
def show(self, request, tenant_id, id):
- """ Returns credential details for the given credential id """
+ """Returns credential details for the given credential id."""
try:
credential = self._plugin.get_credential_details(tenant_id, id)
builder = credential_view.get_view_builder(request)
return faults.Fault(faults.CredentialNotFound(exp))
def create(self, request, tenant_id):
- """ Creates a new credential for a given tenant """
+ """Creates a new credential for a given tenant."""
try:
body = self._deserialize(request.body, request.get_content_type())
req_body = self._prepare_request_body(
return dict(credentials=result)
def update(self, request, tenant_id, id):
- """ Updates the name for the credential with the given id """
+ """Updates the name for the credential with the given id."""
try:
body = self._deserialize(request.body, request.get_content_type())
req_body = self._prepare_request_body(
return faults.Fault(faults.CredentialNotFound(exp))
def delete(self, request, tenant_id, id):
- """ Destroys the credential with the given id """
+ """Destroys the credential with the given id."""
try:
self._plugin.delete_credential(tenant_id, id)
return exc.HTTPOk()
class Qos(extensions.ExtensionDescriptor):
- """Qos extension file"""
+ """Qos extension file."""
@classmethod
def get_name(cls):
- """ Returns Ext Resource Name """
+ """Returns Ext Resource Name."""
return "Cisco qos"
@classmethod
def get_alias(cls):
- """ Returns Ext Resource Alias """
+ """Returns Ext Resource Alias."""
return "Cisco qos"
@classmethod
def get_description(cls):
- """ Returns Ext Resource Description """
+ """Returns Ext Resource Description."""
return "qos includes qos_name and qos_desc"
@classmethod
def get_namespace(cls):
- """ Returns Ext Resource Namespace """
+ """Returns Ext Resource Namespace."""
return "http://docs.ciscocloud.com/api/ext/qos/v1.0"
@classmethod
def get_updated(cls):
- """ Returns Ext Resource update """
+ """Returns Ext Resource update."""
return "2011-07-25T13:25:27-06:00"
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
parent_resource = dict(member_name="tenant",
collection_name="extensions/csco/tenants")
class QosController(common.QuantumController, wsgi.Controller):
- """ qos API controller
- based on QuantumController """
+ """qos API controller based on QuantumController."""
_qos_ops_param_list = [
{'param-name': 'qos_name', 'required': True},
self._plugin = plugin
def index(self, request, tenant_id):
- """ Returns a list of qos ids """
+ """Returns a list of qos ids."""
return self._items(request, tenant_id, is_detail=False)
def _items(self, request, tenant_id, is_detail):
- """ Returns a list of qoss. """
+ """Returns a list of qoss."""
qoss = self._plugin.get_all_qoss(tenant_id)
builder = qos_view.get_view_builder(request)
result = [builder.build(qos, is_detail)['qos'] for qos in qoss]
# pylint: disable-msg=E1101
def show(self, request, tenant_id, id):
- """ Returns qos details for the given qos id """
+ """Returns qos details for the given qos id."""
try:
qos = self._plugin.get_qos_details(tenant_id, id)
builder = qos_view.get_view_builder(request)
return faults.Fault(faults.QosNotFound(exp))
def create(self, request, tenant_id):
- """ Creates a new qos for a given tenant """
+ """Creates a new qos for a given tenant."""
#look for qos name in request
try:
body = self._deserialize(request.body, request.get_content_type())
return dict(qoss=result)
def update(self, request, tenant_id, id):
- """ Updates the name for the qos with the given id """
+ """Updates the name for the qos with the given id."""
try:
body = self._deserialize(request.body, request.get_content_type())
req_body = self._prepare_request_body(body,
return faults.Fault(faults.QosNotFound(exp))
def delete(self, request, tenant_id, id):
- """ Destroys the qos with the given id """
+ """Destroys the qos with the given id."""
try:
self._plugin.delete_qos(tenant_id, id)
return exc.HTTPOk()
from novaclient.v1_1 import client as nova_client
from oslo.config import cfg
+from quantum.db import api as db_api
from quantum.manager import QuantumManager
from quantum.openstack.common import importutils
from quantum.plugins.cisco.common import cisco_constants as const
from quantum.plugins.cisco.common import cisco_credentials_v2 as cred
-from quantum.plugins.cisco.db import network_db_v2 as cdb
from quantum.plugins.cisco.common import config as conf
+from quantum.plugins.cisco.db import network_db_v2 as cdb
from quantum.plugins.openvswitch import ovs_db_v2 as odb
from quantum import quantum_plugin_base_v2
-from quantum.db import api as db_api
LOG = logging.getLogger(__name__)
return getattr(plugin, name)
def _func_name(self, offset=0):
- """Get the name of the calling function"""
+ """Get the name of the calling function."""
frame_record = inspect.stack()[1 + offset]
func_name = frame_record[3]
return func_name
ovs_output[0]['id'], vlan_name, vlan_id,
{'vlan_ids': vlanids}]
return ovs_output[0]
- except:
- # TODO (Sumit): Check if we need to perform any rollback here
+ except Exception:
+ # TODO(Sumit): Check if we need to perform any rollback here
raise
def update_network(self, context, id, network):
self._invoke_plugin_per_device(const.NEXUS_PLUGIN,
self._func_name(), args)
return ovs_output[0]
- except:
+ except Exception:
raise
def get_network(self, context, id, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def get_networks(self, context, filters=None, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def _invoke_nexus_for_net_create(self, context, tenant_id, net_id,
context, tenant_id, net_id, instance_id)
return ovs_output[0]
- except:
- # TODO (asomya): Check if we need to perform any rollback here
+ except Exception:
+ # TODO(asomya): Check if we need to perform any rollback here
raise
def get_port(self, context, id, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def get_ports(self, context, filters=None, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def update_port(self, context, id, port):
context, tenant_id, net_id, instance_id)
return ovs_output[0]
- except:
+ except Exception:
raise
def delete_port(self, context, id):
self._func_name(),
n_args)
return ovs_output[0]
- except:
- # TODO (asomya): Check if we need to perform any rollback here
+ except Exception:
+ # TODO(asomya): Check if we need to perform any rollback here
raise
def create_subnet(self, context, subnet):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def update_subnet(self, context, id, subnet):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def get_subnet(self, context, id, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def delete_subnet(self, context, id, kwargs):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
def get_subnets(self, context, filters=None, fields=None):
- """For this model this method will be delegated to vswitch plugin"""
+ """For this model this method will be delegated to vswitch plugin."""
pass
self._invoke_device_plugins(self._func_name(), [context,
new_network])
return new_network
- except:
+ except Exception:
super(PluginV2, self).delete_network(context,
new_network['id'])
raise
self._invoke_device_plugins(self._func_name(), [context, id,
kwargs])
return super(PluginV2, self).delete_network(context, id)
- except:
+ except Exception:
raise
def get_network(self, context, id, fields=None):
try:
self._invoke_device_plugins(self._func_name(), [context, new_port])
return new_port
- except:
+ except Exception:
super(PluginV2, self).delete_port(context, new_port['id'])
raise
"""
try:
kwargs = {const.PORT: port}
- # TODO (Sumit): Might first need to check here if port is active
+ # TODO(Sumit): Might first need to check here if port is active
self._invoke_device_plugins(self._func_name(), [context, id,
kwargs])
return super(PluginV2, self).delete_port(context, id)
- except:
+ except Exception:
raise
def update_port(self, context, id, port):
self._invoke_device_plugins(self._func_name(), [context, id,
port])
return super(PluginV2, self).update_port(context, id, port)
- except:
+ except Exception:
raise
def create_subnet(self, context, subnet):
self._invoke_device_plugins(self._func_name(), [context,
new_subnet])
return new_subnet
- except:
+ except Exception:
super(PluginV2, self).delete_subnet(context, new_subnet['id'])
raise
self._invoke_device_plugins(self._func_name(), [context, id,
subnet])
return super(PluginV2, self).update_subnet(context, id, subnet)
- except:
+ except Exception:
raise
def delete_subnet(self, context, id):
self._invoke_device_plugins(self._func_name(), [context, id,
kwargs])
return super(PluginV2, self).delete_subnet(context, id)
- except:
+ except Exception:
raise
"""
Extension API implementation
"""
def get_all_qoss(self, tenant_id):
- """Get all QoS levels"""
+ """Get all QoS levels."""
LOG.debug(_("get_all_qoss() called"))
qoslist = cdb.get_all_qoss(tenant_id)
return qoslist
def get_qos_details(self, tenant_id, qos_id):
- """Get QoS Details"""
+ """Get QoS Details."""
LOG.debug(_("get_qos_details() called"))
try:
qos_level = cdb.get_qos(tenant_id, qos_id)
return qos_level
def create_qos(self, tenant_id, qos_name, qos_desc):
- """Create a QoS level"""
+ """Create a QoS level."""
LOG.debug(_("create_qos() called"))
qos = cdb.add_qos(tenant_id, qos_name, str(qos_desc))
return qos
def delete_qos(self, tenant_id, qos_id):
- """Delete a QoS level"""
+ """Delete a QoS level."""
LOG.debug(_("delete_qos() called"))
try:
cdb.get_qos(tenant_id, qos_id)
return cdb.remove_qos(tenant_id, qos_id)
def rename_qos(self, tenant_id, qos_id, new_name):
- """Rename QoS level"""
+ """Rename QoS level."""
LOG.debug(_("rename_qos() called"))
try:
cdb.get_qos(tenant_id, qos_id)
return qos
def get_all_credentials(self, tenant_id):
- """Get all credentials"""
+ """Get all credentials."""
LOG.debug(_("get_all_credentials() called"))
credential_list = cdb.get_all_credentials(tenant_id)
return credential_list
def get_credential_details(self, tenant_id, credential_id):
- """Get a particular credential"""
+ """Get a particular credential."""
LOG.debug(_("get_credential_details() called"))
try:
credential = cdb.get_credential(tenant_id, credential_id)
def create_credential(self, tenant_id, credential_name, user_name,
password):
- """Create a new credential"""
+ """Create a new credential."""
LOG.debug(_("create_credential() called"))
credential = cdb.add_credential(tenant_id, credential_name,
user_name, password)
return credential
def delete_credential(self, tenant_id, credential_id):
- """Delete a credential"""
+ """Delete a credential."""
LOG.debug(_("delete_credential() called"))
try:
credential = cdb.get_credential(tenant_id, credential_id)
return credential
def rename_credential(self, tenant_id, credential_id, new_name):
- """Rename the particular credential resource"""
+ """Rename the particular credential resource."""
LOG.debug(_("rename_credential() called"))
try:
credential = cdb.get_credential(tenant_id, credential_id)
return credential
def schedule_host(self, tenant_id, instance_id, instance_desc):
- """Provides the hostname on which a dynamic vnic is reserved"""
+ """Provides the hostname on which a dynamic vnic is reserved."""
LOG.debug(_("schedule_host() called"))
host_list = self._invoke_device_plugins(self._func_name(),
[tenant_id,
return getattr(self._model, function_name)(*args)
def _func_name(self, offset=0):
- """Getting the name of the calling funciton"""
+ """Getting the name of the calling funciton."""
return inspect.stack()[1 + offset][3]
def create_request(self, path, body, content_type, method='GET'):
- """ Test create request"""
+ """Test create request."""
LOG.debug("test_create_request - START")
req = webob.Request.blank(path)
def _create_network(self, name=None):
- """ Test create network"""
+ """Test create network."""
LOG.debug("Creating network - START")
if name:
def _create_port(self, network_id, port_state):
- """ Test create port"""
+ """Test create port."""
LOG.debug("Creating port for network %s - START", network_id)
port_path = "/tenants/tt/networks/%s/ports" % network_id
return port_data['port']['id']
def _delete_port(self, network_id, port_id):
- """ Delete port """
+ """Delete port."""
LOG.debug("Deleting port for network %s - START", network_id)
port_path = ("/tenants/tt/networks/%(network_id)s/ports/%(port_id)s" %
locals())
LOG.debug("Deleting port for network - END")
def _delete_network(self, network_id):
- """ Delete network """
+ """Delete network."""
LOG.debug("Deleting network %s - START", network_id)
network_path = "/tenants/tt/networks/%s" % network_id
network_req = self.create_request(network_path, None,
LOG.debug("Deleting network - END")
def tear_down_port_network(self, net_id, port_id):
- """ Tear down port and network """
+ """Tear down port and network."""
self._delete_port(net_id, port_id)
self._delete_network(net_id)
def setUp(self):
- """ Set up function """
+ """Set up function."""
super(QosExtensionTest, self).setUp()
parent_resource = dict(member_name="tenant",
def test_create_qos(self):
- """ Test create qos """
+ """Test create qos."""
LOG.debug("test_create_qos - START")
req_body = jsonutils.dumps(self.test_qos_data)
def test_create_qosBADRequest(self):
- """ Test create qos bad request """
+ """Test create qos bad request."""
LOG.debug("test_create_qosBADRequest - START")
index_response = self.test_app.post(self.qos_path,
def test_list_qoss(self):
- """ Test list qoss """
+ """Test list qoss."""
LOG.debug("test_list_qoss - START")
req_body1 = jsonutils.dumps(self.test_qos_data)
def test_show_qos(self):
- """ Test show qos """
+ """Test show qos."""
LOG.debug("test_show_qos - START")
req_body = jsonutils.dumps(self.test_qos_data)
def test_show_qosDNE(self, qos_id='100'):
- """ Test show qos does not exist"""
+ """Test show qos does not exist."""
LOG.debug("test_show_qosDNE - START")
show_path_temp = self.qos_second_path + qos_id
def test_update_qos(self):
- """ Test update qos """
+ """Test update qos."""
LOG.debug("test_update_qos - START")
req_body = jsonutils.dumps(self.test_qos_data)
def test_update_qosDNE(self, qos_id='100'):
- """ Test update qos does not exist """
+ """Test update qos does not exist."""
LOG.debug("test_update_qosDNE - START")
rename_req_body = jsonutils.dumps({
def test_update_qosBADRequest(self):
- """ Test update qos bad request """
+ """Test update qos bad request."""
LOG.debug("test_update_qosBADRequest - START")
req_body = jsonutils.dumps(self.test_qos_data)
def test_delete_qos(self):
- """ Test delte qos """
+ """Test delte qos."""
LOG.debug("test_delete_qos - START")
req_body = jsonutils.dumps({
def test_delete_qosDNE(self, qos_id='100'):
- """ Test delte qos does not exist"""
+ """Test delte qos does not exist."""
LOG.debug("test_delete_qosDNE - START")
delete_path_temp = self.qos_second_path + qos_id
def tearDownQos(self, delete_profile_path):
- """ Tear Down Qos """
+ """Tear Down Qos."""
self.test_app.delete(delete_profile_path)
def setUp(self):
- """ Set up function """
+ """Set up function."""
super(CredentialExtensionTest, self).setUp()
parent_resource = dict(member_name="tenant",
def test_list_credentials(self):
- """ Test list credentials """
+ """Test list credentials."""
#Create Credential before listing
LOG.debug("test_list_credentials - START")
def test_create_credential(self):
- """ Test create credential """
+ """Test create credential."""
LOG.debug("test_create_credential - START")
req_body = jsonutils.dumps(self.test_credential_data)
def test_create_credentialBADRequest(self):
- """ Test create credential bad request """
+ """Test create credential bad request."""
LOG.debug("test_create_credentialBADRequest - START")
index_response = self.test_app.post(
def test_show_credential(self):
- """ Test show credential """
+ """Test show credential."""
LOG.debug("test_show_credential - START")
req_body = jsonutils.dumps(self.test_credential_data)
def test_show_credentialDNE(self, credential_id='100'):
- """ Test show credential does not exist """
+ """Test show credential does not exist."""
LOG.debug("test_show_credentialDNE - START")
show_path_temp = self.cred_second_path + credential_id
def test_update_credential(self):
- """ Test update credential """
+ """Test update credential."""
LOG.debug("test_update_credential - START")
req_body = jsonutils.dumps(self.test_credential_data)
def test_update_credBADReq(self):
- """ Test update credential bad request """
+ """Test update credential bad request."""
LOG.debug("test_update_credBADReq - START")
req_body = jsonutils.dumps(self.test_credential_data)
def test_update_credentialDNE(self, credential_id='100'):
- """ Test update credential does not exist"""
+ """Test update credential does not exist."""
LOG.debug("test_update_credentialDNE - START")
rename_req_body = jsonutils.dumps({
def test_delete_credential(self):
- """ Test delete credential """
+ """Test delete credential."""
LOG.debug("test_delete_credential - START")
req_body = jsonutils.dumps(self.test_credential_data)
def test_delete_credentialDNE(self, credential_id='100'):
- """ Test delete credential does not exist """
+ """Test delete credential does not exist."""
LOG.debug("test_delete_credentialDNE - START")
delete_path_temp = self.cred_second_path + credential_id
class NexusDB(object):
- """Class consisting of methods to call nexus db methods"""
+ """Class consisting of methods to call nexus db methods."""
def get_all_nexusportbindings(self):
- """get all nexus port bindings"""
+ """get all nexus port bindings."""
bindings = []
try:
for bind in nexus_db.get_all_nexusport_bindings():
return bindings
def get_nexusportbinding(self, vlan_id):
- """get nexus port binding"""
+ """get nexus port binding."""
binding = []
try:
for bind in nexus_db.get_nexusport_binding(vlan_id):
return binding
def create_nexusportbinding(self, port_id, vlan_id):
- """create nexus port binding"""
+ """create nexus port binding."""
bind_dict = {}
try:
res = nexus_db.add_nexusport_binding(port_id, vlan_id)
LOG.error("Failed to create nexus binding: %s" % str(exc))
def delete_nexusportbinding(self, vlan_id):
- """delete nexus port binding"""
+ """delete nexus port binding."""
bindings = []
try:
bind = nexus_db.remove_nexusport_binding(vlan_id)
% str(exc))
def update_nexusport_binding(self, port_id, new_vlan_id):
- """update nexus port binding"""
+ """update nexus port binding."""
try:
res = nexus_db.update_nexusport_binding(port_id, new_vlan_id)
LOG.debug("Updating nexus port binding : %s" % res.port_id)
class L2networkDB(object):
- """Class conisting of methods to call L2network db methods"""
+ """Class conisting of methods to call L2network db methods."""
def get_all_vlan_bindings(self):
- """Get all vlan binding into a list of dict"""
+ """Get all vlan binding into a list of dict."""
vlans = []
try:
for vlan_bind in l2network_db.get_all_vlan_bindings():
return vlans
def get_vlan_binding(self, network_id):
- """Get a vlan binding"""
+ """Get a vlan binding."""
vlan = []
try:
for vlan_bind in l2network_db.get_vlan_binding(network_id):
return vlan
def create_vlan_binding(self, vlan_id, vlan_name, network_id):
- """Create a vlan binding"""
+ """Create a vlan binding."""
vlan_dict = {}
try:
res = l2network_db.add_vlan_binding(vlan_id, vlan_name, network_id)
LOG.error("Failed to create vlan binding: %s" % str(exc))
def delete_vlan_binding(self, network_id):
- """Delete a vlan binding"""
+ """Delete a vlan binding."""
try:
res = l2network_db.remove_vlan_binding(network_id)
LOG.debug("Deleted vlan binding for vlan: %s" % res.vlan_id)
raise Exception("Failed to delete vlan binding: %s" % str(exc))
def update_vlan_binding(self, network_id, vlan_id, vlan_name):
- """Update a vlan binding"""
+ """Update a vlan binding."""
try:
res = l2network_db.update_vlan_binding(network_id, vlan_id,
vlan_name)
class QuantumDB(object):
- """Class conisting of methods to call Quantum db methods"""
+ """Class conisting of methods to call Quantum db methods."""
def get_all_networks(self, tenant_id):
- """Get all networks"""
+ """Get all networks."""
nets = []
try:
for net in db.network_list(tenant_id):
return nets
def get_network(self, network_id):
- """Get a network"""
+ """Get a network."""
net = []
try:
for net in db.network_get(network_id):
return net
def create_network(self, tenant_id, net_name):
- """Create a network"""
+ """Create a network."""
net_dict = {}
try:
res = db.network_create(tenant_id, net_name)
LOG.error("Failed to create network: %s" % str(exc))
def delete_network(self, net_id):
- """Delete a network"""
+ """Delete a network."""
try:
net = db.network_destroy(net_id)
LOG.debug("Deleted network: %s" % net.uuid)
raise Exception("Failed to delete port: %s" % str(exc))
def update_network(self, tenant_id, net_id, **kwargs):
- """Update a network"""
+ """Update a network."""
try:
net = db.network_update(net_id, tenant_id, **kwargs)
LOG.debug("Updated network: %s" % net.uuid)
raise Exception("Failed to update network: %s" % str(exc))
def get_all_ports(self, net_id):
- """Get all ports"""
+ """Get all ports."""
ports = []
try:
for port in db.port_list(net_id):
LOG.error("Failed to get all ports: %s" % str(exc))
def get_port(self, net_id, port_id):
- """Get a port"""
+ """Get a port."""
port_list = []
port = db.port_get(net_id, port_id)
try:
LOG.error("Failed to get port: %s" % str(exc))
def create_port(self, net_id):
- """Add a port"""
+ """Add a port."""
port_dict = {}
try:
port = db.port_create(net_id)
LOG.error("Failed to create port: %s" % str(exc))
def delete_port(self, net_id, port_id):
- """Delete a port"""
+ """Delete a port."""
try:
port = db.port_destroy(net_id, port_id)
LOG.debug("Deleted port %s" % port.uuid)
raise Exception("Failed to delete port: %s" % str(exc))
def update_port(self, net_id, port_id, port_state):
- """Update a port"""
+ """Update a port."""
try:
port = db.port_set_state(net_id, port_id, port_state)
LOG.debug("Updated port %s" % port.uuid)
raise Exception("Failed to update port state: %s" % str(exc))
def plug_interface(self, net_id, port_id, int_id):
- """Plug interface to a port"""
+ """Plug interface to a port."""
try:
port = db.port_set_attachment(net_id, port_id, int_id)
LOG.debug("Attached interface to port %s" % port.uuid)
raise Exception("Failed to plug interface: %s" % str(exc))
def unplug_interface(self, net_id, port_id):
- """Unplug interface to a port"""
+ """Unplug interface to a port."""
try:
port = db.port_unset_attachment(net_id, port_id)
LOG.debug("Detached interface from port %s" % port.uuid)
class NexusDBTest(base.BaseTestCase):
- """Class conisting of nexus DB unit tests"""
+ """Class conisting of nexus DB unit tests."""
def setUp(self):
super(NexusDBTest, self).setUp()
- """Setup for nexus db tests"""
+ """Setup for nexus db tests."""
l2network_db.initialize()
self.addCleanup(db.clear_db)
self.dbtest = NexusDB()
LOG.debug("Setup")
def testa_create_nexusportbinding(self):
- """create nexus port binding"""
+ """create nexus port binding."""
binding1 = self.dbtest.create_nexusportbinding("port1", 10)
self.assertTrue(binding1["port-id"] == "port1")
self.tearDown_nexusportbinding()
def testb_getall_nexusportbindings(self):
- """get all nexus port binding"""
+ """get all nexus port binding."""
self.dbtest.create_nexusportbinding("port1", 10)
self.dbtest.create_nexusportbinding("port2", 10)
bindings = self.dbtest.get_all_nexusportbindings()
self.tearDown_nexusportbinding()
def testc_delete_nexusportbinding(self):
- """delete nexus port binding"""
+ """delete nexus port binding."""
self.dbtest.create_nexusportbinding("port1", 10)
self.dbtest.delete_nexusportbinding(10)
bindings = self.dbtest.get_all_nexusportbindings()
self.tearDown_nexusportbinding()
def testd_update_nexusportbinding(self):
- """update nexus port binding"""
+ """update nexus port binding."""
binding1 = self.dbtest.create_nexusportbinding("port1", 10)
binding1 = self.dbtest.update_nexusport_binding(binding1["port-id"],
20)
self.tearDown_nexusportbinding()
def tearDown_nexusportbinding(self):
- """tear down nexusport binding table"""
+ """tear down nexusport binding table."""
LOG.debug("Tearing Down Nexus port Bindings")
binds = self.dbtest.get_all_nexusportbindings()
for bind in binds:
class L2networkDBTest(base.BaseTestCase):
- """Class conisting of L2network DB unit tests"""
+ """Class conisting of L2network DB unit tests."""
def setUp(self):
- """Setup for tests"""
+ """Setup for tests."""
super(L2networkDBTest, self).setUp()
l2network_db.initialize()
self.dbtest = L2networkDB()
LOG.debug("Setup")
def testa_create_vlanbinding(self):
- """test add vlan binding"""
+ """test add vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
self.teardown_network()
def testb_getall_vlanbindings(self):
- """test get all vlan binding"""
+ """test get all vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
net2 = self.quantum.create_network("t1", "netid2")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.teardown_network()
def testc_delete_vlanbinding(self):
- """test delete vlan binding"""
+ """test delete vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
self.teardown_network()
def testd_update_vlanbinding(self):
- """test update vlan binding"""
+ """test update vlan binding."""
net1 = self.quantum.create_network("t1", "netid1")
vlan1 = self.dbtest.create_vlan_binding(10, "vlan1", net1["net-id"])
self.assertTrue(vlan1["vlan-id"] == "10")
self.teardown_network()
def testm_test_vlanids(self):
- """test vlanid methods"""
+ """test vlanid methods."""
l2network_db.create_vlanids()
vlanids = l2network_db.get_all_vlanids()
self.assertTrue(len(vlanids) > 0)
#counting on default teardown here to clear db
def teardown_network(self):
- """tearDown Network table"""
+ """tearDown Network table."""
LOG.debug("Tearing Down Network")
nets = self.quantum.get_all_networks("t1")
for net in nets:
self.quantum.delete_network(netid)
def teardown_port(self):
- """tearDown Port table"""
+ """tearDown Port table."""
LOG.debug("Tearing Down Port")
nets = self.quantum.get_all_networks("t1")
for net in nets:
self.quantum.delete_port(netid, portid)
def teardown_vlanbinding(self):
- """tearDown VlanBinding table"""
+ """tearDown VlanBinding table."""
LOG.debug("Tearing Down Vlan Binding")
vlans = self.dbtest.get_all_vlan_bindings()
for vlan in vlans:
class QuantumDBTest(base.BaseTestCase):
- """Class conisting of Quantum DB unit tests"""
+ """Class conisting of Quantum DB unit tests."""
def setUp(self):
- """Setup for tests"""
+ """Setup for tests."""
super(QuantumDBTest, self).setUp()
l2network_db.initialize()
self.addCleanup(db.clear_db)
LOG.debug("Setup")
def testa_create_network(self):
- """test to create network"""
+ """test to create network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
self.teardown_network_port()
def testb_get_networks(self):
- """test to get all networks"""
+ """test to get all networks."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
net2 = self.dbtest.create_network(self.tenant_id, "plugin_test2")
self.teardown_network_port()
def testc_delete_network(self):
- """test to delete network"""
+ """test to delete network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
self.dbtest.delete_network(net1["net-id"])
self.teardown_network_port()
def testd_update_network(self):
- """test to update (rename) network"""
+ """test to update (rename) network."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
self.assertTrue(net1["net-name"] == "plugin_test1")
net = self.dbtest.update_network(self.tenant_id, net1["net-id"],
self.teardown_network_port()
def teste_create_port(self):
- """test to create port"""
+ """test to create port."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port["net-id"] == net1["net-id"])
self.teardown_network_port()
def testf_delete_port(self):
- """test to delete port"""
+ """test to delete port."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port["net-id"] == net1["net-id"])
self.teardown_network_port()
def testg_plug_unplug_interface(self):
- """test to plug/unplug interface"""
+ """test to plug/unplug interface."""
net1 = self.dbtest.create_network(self.tenant_id, "plugin_test1")
port1 = self.dbtest.create_port(net1["net-id"])
self.dbtest.plug_interface(net1["net-id"], port1["port-id"], "vif1.1")
self.teardown_network_port()
def testh_joined_test(self):
- """test to get network and port"""
+ """test to get network and port."""
net1 = self.dbtest.create_network("t1", "net1")
port1 = self.dbtest.create_port(net1["net-id"])
self.assertTrue(port1["net-id"] == net1["net-id"])
self.teardown_joined_test()
def teardown_network_port(self):
- """tearDown for Network and Port table"""
+ """tearDown for Network and Port table."""
networks = self.dbtest.get_all_networks(self.tenant_id)
for net in networks:
netid = net["net-id"]
self.dbtest.delete_network(netid)
def teardown_joined_test(self):
- """tearDown for joined Network and Port test"""
+ """tearDown for joined Network and Port test."""
LOG.debug("Tearing Down Network and Ports")
nets = self.dbtest.get_all_networks("t1")
for net in nets:
#Nothing to do
pass
elif network_type == constants.TYPE_LOCAL:
- #TODO (alexpilotti): Check that the switch type is private
+ #TODO(alexpilotti): Check that the switch type is private
#or create it if not existing
pass
else:
- raise utils.HyperVException(_("Cannot provision unknown network "
- "type %s for network %s"),
- network_type, net_uuid)
+ raise utils.HyperVException(
+ _("Cannot provision unknown network type %(network_type)s "
+ "for network %(net_uuid)s"),
+ dict(network_type=network_type, net_uuid=net_uuid))
map = {
'network_type': network_type,
self._utils.connect_vnic_to_vswitch(map['vswitch_name'], port_id)
if network_type == constants.TYPE_VLAN:
- LOG.info(_('Binding VLAN ID %s to switch port %s'),
- segmentation_id, port_id)
+ LOG.info(_('Binding VLAN ID %(segmentation_id)s '
+ 'to switch port %(port_id)s'),
+ dict(segmentation_id=segmentation_id, port_id=port_id))
self._utils.set_vswitch_port_vlan_id(
segmentation_id,
port_id)
self.agent_id)
except Exception as e:
LOG.debug(_(
- "Unable to get port details for device %s: %s"),
- device, e)
+ "Unable to get port details for device %(device)s: %(e)s"),
+ dict(device=device, e=e))
resync = True
continue
if 'port_id' in device_details:
LOG.info(_(
"Port %(device)s updated. Details: %(device_details)s") %
- locals())
+ dict(device=device, device_details=device_details))
self._treat_vif_port(
device_details['port_id'],
device_details['network_id'],
device,
self.agent_id)
except Exception as e:
- LOG.debug(_("Removing port failed for device %s: %s"),
- device, e)
+ LOG.debug(
+ _("Removing port failed for device %(device)s: %(e)s"),
+ dict(device=device, e=e))
resync = True
continue
self._port_unbound(device)
self._check_job_status(ret_val, job_path)
def _check_job_status(self, ret_val, jobpath):
- """Poll WMI job state for completion"""
+ """Poll WMI job state for completion."""
if not ret_val:
return
elif ret_val != WMI_JOB_STATE_RUNNING:
- raise HyperVException(msg=_('Job failed with error %d' % ret_val))
+ raise HyperVException(msg=_('Job failed with error %d') % ret_val)
job_wmi_path = jobpath.replace('\\', '/')
job = wmi.WMI(moniker=job_wmi_path)
locals())
def _create_switch_port(self, vswitch_name, switch_port_name):
- """ Creates a switch port """
+ """Creates a switch port."""
switch_svc = self._conn.Msvm_VirtualSwitchManagementService()[0]
vswitch_path = self._get_vswitch(vswitch_name).path_()
(new_port, ret_val) = switch_svc.CreateSwitchPort(
def disconnect_switch_port(
self, vswitch_name, switch_port_name, delete_port):
- """ Disconnects the switch port """
+ """Disconnects the switch port."""
switch_svc = self._conn.Msvm_VirtualSwitchManagementService()[0]
switch_port_path = self._get_switch_port_path_by_name(
switch_port_name)
session.delete(alloc)
def sync_vlan_allocations(self, network_vlan_ranges):
- """Synchronize vlan_allocations table with configured VLAN ranges"""
+ """Synchronize vlan_allocations table with configured VLAN ranges."""
session = db_api.get_session()
with session.begin():
class VlanAllocation(model_base.BASEV2):
- """Represents allocation state of vlan_id on physical network"""
+ """Represents allocation state of vlan_id on physical network."""
__tablename__ = 'hyperv_vlan_allocations'
physical_network = Column(String(64), nullable=False, primary_key=True)
class NetworkBinding(model_base.BASEV2):
- """Represents binding of virtual network to physical realization"""
+ """Represents binding of virtual network to physical realization."""
__tablename__ = 'hyperv_network_bindings'
network_id = Column(String(36),
return q_rpc.PluginRpcDispatcher([self])
def get_device_details(self, rpc_context, **kwargs):
- """Agent requests device details"""
+ """Agent requests device details."""
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s details requested from %(agent_id)s"),
return entry
def update_device_down(self, rpc_context, **kwargs):
- """Device no longer exists on agent"""
- # (TODO) garyk - live migration and port status
+ """Device no longer exists on agent."""
+ # TODO(garyk) - live migration and port status
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"),
def tunnel_sync(self, rpc_context, **kwargs):
"""Dummy function for ovs agent running on Linux to
- work with Hyper-V plugin and agent."""
+ work with Hyper-V plugin and agent.
+ """
entry = dict()
entry['tunnels'] = {}
# Return the list of tunnels IP's to the agent
def get_network_state(physical_network, vlan_id):
- """Get state of specified network"""
+ """Get state of specified network."""
session = db.get_session()
try:
def get_port_from_device(device):
- """Get port from database"""
+ """Get port from database."""
LOG.debug(_("get_port_from_device() called"))
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
def set_port_status(port_id, status):
- """Set the port status"""
+ """Set the port status."""
LOG.debug(_("set_port_status as %s called"), status)
session = db.get_session()
try:
class NetworkState(model_base.BASEV2):
- """Represents state of vlan_id on physical network"""
+ """Represents state of vlan_id on physical network."""
__tablename__ = 'network_states'
physical_network = sa.Column(sa.String(64), nullable=False,
class NetworkBinding(model_base.BASEV2):
- """Represents binding of virtual network to physical_network and vlan_id"""
+ """Represents binding of virtual network to physical network and vlan."""
__tablename__ = 'network_bindings'
network_id = sa.Column(sa.String(36),
return port
def get_device_details(self, rpc_context, **kwargs):
- """Agent requests device details"""
+ """Agent requests device details."""
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s details requested from %(agent_id)s"),
return entry
def update_device_down(self, rpc_context, **kwargs):
- """Device no longer exists on agent"""
- # (TODO) garyk - live migration and port status
+ """Device no longer exists on agent."""
+ # TODO(garyk) - live migration and port status
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"),
return entry
def update_device_up(self, rpc_context, **kwargs):
- """Device is up on agent"""
+ """Device is up on agent."""
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s up %(agent_id)s"),
try:
meta_db_v2.add_network_flavor_binding(context.session,
flavor, str(net['id']))
- except:
+ except Exception:
LOG.exception(_('Failed to add flavor bindings'))
plugin.delete_network(context, net['id'])
raise FaildToAddFlavorBinding()
try:
subnet_in_db = super(ProxyPluginV2, self).create_subnet(
context, subnet)
- except:
+ except Exception:
self._get_client().delete_subnet(subnet_remote['id'])
return subnet_in_db
try:
network_in_db = super(ProxyPluginV2, self).create_network(
context, network)
- except:
+ except Exception:
self._get_client().delete_network(network_remote['id'])
return network_in_db
try:
port_in_db = super(ProxyPluginV2, self).create_port(
context, port)
- except:
+ except Exception:
self._get_client().delete_port(port_remote['id'])
return port_in_db
LOG.debug(_("MidonetPluginV2.create_router called: router=%r"), router)
if router['router']['admin_state_up'] is False:
- LOG.warning(_('Ignoreing admin_state_up=False for router=%r',
+ LOG.warning(_('Ignoring admin_state_up=False for router=%r. '
'Overriding with True'), router)
router['router']['admin_state_up'] = True
def update_ports(self, context, agent_id, datapath_id,
port_added, port_removed):
- """RPC to update information of ports on Quantum Server"""
+ """RPC to update information of ports on Quantum Server."""
LOG.info(_("Update ports: added=%(added)s, "
"removed=%(removed)s"),
{'added': port_added, 'removed': port_removed})
class OFCClient(object):
- """A HTTP/HTTPS client for OFC Drivers"""
+ """A HTTP/HTTPS client for OFC Drivers."""
def __init__(self, host="127.0.0.1", port=8888, use_ssl=False,
key_file=None, cert_file=None):
self.connection = None
def get_connection_type(self):
- """Returns the proper connection type"""
+ """Returns the proper connection type."""
if self.use_ssl:
return httplib.HTTPSConnection
else:
def get_port_from_device(port_id):
- """Get port from database"""
+ """Get port from database."""
LOG.debug(_("get_port_with_securitygroups() called:port_id=%s"), port_id)
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
from quantum.db import models_v2
-"""New mapping tables"""
+"""New mapping tables."""
class OFCId(object):
- """Resource ID on OpenFlow Controller"""
+ """Resource ID on OpenFlow Controller."""
ofc_id = sa.Column(sa.String(255), unique=True, nullable=False)
class QuantumId(object):
- """Logical ID on Quantum"""
+ """Logical ID on Quantum."""
quantum_id = sa.Column(sa.String(36), primary_key=True)
"""Represents a Filter on OpenFlow Network/Controller."""
-"""Old mapping tables"""
+"""Old mapping tables."""
class HasQuantumId(object):
- """Logical ID on Quantum"""
+ """Logical ID on Quantum."""
quantum_id = sa.Column(sa.String(36), nullable=False)
class PacketFilter(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
- """Represents a packet filter"""
+ """Represents a packet filter."""
network_id = sa.Column(sa.String(36),
sa.ForeignKey('networks.id', ondelete="CASCADE"),
nullable=False)
class NECPluginV2Base(db_base_plugin_v2.QuantumDbPluginV2):
- """ Base class of plugins that handle packet filters. """
+ """Base class of plugins that handle packet filters."""
def _make_packet_filter_dict(self, packet_filter, fields=None):
res = {'id': packet_filter['id'],
return False
def _generate_pfc_str(self, raw_str):
- """Generate PFC acceptable String"""
+ """Generate PFC acceptable String."""
return re.sub(r'[^0-9a-zA-Z]', '_', raw_str)
def _generate_pfc_id(self, id_str):
uuid_str = str(uuid.UUID(id_str)).replace('-', '')
uuid_no_version = uuid_str[:12] + uuid_str[13:]
return uuid_no_version[:31]
- except:
+ except Exception:
return self._generate_pfc_str(id_str)[:31]
def _generate_pfc_description(self, desc):
class TremaDriverBase(ofc_driver_base.OFCDriverBase):
- """Common class for Trema (Sliceable Switch) Drivers"""
+ """Common class for Trema (Sliceable Switch) Drivers."""
networks_path = "/networks"
network_path = "/networks/%s"
class TremaFilterDriver(object):
- """Trema (Sliceable Switch) PacketFilter Driver Mixin"""
+ """Trema (Sliceable Switch) PacketFilter Driver Mixin."""
filters_path = "/filters"
filter_path = "/filters/%s"
class NECPluginV2AgentNotifierApi(proxy.RpcProxy,
sg_rpc.SecurityGroupAgentRpcApiMixin):
- '''RPC API for NEC plugin agent'''
+ '''RPC API for NEC plugin agent.'''
BASE_RPC_API_VERSION = '1.0'
from quantum.api.v2 import attributes as attr
from quantum.api.v2 import base
from quantum.common import constants
-from quantum import context as q_context
from quantum.common import exceptions as q_exc
from quantum.common import rpc as q_rpc
from quantum.common import topics
+from quantum import context as q_context
from quantum.db import agents_db
from quantum.db import agentschedulers_db
from quantum.db import api as db
from quantum.extensions import securitygroup as ext_sg
from quantum.openstack.common import importutils
from quantum.openstack.common import rpc
-from quantum.plugins.nicira.common import metadata_access as nvp_meta
-from quantum.plugins.nicira.common import securitygroups as nvp_sec
-from quantum import policy
from quantum.plugins.nicira.common import config
from quantum.plugins.nicira.common import exceptions as nvp_exc
+from quantum.plugins.nicira.common import metadata_access as nvp_meta
+from quantum.plugins.nicira.common import securitygroups as nvp_sec
from quantum.plugins.nicira.extensions import nvp_networkgw as networkgw
from quantum.plugins.nicira.extensions import nvp_qos as ext_qos
from quantum.plugins.nicira import nicira_db
from quantum.plugins.nicira.nvp_plugin_version import PLUGIN_VERSION
from quantum.plugins.nicira import NvpApiClient
from quantum.plugins.nicira import nvplib
+from quantum import policy
LOG = logging.getLogger("QuantumPlugin")
NVP_NOSNAT_RULES_ORDER = 10
# Provider network extension - allowed network types for the NVP Plugin
class NetworkTypes:
- """ Allowed provider network types for the NVP Plugin """
+ """Allowed provider network types for the NVP Plugin."""
L3_EXT = 'l3_ext'
STT = 'stt'
GRE = 'gre'
raise
def _build_ip_address_list(self, context, fixed_ips, subnet_ids=None):
- """ Build ip_addresses data structure for logical router port
+ """Build ip_addresses data structure for logical router port
No need to perform validation on IPs - this has already been
done in the l3_db mixin class
'router_id': router_id}))
def _get_port_by_device_id(self, context, device_id, device_owner):
- """ Retrieve ports associated with a specific device id.
+ """Retrieve ports associated with a specific device id.
Used for retrieving all quantum ports attached to a given router.
"""
device_owner=device_owner,).all()
def _find_router_subnets_cidrs(self, context, router_id):
- """ Retrieve subnets attached to the specified router """
+ """Retrieve subnets attached to the specified router."""
ports = self._get_port_by_device_id(context, router_id,
l3_db.DEVICE_OWNER_ROUTER_INTF)
# No need to check for overlapping CIDRs
cluster, network, network_binding, max_ports,
allow_extra_lswitches)
except NvpApiClient.NvpApiException:
- err_desc = _(("An exception occured while selecting logical "
- "switch for the port"))
+ err_desc = _("An exception occured while selecting logical "
+ "switch for the port")
LOG.exception(err_desc)
raise nvp_exc.NvpPluginException(err_msg=err_desc)
port_data[ext_qos.QUEUE])
def _nvp_create_port(self, context, port_data):
- """ Driver for creating a logical switch port on NVP platform """
+ """Driver for creating a logical switch port on NVP platform."""
# FIXME(salvatore-orlando): On the NVP platform we do not really have
# external networks. So if as user tries and create a "regular" VIF
# port on an external network we are unable to actually create.
self._nvp_delete_port(context, port_data)
def _nvp_create_router_port(self, context, port_data):
- """ Driver for creating a switch port to be connected to a router """
+ """Driver for creating a switch port to be connected to a router."""
# No router ports on external networks!
if self._network_is_external(context, port_data['network_id']):
raise nvp_exc.NvpPluginException(
return lr_port
def _nvp_create_ext_gw_port(self, context, port_data):
- """ Driver for creating an external gateway port on NVP platform """
+ """Driver for creating an external gateway port on NVP platform."""
# TODO(salvatore-orlando): Handle NVP resource
# rollback when something goes not quite as expected
lr_port = self._find_router_gw_port(context, port_data)
'router_id': router_id})
def _nvp_create_l2_gw_port(self, context, port_data):
- """ Create a switch port, and attach it to a L2 gateway attachment """
+ """Create a switch port, and attach it to a L2 gateway attachment."""
# FIXME(salvatore-orlando): On the NVP platform we do not really have
# external networks. So if as user tries and create a "regular" VIF
# port on an external network we are unable to actually create.
pass
def _nvp_get_port_id(self, context, cluster, quantum_port):
- """ Return the NVP port uuid for a given quantum port.
+ """Return the NVP port uuid for a given quantum port.
First, look up the Quantum database. If not found, execute
a query on NVP platform as the mapping might be missing because
- the port was created before upgrading to grizzly. """
+ the port was created before upgrading to grizzly.
+ """
nvp_port_id = nicira_db.get_nvp_port_id(context.session,
quantum_port['id'])
if nvp_port_id:
quantum_port['id'],
nvp_port['uuid'])
return nvp_port['uuid']
- except:
+ except Exception:
LOG.exception(_("Unable to find NVP uuid for Quantum port %s"),
quantum_port['id'])
def _extend_fault_map(self):
- """ Extends the Quantum Fault Map
+ """Extends the Quantum Fault Map
Exceptions specific to the NVP Plugin are mapped to standard
HTTP Exceptions
raise nvp_exc.NvpInvalidNovaZone(nova_zone=novazone_id)
def _find_target_cluster(self, resource):
- """ Return cluster where configuration should be applied
+ """Return cluster where configuration should be applied
If the resource being configured has a paremeter expressing
the zone id (nova_id), then select corresponding cluster,
allow_extra_lswitches):
lswitches = nvplib.get_lswitches(cluster, network.id)
try:
- # TODO find main_ls too!
+ # TODO(savatore-orlando) Find main_ls too!
return [ls for ls in lswitches
if (ls['_relations']['LogicalSwitchStatus']
['lport_count'] < max_ports)].pop(0)
def _get_lswitch_cluster_pairs(self, netw_id, tenant_id):
"""Figure out the set of lswitches on each cluster that maps to this
- network id"""
+ network id
+ """
pairs = []
for c in self.clusters.itervalues():
lswitches = []
try:
ret_port['status'] = nvplib.get_port_status(
self.default_cluster, ret_port['network_id'], nvp_port_id)
- except:
+ except Exception:
LOG.warn(_("Unable to retrieve port status for:%s."), nvp_port_id)
return ret_port
# If there's no nvp IP do not bother going to NVP and put
# the port in error state
if nvp_id:
- #TODO: pass the appropriate cluster here
+ #TODO(salvatore-orlando): pass the appropriate cluster here
try:
port = nvplib.get_logical_port_status(
self.default_cluster, quantum_db_port['network_id'],
ips_to_remove=nvp_floating_ips)
def _update_fip_assoc(self, context, fip, floatingip_db, external_port):
- """ Update floating IP association data.
+ """Update floating IP association data.
Overrides method from base class.
The method is augmented for creating NAT rules in the process.
super(NvpPluginV2, self).disassociate_floatingips(context, port_id)
def create_network_gateway(self, context, network_gateway):
- """ Create a layer-2 network gateway
+ """Create a layer-2 network gateway
Create the gateway service on NVP platform and corresponding data
structures in Quantum datase
network_gateway)
def delete_network_gateway(self, context, id):
- """ Remove a layer-2 network gateway
+ """Remove a layer-2 network gateway
Remove the gateway service from NVP platform and corresponding data
structures in Quantum datase
context, security_group_id)
def create_security_group_rule(self, context, security_group_rule):
- """create a single security group rule"""
+ """create a single security group rule."""
bulk_rule = {'security_group_rules': [security_group_rule]}
return self.create_security_group_rule_bulk(context, bulk_rule)[0]
def create_security_group_rule_bulk(self, context, security_group_rule):
- """ create security group rules
+ """create security group rules
:param security_group_rule: list of rules to create
"""
s = security_group_rule.get('security_group_rules')
context, security_group_rule)
def delete_security_group_rule(self, context, sgrid):
- """ Delete a security group rule
+ """Delete a security group rule
:param sgrid: security group id to remove.
"""
with context.session.begin(subtransactions=True):
from abc import ABCMeta
import httplib
-import time
import logging
+import time
from quantum.plugins.nicira.api_client.common import (
import time
from quantum.plugins.nicira.api_client import client
-from quantum.plugins.nicira.api_client import (
- request_eventlet)
+from quantum.plugins.nicira.api_client import request_eventlet
eventlet.monkey_patch()
# License for the specific language governing permissions and limitations
# under the License.
-""" NVP Plugin exceptions """
+"""NVP Plugin exceptions"""
from quantum.common import exceptions as q_exc
return self._convert_to_nvp_rules(rules, with_id)
def _get_profile_uuid(self, context, remote_group_id):
- """Return profile id from novas group id. """
+ """Return profile id from novas group id."""
security_group = self.get_security_group(context, remote_group_id)
if not security_group:
raise ext_sg.SecurityGroupNotFound(id=remote_group_id)
def _validate_device_list(data, valid_values=None):
- """ Validate the list of service definitions. """
+ """Validate the list of service definitions."""
if not data:
# Devices must be provided
msg = _("Cannot create a gateway with an empty device list")
class Nvp_networkgw(object):
- """ API extension for Layer-2 Gateway support.
+ """API extension for Layer-2 Gateway support.
The Layer-2 gateway feature allows for connecting quantum networks
with external networks at the layer-2 level. No assumption is made on
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
plugin = manager.QuantumManager.get_plugin()
params = RESOURCE_ATTRIBUTE_MAP.get(COLLECTION_NAME, dict())
from abc import abstractmethod
+from quantum.api import extensions
from quantum.api.v2 import attributes as attr
from quantum.api.v2 import base
-from quantum.api import extensions
from quantum.common import exceptions as qexception
from quantum import manager
class Nvp_qos(object):
- """Port Queue extension"""
+ """Port Queue extension."""
@classmethod
def get_name(cls):
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
exts = []
plugin = manager.QuantumManager.get_plugin()
resource_name = 'qos_queue'
class NetworkConnection(model_base.BASEV2, models_v2.HasTenant):
- """ Defines a connection between a network gateway and a network """
+ """Defines a connection between a network gateway and a network."""
# We use port_id as the primary key as one can connect a gateway
# to a network in multiple ways (and we cannot use the same port form
# more than a single gateway)
class NetworkGateway(model_base.BASEV2, models_v2.HasId,
models_v2.HasTenant):
- """ Defines the data model for a network gateway """
+ """Defines the data model for a network gateway."""
name = sa.Column(sa.String(255))
# Tenant id is nullable for this resource
tenant_id = sa.Column(sa.String(36))
gw['default'] = True
def prevent_network_gateway_port_deletion(self, context, port):
- """ Pre-deletion check.
+ """Pre-deletion check.
Ensures a port will not be deleted if is being used by a network
gateway. In that case an exception will be raised.
def get_cluster_version(cluster):
- """Return major/minor version #"""
+ """Return major/minor version #."""
# Get control-cluster nodes
uri = "/ws.v1/control-cluster/node?_page_length=1&fields=uuid"
try:
def do_single_request(*args, **kwargs):
"""Issue a request to a specified cluster if specified via kwargs
- (cluster=<cluster>)."""
+ (cluster=<cluster>).
+ """
cluster = kwargs["cluster"]
try:
req = cluster.api_client.request(*args)
def do_multi_request(*args, **kwargs):
- """Issue a request to all clusters"""
+ """Issue a request to all clusters."""
results = []
clusters = kwargs["clusters"]
for x in clusters:
def create_l2_gw_service(cluster, tenant_id, display_name, devices):
- """ Create a NVP Layer-2 Network Gateway Service.
+ """Create a NVP Layer-2 Network Gateway Service.
:param cluster: The target NVP cluster
:param tenant_id: Identifier of the Openstack tenant for which
def create_lrouter(cluster, tenant_id, display_name, nexthop):
- """ Create a NVP logical router on the specified cluster.
+ """Create a NVP logical router on the specified cluster.
:param cluster: The target NVP cluster
:param tenant_id: Identifier of the Openstack tenant for which
display_name, device_id, admin_status_enabled,
mac_address=None, fixed_ips=None, port_security_enabled=None,
security_profiles=None, queue_id=None):
- """ Creates a logical port on the assigned logical switch """
+ """Creates a logical port on the assigned logical switch."""
# device_id can be longer than 40 so we rehash it
hashed_device_id = hashlib.sha1(device_id).hexdigest()
display_name = _check_and_truncate_name(display_name)
def create_router_lport(cluster, lrouter_uuid, tenant_id, quantum_port_id,
display_name, admin_status_enabled, ip_addresses):
- """ Creates a logical port on the assigned logical router """
+ """Creates a logical port on the assigned logical router."""
tags = [dict(scope='os_tid', tag=tenant_id),
dict(scope='q_port_id', tag=quantum_port_id)]
lport_obj = dict(
def update_router_lport(cluster, lrouter_uuid, lrouter_port_uuid,
tenant_id, quantum_port_id, display_name,
admin_status_enabled, ip_addresses):
- """ Updates a logical port on the assigned logical router """
+ """Updates a logical port on the assigned logical router."""
lport_obj = dict(
admin_status_enabled=admin_status_enabled,
display_name=display_name,
def delete_router_lport(cluster, lrouter_uuid, lport_uuid):
- """ Creates a logical port on the assigned logical router """
+ """Creates a logical port on the assigned logical router."""
path = _build_uri_path(LROUTERPORT_RESOURCE, lport_uuid, lrouter_uuid)
try:
do_single_request(HTTP_DELETE, path, cluster=cluster)
def find_router_gw_port(context, cluster, router_id):
- """ Retrieves the external gateway port for a NVP logical router """
+ """Retrieves the external gateway port for a NVP logical router."""
# Find the uuid of nvp ext gw logical router port
# TODO(salvatore-orlando): Consider storing it in Quantum DB
def get_port_status(cluster, lswitch_id, port_id):
- """Retrieve the operational status of the port"""
+ """Retrieve the operational status of the port."""
try:
r = do_single_request(HTTP_GET,
"/ws.v1/lswitch/%s/lport/%s/status" %
def plug_l2_gw_service(cluster, lswitch_id, lport_id,
gateway_id, vlan_id=None):
- """ Plug a Layer-2 Gateway Attachment object in a logical port """
+ """Plug a Layer-2 Gateway Attachment object in a logical port."""
att_obj = {'type': 'L2GatewayAttachment',
'l2_gateway_service_uuid': gateway_id}
if vlan_id:
def plug_interface(cluster, lswitch_id, port, type, attachment=None):
- """ Plug a VIF Attachment object in a logical port """
+ """Plug a VIF Attachment object in a logical port."""
lport_obj = {}
if attachment:
lport_obj["vif_uuid"] = attachment
:param args: a list of positional arguments.
:param kwargs: a list of keyworkds arguments.
:returns: the result of do_single_request loaded into a python object
- or None."""
+ or None.
+ """
res = do_single_request(*args, **kwargs)
if res:
return json.loads(res)
"""Convenience function creates and dumps dictionary to string.
:param kwargs: the key/value pirs to be dumped into a json string.
- :returns: a json string."""
+ :returns: a json string.
+ """
return json.dumps(kwargs, ensure_ascii=False)
:param tenant_id: the tenant_id to set.
:param taglist: the taglist to append to (or None).
:returns: a new taglist that includes the old taglist with the new
- tenant_id tag set."""
+ tenant_id tag set.
+ """
new_taglist = []
if taglist:
new_taglist = [x for x in taglist if x['scope'] != TENANT_ID_SCOPE]
# NVP API Calls for check_nvp_config utility
# -----------------------------------------------------------------------------
def check_cluster_connectivity(cluster):
- """Make sure that we can issue a request to each of the cluster nodes"""
+ """Make sure that we can issue a request to each of the cluster nodes."""
try:
resp = do_single_request(HTTP_GET, "/ws.v1/control-cluster",
cluster=cluster)
return (self and other
and self.id == other.id
and self.admin_state_up == other.admin_state_up)
- except:
+ except Exception:
return False
def __ne__(self, other):
:param net_uuid: the network uuid associated with this vlan.
:param lvm: a LocalVLANMapping object that tracks (vlan, lsw_id,
- vif_ids) mapping.'''
+ vif_ids) mapping.
+ '''
LOG.info(_("Reclaiming vlan = %(vlan_id)s from net-id = %(net_uuid)s"),
{'vlan_id': lvm.vlan,
'net_uuid': net_uuid})
VIF.
:param vif_id: the id of the vif
- :param net_uuid: the net_uuid this port is associated with.'''
+ :param net_uuid: the net_uuid this port is associated with.
+ '''
if net_uuid is None:
net_uuid = self.get_net_uuid(vif_id)
def port_dead(self, port):
'''Once a port has no binding, put it on the "dead vlan".
- :param port: a ovs_lib.VifPort object.'''
+ :param port: a ovs_lib.VifPort object.
+ '''
self.int_br.set_db_attribute("Port", port.port_name, "tag",
DEAD_VLAN_TAG)
self.int_br.add_flow(priority=2, in_port=port.ofport, actions="drop")
Creates tunnel bridge, and links it to the integration bridge
using a patch port.
- :param tun_br: the name of the tunnel bridge.'''
+ :param tun_br: the name of the tunnel bridge.
+ '''
self.tun_br = ovs_lib.OVSBridge(tun_br, self.root_helper)
self.tun_br.reset_bridge()
self.patch_tun_ofport = self.int_br.add_patch_port(
Creates physical network bridges and links them to the
integration bridge using veths.
- :param bridge_mappings: map physical network names to bridge names.'''
+ :param bridge_mappings: map physical network names to bridge names.
+ '''
self.phys_brs = {}
self.int_ofports = {}
self.phys_ofports = {}
sync = self.process_network_ports(port_info)
ports = port_info['current']
- except:
+ except Exception:
LOG.exception(_("Error in agent event loop"))
sync = True
tunnel_sync = True
def sync_vlan_allocations(network_vlan_ranges):
- """Synchronize vlan_allocations table with configured VLAN ranges"""
+ """Synchronize vlan_allocations table with configured VLAN ranges."""
session = db.get_session()
with session.begin():
def sync_tunnel_allocations(tunnel_id_ranges):
- """Synchronize tunnel_allocations table with configured tunnel ranges"""
+ """Synchronize tunnel_allocations table with configured tunnel ranges."""
# determine current configured allocatable tunnels
tunnel_ids = set()
def get_port_from_device(port_id):
- """Get port from database"""
+ """Get port from database."""
LOG.debug(_("get_port_with_securitygroups() called:port_id=%s"), port_id)
session = db.get_session()
sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
class VlanAllocation(model_base.BASEV2):
- """Represents allocation state of vlan_id on physical network"""
+ """Represents allocation state of vlan_id on physical network."""
__tablename__ = 'ovs_vlan_allocations'
physical_network = Column(String(64), nullable=False, primary_key=True)
class TunnelAllocation(model_base.BASEV2):
- """Represents allocation state of tunnel_id"""
+ """Represents allocation state of tunnel_id."""
__tablename__ = 'ovs_tunnel_allocations'
tunnel_id = Column(Integer, nullable=False, primary_key=True,
class NetworkBinding(model_base.BASEV2):
- """Represents binding of virtual network to physical realization"""
+ """Represents binding of virtual network to physical realization."""
__tablename__ = 'ovs_network_bindings'
network_id = Column(String(36),
class TunnelIP(model_base.BASEV2):
- """Represents tunnel endpoint in DB mode"""
+ """Represents tunnel endpoint in DB mode."""
__tablename__ = 'ovs_tunnel_ips'
ip_address = Column(String(255), primary_key=True)
class TunnelEndpoint(model_base.BASEV2):
- """Represents tunnel endpoint in RPC mode"""
+ """Represents tunnel endpoint in RPC mode."""
__tablename__ = 'ovs_tunnel_endpoints'
ip_address = Column(String(64), primary_key=True)
return port
def get_device_details(self, rpc_context, **kwargs):
- """Agent requests device details"""
+ """Agent requests device details."""
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s details requested from %(agent_id)s"),
return entry
def update_device_down(self, rpc_context, **kwargs):
- """Device no longer exists on agent"""
- # (TODO) garyk - live migration and port status
+ """Device no longer exists on agent."""
+ # TODO(garyk) - live migration and port status
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s no longer exists on %(agent_id)s"),
return entry
def update_device_up(self, rpc_context, **kwargs):
- """Device is up on agent"""
+ """Device is up on agent."""
agent_id = kwargs.get('agent_id')
device = kwargs.get('device')
LOG.debug(_("Device %(device)s up on %(agent_id)s"),
# @author: Edgar Magana, emagana@plumgrid.com, PLUMgrid, Inc.
-""" Quantum PLUMgrid Plugin exceptions """
+"""Quantum PLUMgrid Plugin exceptions"""
from quantum.common import exceptions as base_exec
self.topology_name = cfg.CONF.PLUMgridNOS.topologyname
self.snippets = plumgrid_nos_snippets.DataNOSPLUMgrid()
- # TODO: (Edgar) These are placeholders for next PLUMgrid release
+ # TODO(Edgar) These are placeholders for next PLUMgrid release
cfg.CONF.PLUMgridNOS.username
cfg.CONF.PLUMgridNOS.password
self.rest_conn = rest_connection.RestConnection(nos_plumgrid,
network)
try:
- LOG.debug(_('QuantumPluginPLUMgrid Status: %s, %s, %s'),
- tenant_id, network["network"], net["id"])
+ LOG.debug(_('QuantumPluginPLUMgrid Status: %(tenant_id)s, '
+ '%(network)s, %(network_id)s'),
+ dict(
+ tenant_id=tenant_id,
+ network=network["network"],
+ network_id=net["id"],
+ ))
nos_url = self.snippets.BASE_NOS_URL + net["id"]
headers = {}
body_data = self.snippets.create_domain_body_data(tenant_id)
self.rest_conn.nos_rest_conn(nos_url,
'PUT', body_data, headers)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
body_data = self.snippets.create_domain_body_data(tenant_id)
self.rest_conn.nos_rest_conn(nos_url,
'PUT', body_data, headers)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
body_data = {}
self.rest_conn.nos_rest_conn(nos_url,
'DELETE', body_data, headers)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
tenant_id, self.topology_name)
self.rest_conn.nos_rest_conn(nos_url,
'PUT', body_data, headers)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed: ")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
body_data = {}
net_id = subnet_details["network_id"]
self._cleaning_nos_subnet_structure(body_data, headers, net_id)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed: ")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
self.rest_conn.nos_rest_conn(nos_url,
'PUT', body_data, headers)
- except:
+ except Exception:
err_message = _("PLUMgrid NOS communication failed: ")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
"""
Extension API implementation
"""
- # TODO: (Edgar) Complete extensions for PLUMgrid
+ # TODO(Edgar) Complete extensions for PLUMgrid
"""
Internal PLUMgrid fuctions
LOG.warning(_("Network with admin_state_up=False are not "
"supported yet by this plugin. Ignoring "
"setting for network %s"), network_name)
- except:
+ except Exception:
err_message = _("Network Admin State Validation Falied: ")
LOG.Exception(err_message)
raise plum_excep.PLUMgridException(err_message)
headers['Content-type'] = 'application/json'
headers['Accept'] = 'application/json'
- LOG.debug(_("PLUMgrid_NOS_Server: %s %s %s"), self.server, self.port,
- action)
+ LOG.debug(_("PLUMgrid_NOS_Server: %(server)s %(port)s %(action)s"),
+ dict(server=self.server, port=self.port, action=action))
conn = httplib.HTTPConnection(self.server, self.port,
timeout=self.timeout)
return
try:
- LOG.debug(_("PLUMgrid_NOS_Server Sending Data: %s %s %s"),
- nos_url, body_data, headers)
+ LOG.debug(_("PLUMgrid_NOS_Server Sending Data: %(nos_url)s "
+ "%(body_data)s %(headers)s"),
+ dict(
+ nos_url=nos_url,
+ body_data=body_data,
+ headers=headers,
+ ))
conn.request(action, nos_url, body_data, headers)
resp = conn.getresponse()
resp_str = resp.read()
- LOG.debug(_("PLUMgrid_NOS_Server Connection Data: %s, %s"),
- resp, resp_str)
+ LOG.debug(_("PLUMgrid_NOS_Server Connection Data: %(resp)s, "
+ "%(resp_str)s"), dict(resp=resp, resp_str=resp_str))
if resp.status is httplib.OK:
try:
LOG.debug(_("Agent loop has new device"))
self._process_devices_filter(port_info)
ports = port_info['current']
- except:
+ except Exception:
LOG.exception(_("Error in agent event loop"))
elapsed = max(time.time() - start, 0)
tunnel_key = self.tunnel_key.allocate(session, net['id'])
try:
self._client_create_network(net['id'], tunnel_key)
- except:
+ except Exception:
self._client_delete_network(net['id'])
raise
"""Manage a cache of known devices."""
class Device(object):
- """Inner classes used to hold values for weakref lookups"""
+ """Inner classes used to hold values for weakref lookups."""
def __init__(self, port_id, pool_id):
self.port_id = port_id
self.pool_id = pool_id
def save_config(conf_path, logical_config, socket_path=None):
- """Convert a logical configuration to the HAProxy version"""
+ """Convert a logical configuration to the HAProxy version."""
data = []
data.extend(_build_global(logical_config, socket_path=socket_path))
data.extend(_build_defaults(logical_config))
def _get_server_health_option(config):
- """return the first active health option"""
+ """return the first active health option."""
for monitor in config['healthmonitors']:
if monitor['status'] == ACTIVE and monitor['admin_state_up']:
break
LOG.debug(msg, port_id)
def update_pool_stats(self, context, pool_id=None, stats=None, host=None):
- # TODO (markmcclain): add stats collection
+ # TODO(markmcclain): add stats collection
pass
class ServicePluginBase(extensions.PluginInterface):
- """ defines base interface for any Advanced Service plugin """
+ """defines base interface for any Advanced Service plugin."""
__metaclass__ = abc.ABCMeta
supported_extension_aliases = []
@abc.abstractmethod
def get_plugin_type(self):
- """ returns one of predefine service types. see
- quantum/plugins/common/constants.py """
+ """returns one of predefine service types. see
+ quantum/plugins/common/constants.py
+ """
pass
@abc.abstractmethod
def get_plugin_name(self):
- """ return a symbolic name for the plugin.
+ """return a symbolic name for the plugin.
Each service plugin should have a symbolic name. This name
will be used, for instance, by service definitions in service types
@abc.abstractmethod
def get_plugin_description(self):
- """ returns string description of the plugin """
+ """returns string description of the plugin."""
pass
def get_resource_and_action(action):
- """ Extract resource and action (write, read) from api operation """
+ """Extract resource and action (write, read) from api operation."""
data = action.split(':', 1)[0].split('_', 1)
return ("%ss" % data[-1], data[0] != 'get')
def _is_attribute_explicitly_set(attribute_name, resource, target):
- """Verify that an attribute is present and has a non-default value"""
+ """Verify that an attribute is present and has a non-default value."""
return ('default' in resource[attribute_name] and
attribute_name in target and
target[attribute_name] is not attributes.ATTR_NOT_SPECIFIED and
class CommandFilter(object):
- """Command filter only checking that the 1st argument matches exec_path"""
+ """Command filter only checking that the 1st argument matches exec_path."""
def __init__(self, exec_path, run_as, *args):
self.exec_path = exec_path
self.args = args
def match(self, userargs):
- """Only check that the first argument (command) matches exec_path"""
+ """Only check that the first argument (command) matches exec_path."""
return os.path.basename(self.exec_path) == userargs[0]
def get_command(self, userargs):
return [self.exec_path] + userargs[1:]
def get_environment(self, userargs):
- """Returns specific environment to set, None if none"""
+ """Returns specific environment to set, None if none."""
return None
class RegExpFilter(CommandFilter):
- """Command filter doing regexp matching for every argument"""
+ """Command filter doing regexp matching for every argument."""
def match(self, userargs):
# Early skip if command or number of args don't match
class DnsmasqFilter(CommandFilter):
- """Specific filter for the dnsmasq call (which includes env)"""
+ """Specific filter for the dnsmasq call (which includes env)."""
def is_dnsmasq_cmd(self, argv):
if (argv[0] == "dnsmasq"):
def match(self, userargs):
"""This matches the combination of the leading env
- vars plus "dnsmasq" """
+ vars plus "dnsmasq"
+ """
if (self.is_dnsmasq_env_vars(userargs) and
self.is_dnsmasq_cmd(userargs[2:])):
return True
class DnsmasqNetnsFilter(DnsmasqFilter):
- """Specific filter for the dnsmasq call (which includes env)"""
+ """Specific filter for the dnsmasq call (which includes env)."""
def is_ip_netns_cmd(self, argv):
if ((argv[0] == "ip") and
def match(self, userargs):
"""This matches the combination of the leading env
- vars plus "ip" "netns" "exec" <foo> "dnsmasq" """
+ vars plus "ip" "netns" "exec" <foo> "dnsmasq"
+ """
if (self.is_dnsmasq_env_vars(userargs) and
self.is_ip_netns_cmd(userargs[2:]) and
self.is_dnsmasq_cmd(userargs[6:])):
class ReadFileFilter(CommandFilter):
- """Specific filter for the utils.read_file_as_root call"""
+ """Specific filter for the utils.read_file_as_root call."""
def __init__(self, file_path, *args):
self.file_path = file_path
def build_filter(class_name, *args):
- """Returns a filter object of class class_name"""
+ """Returns a filter object of class class_name."""
if not hasattr(filters, class_name):
# TODO(jrd): Log the error (whenever quantum-rootwrap has a log file)
return None
def load_filters(filters_path):
- """Load filters from a list of directories"""
+ """Load filters from a list of directories."""
filterlist = []
for filterdir in filters_path:
if not os.path.isdir(filterdir):
from sqlalchemy.sql import exists
from quantum.common import constants
-from quantum.db import models_v2
from quantum.db import agents_db
from quantum.db import agentschedulers_db
+from quantum.db import models_v2
from quantum.openstack.common import log as logging
class ChanceScheduler(object):
"""Allocate a DHCP agent for a network in a random way.
More sophisticated scheduler (similar to filter scheduler in nova?)
- can be introduced later."""
+ can be introduced later.
+ """
def schedule(self, plugin, context, network):
"""Schedule the network to an active DHCP agent if there
def auto_schedule_networks(self, plugin, context, host):
"""Schedule non-hosted networks to the DHCP agent on
- the specified host."""
+ the specified host.
+ """
with context.session.begin(subtransactions=True):
query = context.session.query(agents_db.Agent)
query = query.filter(agents_db.Agent.agent_type ==
from sqlalchemy.sql import exists
from quantum.common import constants
-from quantum.db import l3_db
from quantum.db import agents_db
from quantum.db import agentschedulers_db
+from quantum.db import l3_db
from quantum.openstack.common import log as logging
class ChanceScheduler(object):
"""Allocate a L3 agent for a router in a random way.
More sophisticated scheduler (similar to filter scheduler in nova?)
- can be introduced later."""
+ can be introduced later.
+ """
def auto_schedule_routers(self, plugin, context, host, router_id):
"""Schedule non-hosted routers to L3 Agent running on host.
"""Service object for binaries running on hosts.
A service takes a manager and enables rpc by listening to queues based
- on topic. It also periodically runs tasks on the manager."""
+ on topic. It also periodically runs tasks on the manager.
+ """
def __init__(self, host, binary, topic, manager, report_interval=None,
periodic_interval=None, periodic_fuzzy_delay=None,
class TestBrocadeDb(test_plugin.QuantumDbPluginV2TestCase):
- """Test brocade db functionality"""
+ """Test brocade db functionality."""
def test_create_network(self):
"""Test brocade specific network db."""
#
# @author: Rohit Agarwalla, Cisco Systems, Inc.
-""" stubs.py provides interface methods for the database test cases """
+"""stubs.py provides interface methods for the database test cases"""
from quantum.db import api as db
from quantum.openstack.common import log as logging
class QuantumDB(object):
- """Class conisting of methods to call Quantum db methods"""
+ """Class conisting of methods to call Quantum db methods."""
def get_all_networks(self, tenant_id):
- """Get all networks"""
+ """Get all networks."""
nets = []
try:
for net in db.network_list(tenant_id):
return nets
def get_network(self, network_id):
- """Get a network"""
+ """Get a network."""
net = []
try:
for net in db.network_get(network_id):
return net
def create_network(self, tenant_id, net_name):
- """Create a network"""
+ """Create a network."""
net_dict = {}
try:
res = db.network_create(tenant_id, net_name)
LOG.error("Failed to create network: %s", str(exc))
def delete_network(self, net_id):
- """Delete a network"""
+ """Delete a network."""
try:
net = db.network_destroy(net_id)
LOG.debug("Deleted network: %s", net.uuid)
LOG.error("Failed to delete network: %s", str(exc))
def update_network(self, tenant_id, net_id, param_data):
- """Rename a network"""
+ """Rename a network."""
try:
print param_data
net = db.network_update(net_id, tenant_id, **param_data)
LOG.error("Failed to update network: %s", str(exc))
def get_all_ports(self, net_id):
- """Get all ports"""
+ """Get all ports."""
ports = []
try:
for port in db.port_list(net_id):
LOG.error("Failed to get all ports: %s", str(exc))
def get_port(self, net_id, port_id):
- """Get a port"""
+ """Get a port."""
port_list = []
port = db.port_get(port_id, net_id)
try:
LOG.error("Failed to get port: %s", str(exc))
def create_port(self, net_id):
- """Add a port"""
+ """Add a port."""
port_dict = {}
try:
port = db.port_create(net_id)
LOG.error("Failed to create port: %s", str(exc))
def delete_port(self, net_id, port_id):
- """Delete a port"""
+ """Delete a port."""
try:
port = db.port_destroy(port_id, net_id)
LOG.debug("Deleted port %s", port.uuid)
LOG.error("Failed to delete port: %s", str(exc))
def update_port(self, net_id, port_id, **kwargs):
- """Update a port"""
+ """Update a port."""
try:
port = db.port_update(port_id, net_id, **kwargs)
LOG.debug("Updated port %s", port.uuid)
LOG.error("Failed to update port state: %s", str(exc))
def plug_interface(self, net_id, port_id, int_id):
- """Plug interface to a port"""
+ """Plug interface to a port."""
try:
port = db.port_set_attachment(port_id, net_id, int_id)
LOG.debug("Attached interface to port %s", port.uuid)
LOG.error("Failed to plug interface: %s", str(exc))
def unplug_interface(self, net_id, port_id):
- """Unplug interface to a port"""
+ """Unplug interface to a port."""
try:
db.port_unset_attachment(port_id, net_id)
LOG.debug("Detached interface from port %s", port_id)
import webob.exc
-from quantum import context
from quantum.api.extensions import ExtensionMiddleware
from quantum.api.extensions import PluginAwareExtensionManager
from quantum.common import config
+from quantum import context
from quantum.db.loadbalancer import loadbalancer_db as ldb
import quantum.extensions
from quantum.extensions import loadbalancer
return vip
def test_create_vip_twice_for_same_pool(self):
- """ Test loadbalancer db plugin via extension and directly """
+ """Test loadbalancer db plugin via extension and directly."""
with self.subnet() as subnet:
with self.pool(name="pool1") as pool:
with self.vip(name='vip1', subnet=subnet, pool=pool):
@classmethod
def get_resources(cls):
- """ Returns Extended Resource for dummy management """
+ """Returns Extended Resource for dummy management."""
q_mgr = manager.QuantumManager.get_instance()
dummy_inst = q_mgr.get_service_plugins()['DUMMY']
controller = base.create_resource(
class DummyServicePlugin(ServicePluginBase):
- """ This is a simple plugin for managing instantes of a fictional 'dummy'
+ """This is a simple plugin for managing instantes of a fictional 'dummy'
service. This plugin is provided as a proof-of-concept of how
advanced service might leverage the service type extension.
Ideally, instances of real advanced services, such as load balancing
@classmethod
def get_resources(cls):
- """ Returns Ext Resources """
+ """Returns Ext Resources."""
exts = []
plugin = manager.QuantumManager.get_plugin()
resource_name = 'ext_test_resource'
# See the License for the specific language governing permissions and
# limitations under the License.
-from quantum.tests.unit.openvswitch import test_agent_scheduler
from quantum.tests.unit.linuxbridge import test_linuxbridge_plugin
+from quantum.tests.unit.openvswitch import test_agent_scheduler
class LbAgentSchedulerTestCase(
class MetaQuantumPluginV2Test(base.BaseTestCase):
- """Class conisting of MetaQuantumPluginV2 unit tests"""
+ """Class conisting of MetaQuantumPluginV2 unit tests."""
def setUp(self):
super(MetaQuantumPluginV2Test, self).setUp()
self.plugin.not_implemented()
except AttributeError:
return
- except:
+ except Exception:
self.fail("AttributeError Error is not raised")
self.fail("No Error is not raised")
# See the License for the specific language governing permissions and
# limitations under the License.
-from quantum.tests.unit.openvswitch import test_agent_scheduler
from quantum.tests.unit.nec import test_nec_plugin
+from quantum.tests.unit.openvswitch import test_agent_scheduler
class NecAgentSchedulerTestCase(
class NECPluginV2DBTestBase(base.BaseTestCase):
- """Class conisting of NECPluginV2 DB unit tests"""
+ """Class conisting of NECPluginV2 DB unit tests."""
def setUp(self):
- """Setup for tests"""
+ """Setup for tests."""
super(NECPluginV2DBTestBase, self).setUp()
ndb.initialize()
self.session = db_api.get_session()
self.addCleanup(ndb.clear_db)
def get_ofc_item_random_params(self):
- """create random parameters for ofc_item test"""
+ """create random parameters for ofc_item test."""
ofc_id = uuidutils.generate_uuid()
quantum_id = uuidutils.generate_uuid()
none = uuidutils.generate_uuid()
return ofc_id, quantum_id, none
def get_portinfo_random_params(self):
- """create random parameters for portinfo test"""
+ """create random parameters for portinfo test."""
port_id = uuidutils.generate_uuid()
datapath_id = hex(random.randint(0, 0xffffffff))
port_no = random.randint(1, 100)
class NECPluginV2DBTest(NECPluginV2DBTestBase):
def testa_add_ofc_item(self):
- """test add OFC item"""
+ """test add OFC item."""
o, q, n = self.get_ofc_item_random_params()
tenant = ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
self.assertEqual(tenant.ofc_id, o)
self.session, 'ofc_tenant', q, o)
def testb_get_ofc_item(self):
- """test get OFC item"""
+ """test get OFC item."""
o, q, n = self.get_ofc_item_random_params()
ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
tenant = ndb.get_ofc_item(self.session, 'ofc_tenant', q)
self.assertEqual(None, tenant_none)
def testb_get_ofc_id(self):
- """test get OFC d"""
+ """test get OFC d."""
o, q, n = self.get_ofc_item_random_params()
ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
tenant_id = ndb.get_ofc_id(self.session, 'ofc_tenant', q)
self.assertEqual(None, tenant_none)
def testb_exists_ofc_item(self):
- """test get OFC d"""
+ """test get OFC d."""
o, q, n = self.get_ofc_item_random_params()
ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
ret = ndb.exists_ofc_item(self.session, 'ofc_tenant', q)
self.assertEqual(None, tenant_none)
def testc_find_ofc_item(self):
- """test find OFC item"""
+ """test find OFC item."""
o, q, n = self.get_ofc_item_random_params()
ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
tenant = ndb.find_ofc_item(self.session, 'ofc_tenant', o)
self.assertEqual(None, tenant_none)
def testc_del_ofc_item(self):
- """test delete OFC item"""
+ """test delete OFC item."""
o, q, n = self.get_ofc_item_random_params()
ndb.add_ofc_item(self.session, 'ofc_tenant', q, o)
ndb.del_ofc_item(self.session, 'ofc_tenant', q)
self.assertEqual(None, tenant_none)
def testd_add_portinfo(self):
- """test add portinfo"""
+ """test add portinfo."""
i, d, p, v, m, n = self.get_portinfo_random_params()
portinfo = ndb.add_portinfo(self.session, i, d, p, v, m)
self.assertEqual(portinfo.id, i)
self.assertTrue(exception_raised)
def teste_get_portinfo(self):
- """test get portinfo"""
+ """test get portinfo."""
i, d, p, v, m, n = self.get_portinfo_random_params()
ndb.add_portinfo(self.session, i, d, p, v, m)
portinfo = ndb.get_portinfo(self.session, i)
self.assertEqual(None, portinfo_none)
def testf_del_portinfo(self):
- """test delete portinfo"""
+ """test delete portinfo."""
i, d, p, v, m, n = self.get_portinfo_random_params()
ndb.add_portinfo(self.session, i, d, p, v, m)
portinfo = ndb.get_portinfo(self.session, i)
class NECPluginV2DBOldMappingTest(NECPluginV2DBTestBase):
- """Test related to old ID mapping"""
+ """Test related to old ID mapping."""
# Mapping Table mode
OLD = True
import mock
-from quantum import context as q_context
-from quantum import manager
from quantum.common import topics
+from quantum import context as q_context
from quantum.extensions import portbindings
+from quantum import manager
from quantum.plugins.nec import nec_plugin
from quantum.tests.unit import _test_extension_portbindings as test_bindings
from quantum.tests.unit import test_db_plugin as test_plugin
class OFCManagerTestBase(base.BaseTestCase):
- """Class conisting of OFCManager unit tests"""
+ """Class conisting of OFCManager unit tests."""
def setUp(self):
super(OFCManagerTestBase, self).setUp()
self.ctx = context.get_admin_context()
def get_random_params(self):
- """create random parameters for portinfo test"""
+ """create random parameters for portinfo test."""
tenant = uuidutils.generate_uuid()
network = uuidutils.generate_uuid()
port = uuidutils.generate_uuid()
class OFCManagerTest(OFCManagerTestBase):
def testa_create_ofc_tenant(self):
- """test create ofc_tenant"""
+ """test create ofc_tenant."""
t, n, p, f, none = self.get_random_params()
self.assertFalse(ndb.get_ofc_item(self.ctx.session, 'ofc_tenant', t))
self.ofc.create_ofc_tenant(self.ctx, t)
self.assertEqual(tenant.ofc_id, "ofc-" + t[:-4])
def testb_exists_ofc_tenant(self):
- """test exists_ofc_tenant"""
+ """test exists_ofc_tenant."""
t, n, p, f, none = self.get_random_params()
self.assertFalse(self.ofc.exists_ofc_tenant(self.ctx, t))
self.ofc.create_ofc_tenant(self.ctx, t)
self.assertTrue(self.ofc.exists_ofc_tenant(self.ctx, t))
def testc_delete_ofc_tenant(self):
- """test delete ofc_tenant"""
+ """test delete ofc_tenant."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.assertTrue(ndb.get_ofc_item(self.ctx.session, 'ofc_tenant', t))
self.assertFalse(ndb.get_ofc_item(self.ctx.session, 'ofc_tenant', t))
def testd_create_ofc_network(self):
- """test create ofc_network"""
+ """test create ofc_network."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.assertFalse(ndb.get_ofc_item(self.ctx.session, 'ofc_network', n))
self.assertEqual(network.ofc_id, "ofc-" + n[:-4])
def teste_exists_ofc_network(self):
- """test exists_ofc_network"""
+ """test exists_ofc_network."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.assertFalse(self.ofc.exists_ofc_network(self.ctx, n))
self.assertTrue(self.ofc.exists_ofc_network(self.ctx, n))
def testf_delete_ofc_network(self):
- """test delete ofc_network"""
+ """test delete ofc_network."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertFalse(ndb.get_ofc_item(self.ctx.session, 'ofc_network', n))
def testg_create_ofc_port(self):
- """test create ofc_port"""
+ """test create ofc_port."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertEqual(port.ofc_id, "ofc-" + p[:-4])
def testh_exists_ofc_port(self):
- """test exists_ofc_port"""
+ """test exists_ofc_port."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertTrue(self.ofc.exists_ofc_port(self.ctx, p))
def testi_delete_ofc_port(self):
- """test delete ofc_port"""
+ """test delete ofc_port."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertFalse(ndb.get_ofc_item(self.ctx.session, 'ofc_port', p))
def testj_create_ofc_packet_filter(self):
- """test create ofc_filter"""
+ """test create ofc_filter."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertEqual(_filter.ofc_id, "ofc-" + f[:-4])
def testk_exists_ofc_packet_filter(self):
- """test exists_ofc_packet_filter"""
+ """test exists_ofc_packet_filter."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
self.assertTrue(self.ofc.exists_ofc_packet_filter(self.ctx, f))
def testl_delete_ofc_packet_filter(self):
- """test delete ofc_filter"""
+ """test delete ofc_filter."""
t, n, p, f, none = self.get_random_params()
self.ofc.create_ofc_tenant(self.ctx, t)
self.ofc.create_ofc_network(self.ctx, t, n)
class TestConfig(object):
- """Configuration for this test"""
+ """Configuration for this test."""
host = '127.0.0.1'
port = 8888
use_ssl = False
def _ofc(id):
- """OFC ID converter"""
+ """OFC ID converter."""
return "ofc-%s" % id
self.addCleanup(self.mox.UnsetStubs)
def get_ofc_item_random_params(self):
- """create random parameters for ofc_item test"""
+ """create random parameters for ofc_item test."""
tenant_id = uuidutils.generate_uuid()
network_id = uuidutils.generate_uuid()
port_id = uuidutils.generate_uuid()
class TestConfig(object):
- """Configuration for this test"""
+ """Configuration for this test."""
host = '127.0.0.1'
port = 8888
self.addCleanup(self.mox.UnsetStubs)
def get_ofc_item_random_params(self):
- """create random parameters for ofc_item test"""
+ """create random parameters for ofc_item test."""
tenant_id = uuidutils.generate_uuid()
network_id = uuidutils.generate_uuid()
port_id = uuidutils.generate_uuid()
class TremaFilterDriverTest(TremaDriverTestBase):
def get_ofc_item_random_params(self):
- """create random parameters for ofc_item test"""
+ """create random parameters for ofc_item test."""
t, n, p = (super(TremaFilterDriverTest, self).
get_ofc_item_random_params())
filter_id = uuidutils.generate_uuid()
def _lswitch_match(res_uuid):
# verify that the switch exist
if parent_uuid and not parent_uuid in self._fake_lswitch_dict:
- raise Exception(_("lswitch:%s not found" % parent_uuid))
+ raise Exception(_("lswitch:%s not found") % parent_uuid)
if (not parent_uuid
or res_dict[res_uuid].get('ls_uuid') == parent_uuid):
return True
def _lrouter_match(res_uuid):
# verify that the router exist
if parent_uuid and not parent_uuid in self._fake_lrouter_dict:
- raise Exception(_("lrouter:%s not found" % parent_uuid))
+ raise Exception(_("lrouter:%s not found") % parent_uuid)
if (not parent_uuid or
res_dict[res_uuid].get('lr_uuid') == parent_uuid):
return True
class NetworkGatewayDbTestCase(test_db_plugin.QuantumDbPluginV2TestCase):
- """ Unit tests for Network Gateway DB support """
+ """Unit tests for Network Gateway DB support."""
def setUp(self):
test_config['plugin_name_v2'] = '%s.%s' % (
class TestNetworkGatewayPlugin(db_base_plugin_v2.QuantumDbPluginV2,
nicira_networkgw_db.NetworkGatewayMixin):
- """ Simple plugin class for testing db support for network gateway ext """
+ """Simple plugin class for testing db support for network gateway ext."""
supported_extension_aliases = ["network-gateway"]
self.assertEqual(net['network'][k], v)
def _nvp_validate_ext_gw(self, router_id, l3_gw_uuid, vlan_id):
- """ Verify data on fake NVP API client in order to validate
- plugin did set them properly"""
+ """Verify data on fake NVP API client in order to validate
+ plugin did set them properly
+ """
ports = [port for port in self.fc._fake_lrouter_lport_dict.values()
if (port['lr_uuid'] == router_id and
port['att_type'] == "L3GatewayAttachment")]
from quantum.openstack.common import timeutils
from quantum.openstack.common import uuidutils
from quantum.tests.unit import test_agent_ext_plugin
-from quantum.tests.unit.testlib_api import create_request
from quantum.tests.unit import test_db_plugin as test_plugin
from quantum.tests.unit import test_extensions
from quantum.tests.unit import test_l3_plugin
+from quantum.tests.unit.testlib_api import create_request
from quantum.wsgi import Serializer
L3_HOSTA = 'hosta'
self.addCleanup(self.mox.UnsetStubs)
def test_vifport(self):
- """create and stringify vif port, confirm no exceptions"""
+ """create and stringify vif port, confirm no exceptions."""
self.mox.ReplayAll()
pname = "vif1.0"
# If something goes wrong, mox.VerifyAll() will catch it
try:
q_agent.daemon_loop()
- except:
+ except Exception:
pass
self.mox.VerifyAll()
class ConfigurationTest(base.BaseTestCase):
- """Configuration file Tests"""
+ """Configuration file Tests."""
def test_defaults(self):
self.assertEqual('br-int', cfg.CONF.OVS.integration_bridge)
self.assertEqual(2, cfg.CONF.AGENT.polling_interval)
import mock
from quantum import context
-from quantum import manager
from quantum.db.loadbalancer import loadbalancer_db as ldb
+from quantum import manager
from quantum.openstack.common import uuidutils
from quantum.plugins.common import constants
from quantum.plugins.services.agent_loadbalancer import plugin
class _ArgMatcher(object):
- """ An adapter to assist mock assertions, used to custom compare """
+ """An adapter to assist mock assertions, used to custom compare."""
def __init__(self, cmp, obj):
self.cmp = cmp
class TestAttributes(base.BaseTestCase):
def _construct_dict_and_constraints(self):
- """ Constructs a test dictionary and a definition of constraints.
+ """Constructs a test dictionary and a definition of constraints.
:return: A (dictionary, constraint) tuple
"""
constraints = {'key1': {'type:values': ['val1', 'val2'],
return data
def _create_bulk_from_list(self, fmt, resource, objects, **kwargs):
- """ Creates a bulk request from a list of objects """
+ """Creates a bulk request from a list of objects."""
collection = "%ss" % resource
req_data = {collection: objects}
req = self.new_create_request(collection, req_data, fmt)
return req.get_response(self.api)
def _create_bulk(self, fmt, number, resource, data, name='test', **kwargs):
- """ Creates a bulk request for any kind of resource """
+ """Creates a bulk request for any kind of resource."""
objects = []
collection = "%ss" % resource
for i in range(0, number):
return self.deserialize(fmt, res)
def _do_side_effect(self, patched_plugin, orig, *args, **kwargs):
- """ Invoked by test cases for injecting failures in plugin """
+ """Invoked by test cases for injecting failures in plugin."""
def second_call(*args, **kwargs):
raise q_exc.QuantumException
patched_plugin.side_effect = second_call
self._check_list_with_fields(res, 'name')
def test_list_with_fields_noadmin_and_policy_field(self):
- """ If a field used by policy is selected, do not duplicate it.
+ """If a field used by policy is selected, do not duplicate it.
Verifies that if the field parameter explicitly specifies a field
which is used by the policy engine, then it is not duplicated
cfg.CONF.set_override('base_mac', "bad_mac")
try:
self.plugin._check_base_mac_format()
- except:
+ except Exception:
return
self.fail("No exception for illegal base_mac format")
class DbModelTestCase(base.BaseTestCase):
- """ DB model tests """
+ """DB model tests."""
def test_repr(self):
- """ testing the string representation of 'model' classes """
+ """testing the string representation of 'model' classes."""
network = models_v2.Network(name="net_net", status="OK",
admin_state_up=True)
actual_repr_output = repr(network)
from quantum.db import db_base_plugin_v2
from quantum.db import portsecurity_db
from quantum.db import securitygroups_db
-from quantum.extensions import securitygroup as ext_sg
from quantum.extensions import portsecurity as psec
+from quantum.extensions import securitygroup as ext_sg
from quantum.manager import QuantumManager
from quantum import policy
from quantum.tests.unit import test_db_plugin
securitygroups_db.SecurityGroupDbMixin,
portsecurity_db.PortSecurityDbMixin):
- """ Test plugin that implements necessary calls on create/delete port for
+ """Test plugin that implements necessary calls on create/delete port for
associating ports with security groups and port security.
"""
security_group_rule['security_group_rule']['id'])
def _delete_default_security_group_egress_rules(self, security_group_id):
- """Deletes default egress rules given a security group ID"""
+ """Deletes default egress rules given a security group ID."""
res = self._list(
'security-group-rules',
query_params='security_group_id=%s' % security_group_id)
class SecurityGroupTestPlugin(db_base_plugin_v2.QuantumDbPluginV2,
securitygroups_db.SecurityGroupDbMixin):
- """ Test plugin that implements necessary calls on create/delete port for
+ """Test plugin that implements necessary calls on create/delete port for
associating ports with security groups.
"""
from quantum.agent.common import config as a_cfg
from quantum.agent.linux.iptables_firewall import IptablesFirewallDriver
-from quantum.tests.unit import test_api_v2
from quantum.tests import base
+from quantum.tests.unit import test_api_v2
+
_uuid = test_api_v2._uuid
FAKE_PREFIX = {'IPv4': '10.0.0.0/24',
try:
with self.firewall.defer_apply():
raise Exception("same exception")
- except:
+ except Exception:
pass
self.iptables_inst.assert_has_calls([call.defer_apply_on(),
call.defer_apply_off()])
class L3NatTestCaseMixin(object):
def _create_network(self, fmt, name, admin_state_up, **kwargs):
- """ Override the routine for allowing the router:external attribute """
+ """Override the routine for allowing the router:external attribute."""
# attributes containing a colon should be passed with
# a double underscore
new_args = dict(itertools.izip(map(lambda x: x.replace('__', ':'),
kargs = [item for item in args]
kargs.append(notifyApi)
target_func(*kargs)
- except:
+ except Exception:
l3_rpc_agent_api.L3AgentNotify = oldNotify
raise
else:
self.assertEqual(res['vip'], return_value)
def _test_entity_delete(self, entity):
- """ does the entity deletion based on naming convention """
+ """Does the entity deletion based on naming convention."""
entity_id = _uuid()
res = self.api.delete(_get_path('lb/' + entity + 's', id=entity_id,
fmt=self.fmt))
import webob
from quantum.agent.metadata import agent
-from quantum.tests import base
from quantum.common import utils
+from quantum.tests import base
class FakeConf(object):
import webob
from quantum.agent.metadata import namespace_proxy as ns_proxy
-from quantum.tests import base
from quantum.common import utils
+from quantum.tests import base
class FakeConf(object):
self.assertTrue(f.match(usercmd) or f2.match(usercmd))
def test_KillFilter_no_raise(self):
- """Makes sure ValueError from bug 926412 is gone"""
+ """Makes sure ValueError from bug 926412 is gone."""
f = filters.KillFilter("root", "")
# Providing anything other than kill should be False
usercmd = ['notkill', 999999]
self.assertFalse(f.match(usercmd))
def test_KillFilter_deleted_exe(self):
- """Makes sure deleted exe's are killed correctly"""
+ """Makes sure deleted exe's are killed correctly."""
# See bug #1073768.
with mock.patch('os.readlink') as mock_readlink:
mock_readlink.return_value = '/bin/commandddddd (deleted)'
class TestServiceTypeExtensionManager(object):
- """ Mock extensions manager """
+ """Mock extensions manager."""
def get_resources(self):
return (servicetype.Servicetype.get_resources() +
import urllib2
import mock
-import testtools
from oslo.config import cfg
+import testtools
import webob
import webob.exc
socket.SOCK_STREAM)[0]
family = info[0]
bind_addr = info[-1]
- except:
+ except Exception:
LOG.exception(_("Unable to listen on %(host)s:%(port)s") %
{'host': host, 'port': port})
sys.exit(1)
class DictSerializer(ActionDispatcher):
- """Default request body serialization"""
+ """Default request body serialization."""
def serialize(self, data, action='default'):
return self.dispatch(data, action=action)
class JSONDictSerializer(DictSerializer):
- """Default JSON request body serialization"""
+ """Default JSON request body serialization."""
def default(self, data):
def sanitizer(obj):
class ResponseHeaderSerializer(ActionDispatcher):
- """Default response headers serialization"""
+ """Default response headers serialization."""
def serialize(self, response, data, action):
self.dispatch(response, data, action=action)
class ResponseSerializer(object):
- """Encode the necessary pieces into a response object"""
+ """Encode the necessary pieces into a response object."""
def __init__(self, body_serializers=None, headers_serializer=None):
self.body_serializers = {
class TextDeserializer(ActionDispatcher):
- """Default request body deserialization"""
+ """Default request body deserialization."""
def deserialize(self, datastring, action='default'):
return self.dispatch(datastring, action=action)
class RequestHeadersDeserializer(ActionDispatcher):
- """Default request headers deserializer"""
+ """Default request headers deserializer."""
def deserialize(self, request, action):
return self.dispatch(request, action=action)
class Fault(webob.exc.HTTPException):
- """ Generates an HTTP response from a webob HTTP exception"""
+ """Generates an HTTP response from a webob HTTP exception."""
def __init__(self, exception, xmlns=None, body_function=None):
"""Creates a Fault for the given webob.exc.exception."""
import os
import sys
-from quantum.common.test_lib import run_tests
from nose import config
from nose import core
+from quantum.common.test_lib import run_tests
import quantum.tests.unit
def is_localized(node):
- """ Check message wrapped by _() """
+ """Check message wrapped by _()"""
if isinstance(node.parent, compiler.ast.CallFunc):
if isinstance(node.parent.node, compiler.ast.Name):
if node.parent.node.name == '_':
cfg_path = sys.argv[2]
try:
cfg_mod = imp.load_source('', cfg_path)
- except:
+ except Exception:
print >> sys.stderr, "Load cfg module failed"
sys.exit(1)
def is_log_callfunc(n):
- """ LOG.xxx('hello %s' % xyz) and LOG('hello') """
+ """LOG.xxx('hello %s' % xyz) and LOG('hello')"""
if isinstance(n.parent, compiler.ast.Mod):
n = n.parent
if isinstance(n.parent, compiler.ast.CallFunc):
def is_log_i18n_msg_with_mod(n):
- """ LOG.xxx("Hello %s" % xyz) should be LOG.xxx("Hello %s", xyz) """
+ """LOG.xxx("Hello %s" % xyz) should be LOG.xxx("Hello %s", xyz)"""
if not isinstance(n.parent.parent, compiler.ast.Mod):
return False
n = n.parent.parent
def is_wrong_i18n_format(n):
- """ Check _('hello %s' % xyz) """
+ """Check _('hello %s' % xyz)"""
if isinstance(n.parent, compiler.ast.Mod):
n = n.parent
if isinstance(n.parent, compiler.ast.CallFunc):
distribute>=0.6.24
fixtures>=0.3.12
flake8
+hacking
mock>=1.0b1
mox==0.5.3
nose
# E711/E712 comparison to False should be 'if cond is False:' or 'if not cond:'
# query = query.filter(Component.disabled == False)
# E125 continuation line does not distinguish itself from next logical line
-# H hacking.py - automatic checks of rules in HACKING.rst
-ignore = E711,E712,E125,H
+# H301 one import per line
+# H302 import only modules
+# TODO(marun) H404 multi line docstring should start with a summary
+# TODO(marun) H901,902 use the not operator inline for clarity
+# TODO(markmcclain) H202 assertRaises Exception too broad
+ignore = E711,E712,E125,H301,H302,H404,H901,H902,H202
show-source = true
builtins = _
exclude=.venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,tools