diff --git a/nova/api/ec2/__init__.py b/nova/api/ec2/__init__.py index 35dda8b093ca..1cc368ce50f4 100644 --- a/nova/api/ec2/__init__.py +++ b/nova/api/ec2/__init__.py @@ -468,8 +468,7 @@ def exception_to_ec2code(ex): def ec2_error_ex(ex, req, code=None, message=None, unexpected=False): - """ - Return an EC2 error response based on passed exception and log + """Return an EC2 error response based on passed exception and log the exception on an appropriate log level: * DEBUG: expected errors diff --git a/nova/api/openstack/__init__.py b/nova/api/openstack/__init__.py index 06eb4a0246ae..9a084846e3bb 100644 --- a/nova/api/openstack/__init__.py +++ b/nova/api/openstack/__init__.py @@ -172,8 +172,7 @@ class PlainMapper(APIMapper): class APIRouter(base_wsgi.Router): - """ - Routes requests on the OpenStack API to the appropriate controller + """Routes requests on the OpenStack API to the appropriate controller and method. """ ExtensionManager = None # override in subclasses @@ -252,8 +251,7 @@ class APIRouter(base_wsgi.Router): class APIRouterV3(base_wsgi.Router): - """ - Routes requests on the OpenStack v3 API to the appropriate controller + """Routes requests on the OpenStack v3 API to the appropriate controller and method. """ diff --git a/nova/api/openstack/common.py b/nova/api/openstack/common.py index 7fe58c72f6ad..d4b8b8b5eb0f 100644 --- a/nova/api/openstack/common.py +++ b/nova/api/openstack/common.py @@ -476,8 +476,7 @@ class ViewBuilder(object): """Model API responses as dictionaries.""" def _get_project_id(self, request): - """ - Get project id from request url if present or empty string + """Get project id from request url if present or empty string otherwise """ project_id = request.environ["nova.context"].project_id diff --git a/nova/api/openstack/compute/__init__.py b/nova/api/openstack/compute/__init__.py index 128dbd0597de..bca184cedb86 100644 --- a/nova/api/openstack/compute/__init__.py +++ b/nova/api/openstack/compute/__init__.py @@ -42,8 +42,7 @@ CONF.register_opt(allow_instance_snapshots_opt) class APIRouter(nova.api.openstack.APIRouter): - """ - Routes requests on the OpenStack API to the appropriate controller + """Routes requests on the OpenStack API to the appropriate controller and method. """ ExtensionManager = extensions.ExtensionManager @@ -130,8 +129,7 @@ class APIRouter(nova.api.openstack.APIRouter): class APIRouterV3(nova.api.openstack.APIRouterV3): - """ - Routes requests on the OpenStack API to the appropriate controller + """Routes requests on the OpenStack API to the appropriate controller and method. """ def __init__(self, init_only=None): diff --git a/nova/api/openstack/compute/contrib/agents.py b/nova/api/openstack/compute/contrib/agents.py index e667830355dd..1c66185efeb2 100644 --- a/nova/api/openstack/compute/contrib/agents.py +++ b/nova/api/openstack/compute/contrib/agents.py @@ -42,8 +42,7 @@ class AgentsIndexTemplate(xmlutil.TemplateBuilder): class AgentController(object): - """ - The agent is talking about guest agent.The host can use this for + """The agent is talking about guest agent.The host can use this for things like accessing files on the disk, configuring networking, or running other applications/scripts in the guest while it is running. Typically this uses some hypervisor-specific transport @@ -66,9 +65,7 @@ class AgentController(object): """ @wsgi.serializers(xml=AgentsIndexTemplate) def index(self, req): - """ - Return a list of all agent builds. Filter by hypervisor. - """ + """Return a list of all agent builds. Filter by hypervisor.""" context = req.environ['nova.context'] authorize(context) hypervisor = None diff --git a/nova/api/openstack/compute/contrib/aggregates.py b/nova/api/openstack/compute/contrib/aggregates.py index c82be1521c63..a276b64246a6 100644 --- a/nova/api/openstack/compute/contrib/aggregates.py +++ b/nova/api/openstack/compute/contrib/aggregates.py @@ -59,8 +59,7 @@ class AggregateController(object): for a in aggregates]} def create(self, req, body): - """ - Creates an aggregate, given its name and + """Creates an aggregate, given its name and optional availability zone. """ context = _get_context(req) diff --git a/nova/api/openstack/compute/contrib/cells.py b/nova/api/openstack/compute/contrib/cells.py index e20ab1ea24cf..aae2b0101f0b 100644 --- a/nova/api/openstack/compute/contrib/cells.py +++ b/nova/api/openstack/compute/contrib/cells.py @@ -133,8 +133,7 @@ class CellDeserializer(wsgi.XMLDeserializer): def _filter_keys(item, keys): - """ - Filters all model attributes except for keys + """Filters all model attributes except for keys item is a dict """ @@ -142,8 +141,7 @@ def _filter_keys(item, keys): def _fixup_cell_info(cell_info, keys): - """ - If the transport_url is present in the cell, derive username, + """If the transport_url is present in the cell, derive username, rpc_host, and rpc_port from it. """ @@ -294,8 +292,7 @@ class Controller(object): raise exc.HTTPBadRequest(explanation=msg) def _normalize_cell(self, cell, existing=None): - """ - Normalize input cell data. Normalizations include: + """Normalize input cell data. Normalizations include: * Converting cell['type'] to is_parent boolean. * Merging existing transport URL with transport information. diff --git a/nova/api/openstack/compute/contrib/evacuate.py b/nova/api/openstack/compute/contrib/evacuate.py index 0dd2c445c4da..6f38152baff3 100644 --- a/nova/api/openstack/compute/contrib/evacuate.py +++ b/nova/api/openstack/compute/contrib/evacuate.py @@ -37,8 +37,7 @@ class Controller(wsgi.Controller): @wsgi.action('evacuate') def _evacuate(self, req, id, body): - """ - Permit admins to evacuate a server from a failed host + """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] diff --git a/nova/api/openstack/compute/contrib/flavormanage.py b/nova/api/openstack/compute/contrib/flavormanage.py index f22003020710..b6eac7a61636 100644 --- a/nova/api/openstack/compute/contrib/flavormanage.py +++ b/nova/api/openstack/compute/contrib/flavormanage.py @@ -25,9 +25,7 @@ authorize = extensions.extension_authorizer('compute', 'flavormanage') class FlavorManageController(wsgi.Controller): - """ - The Flavor Lifecycle API controller for the OpenStack API. - """ + """The Flavor Lifecycle API controller for the OpenStack API.""" _view_builder_class = flavors_view.ViewBuilder def __init__(self): @@ -87,9 +85,7 @@ class FlavorManageController(wsgi.Controller): class Flavormanage(extensions.ExtensionDescriptor): - """ - Flavor create/delete API support - """ + """Flavor create/delete API support.""" name = "FlavorManage" alias = "os-flavor-manage" diff --git a/nova/api/openstack/compute/contrib/floating_ips_bulk.py b/nova/api/openstack/compute/contrib/floating_ips_bulk.py index ff654e2f8c4b..a93effbfba54 100644 --- a/nova/api/openstack/compute/contrib/floating_ips_bulk.py +++ b/nova/api/openstack/compute/contrib/floating_ips_bulk.py @@ -131,8 +131,7 @@ class FloatingIPBulkController(object): return {"floating_ips_bulk_delete": ip_range} def _address_to_hosts(self, addresses): - """ - Iterate over hosts within an address range. + """Iterate over hosts within an address range. If an explicit range specifier is missing, the parameter is interpreted as a specific individual address. diff --git a/nova/api/openstack/compute/contrib/hosts.py b/nova/api/openstack/compute/contrib/hosts.py index 2ceeb39da46d..cbcea9eb29b9 100644 --- a/nova/api/openstack/compute/contrib/hosts.py +++ b/nova/api/openstack/compute/contrib/hosts.py @@ -96,9 +96,7 @@ class HostController(object): @wsgi.serializers(xml=HostIndexTemplate) def index(self, req): - """ - :returns: A dict in the format: - + """Returns a dict in the format: {'hosts': [{'host_name': 'some.host.name', 'service': 'cells', 'zone': 'internal'}, @@ -151,19 +149,20 @@ class HostController(object): @wsgi.serializers(xml=HostUpdateTemplate) @wsgi.deserializers(xml=HostUpdateDeserializer) def update(self, req, id, body): - """ + """Updates a specified body. + :param body: example format {'status': 'enable', 'maintenance_mode': 'enable'} - :returns: """ def read_enabled(orig_val, msg): - """ + """Checks a specified orig_val and returns True for 'enabled' + and False for 'disabled'. + :param orig_val: A string with either 'enable' or 'disable'. May be surrounded by whitespace, and case doesn't matter :param msg: The message to be passed to HTTPBadRequest. A single %s will be replaced with orig_val. - :returns: True for 'enabled' and False for 'disabled' """ val = orig_val.strip().lower() if val == "enable": diff --git a/nova/api/openstack/compute/contrib/keypairs.py b/nova/api/openstack/compute/contrib/keypairs.py index 3955ffeb15c8..134d0b3b67f0 100644 --- a/nova/api/openstack/compute/contrib/keypairs.py +++ b/nova/api/openstack/compute/contrib/keypairs.py @@ -64,8 +64,7 @@ class KeypairController(object): @wsgi.serializers(xml=KeypairTemplate) def create(self, req, body): - """ - Create or import keypair. + """Create or import keypair. Sending name will generate a key and return private_key and fingerprint. @@ -112,9 +111,7 @@ class KeypairController(object): raise webob.exc.HTTPConflict(explanation=exc.format_message()) def delete(self, req, id): - """ - Delete a keypair with a given name - """ + """Delete a keypair with a given name.""" context = req.environ['nova.context'] authorize(context, action='delete') try: @@ -137,9 +134,7 @@ class KeypairController(object): @wsgi.serializers(xml=KeypairsTemplate) def index(self, req): - """ - List of keypairs for a user - """ + """List of keypairs for a user.""" context = req.environ['nova.context'] authorize(context, action='index') key_pairs = self.api.get_key_pairs(context, context.user_id) diff --git a/nova/api/openstack/compute/contrib/security_groups.py b/nova/api/openstack/compute/contrib/security_groups.py index 5f604a5bb5a0..496c4dc9625d 100644 --- a/nova/api/openstack/compute/contrib/security_groups.py +++ b/nova/api/openstack/compute/contrib/security_groups.py @@ -111,9 +111,7 @@ class SecurityGroupsTemplate(xmlutil.TemplateBuilder): class SecurityGroupXMLDeserializer(wsgi.MetadataXMLDeserializer): - """ - Deserializer to handle xml-formatted security group requests. - """ + """Deserializer to handle xml-formatted security group requests.""" def default(self, string): """Deserialize an xml-formatted security group create request.""" dom = xmlutil.safe_minidom_parse_string(string) @@ -131,9 +129,7 @@ class SecurityGroupXMLDeserializer(wsgi.MetadataXMLDeserializer): class SecurityGroupRulesXMLDeserializer(wsgi.MetadataXMLDeserializer): - """ - Deserializer to handle xml-formatted security group requests. - """ + """Deserializer to handle xml-formatted security group requests.""" def default(self, string): """Deserialize an xml-formatted security group create request.""" diff --git a/nova/api/openstack/compute/contrib/services.py b/nova/api/openstack/compute/contrib/services.py index 601255ec7b14..617de202883f 100644 --- a/nova/api/openstack/compute/contrib/services.py +++ b/nova/api/openstack/compute/contrib/services.py @@ -148,9 +148,7 @@ class ServiceController(object): @wsgi.serializers(xml=ServicesIndexTemplate) def index(self, req): - """ - Return a list of all running services. Filter by host & service name. - """ + """Return a list of all running services.""" detailed = self.ext_mgr.is_loaded('os-extended-services') services = self._get_services_list(req, detailed) diff --git a/nova/api/openstack/compute/images.py b/nova/api/openstack/compute/images.py index 1fbf88422703..13a3c0deba54 100644 --- a/nova/api/openstack/compute/images.py +++ b/nova/api/openstack/compute/images.py @@ -100,8 +100,7 @@ class Controller(wsgi.Controller): nova.image.glance.get_default_image_service()) def _get_filters(self, req): - """ - Return a dictionary of query param filters from the request + """Return a dictionary of query param filters from the request. :param req: the Request object coming from the wsgi layer :retval a dict of key/value filters diff --git a/nova/api/openstack/compute/limits.py b/nova/api/openstack/compute/limits.py index 1015ac4fbcaa..90194088ac90 100644 --- a/nova/api/openstack/compute/limits.py +++ b/nova/api/openstack/compute/limits.py @@ -128,15 +128,12 @@ def create_resource(): class Limit(object): - """ - Stores information about a limit for HTTP requests. - """ + """Stores information about a limit for HTTP requests.""" UNITS = dict([(v, k) for k, v in utils.TIME_UNITS.items()]) def __init__(self, verb, uri, regex, value, unit): - """ - Initialize a new `Limit`. + """Initialize a new `Limit`. @param verb: HTTP verb (POST, PUT, etc.) @param uri: Human-readable URI @@ -166,8 +163,7 @@ class Limit(object): self.error_message = msg % self.__dict__ def __call__(self, verb, url): - """ - Represents a call to this limit from a relevant request. + """Represents a call to this limit from a relevant request. @param verb: string http verb (POST, GET, etc.) @param url: string URL @@ -237,15 +233,14 @@ DEFAULT_LIMITS = [ class RateLimitingMiddleware(base_wsgi.Middleware): - """ - Rate-limits requests passing through this middleware. All limit information - is stored in memory for this implementation. + """Rate-limits requests passing through this middleware. All limit + information is stored in memory for this implementation. """ def __init__(self, application, limits=None, limiter=None, **kwargs): - """ - Initialize new `RateLimitingMiddleware`, which wraps the given WSGI - application and sets up the given limits. + """Initialize new `RateLimitingMiddleware`. + + It wraps the given WSGI application and sets up the given limits. @param application: WSGI application to wrap @param limits: String describing limits @@ -269,10 +264,10 @@ class RateLimitingMiddleware(base_wsgi.Middleware): @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): - """ - Represents a single call through this middleware. We should record the - request if we have a limit relevant to it. If no limit is relevant to - the request, ignore it. + """Represents a single call through this middleware. + + We should record the request if we have a limit relevant to it. + If no limit is relevant to the request, ignore it. If the request should be rate limited, return a fault telling the user they are over the limit and need to retry later. @@ -299,13 +294,10 @@ class RateLimitingMiddleware(base_wsgi.Middleware): class Limiter(object): - """ - Rate-limit checking class which handles limits in memory. - """ + """Rate-limit checking class which handles limits in memory.""" def __init__(self, limits, **kwargs): - """ - Initialize the new `Limiter`. + """Initialize the new `Limiter`. @param limits: List of `Limit` objects """ @@ -319,14 +311,11 @@ class Limiter(object): self.levels[username] = self.parse_limits(value) def get_limits(self, username=None): - """ - Return the limits for a given user. - """ + """Return the limits for a given user.""" return [limit.display() for limit in self.levels[username]] def check_for_delay(self, verb, url, username=None): - """ - Check the given verb/user/user triplet for limit. + """Check the given verb/user/user triplet for limit. @return: Tuple of delay (in seconds) and error message (or None, None) """ @@ -350,8 +339,7 @@ class Limiter(object): # default limit parsing. @staticmethod def parse_limits(limits): - """ - Convert a string into a list of Limit instances. This + """Convert a string into a list of Limit instances. This implementation expects a semicolon-separated sequence of parenthesized groups, where each group contains a comma-separated sequence consisting of HTTP method, @@ -405,8 +393,8 @@ class Limiter(object): class WsgiLimiter(object): - """ - Rate-limit checking from a WSGI application. Uses an in-memory `Limiter`. + """Rate-limit checking from a WSGI application. Uses an in-memory + `Limiter`. To use, POST ``/`` with JSON data such as:: @@ -421,8 +409,7 @@ class WsgiLimiter(object): """ def __init__(self, limits=None): - """ - Initialize the new `WsgiLimiter`. + """Initialize the new `WsgiLimiter`. @param limits: List of `Limit` objects """ @@ -430,10 +417,11 @@ class WsgiLimiter(object): @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, request): - """ - Handles a call to this application. Returns 204 if the request is - acceptable to the limiter, else a 403 is returned with a relevant - header indicating when the request *will* succeed. + """Handles a call to this application. + + Returns 204 if the request is acceptable to the limiter, else a 403 + is returned with a relevant header indicating when the request *will* + succeed. """ if request.method != "POST": raise webob.exc.HTTPMethodNotAllowed() @@ -457,13 +445,10 @@ class WsgiLimiter(object): class WsgiLimiterProxy(object): - """ - Rate-limit requests based on answers from a remote source. - """ + """Rate-limit requests based on answers from a remote source.""" def __init__(self, limiter_address): - """ - Initialize the new `WsgiLimiterProxy`. + """Initialize the new `WsgiLimiterProxy`. @param limiter_address: IP/port combination of where to request limit """ @@ -494,8 +479,7 @@ class WsgiLimiterProxy(object): # decisions are made by a remote server. @staticmethod def parse_limits(limits): - """ - Ignore a limits string--simply doesn't apply for the limit + """Ignore a limits string--simply doesn't apply for the limit proxy. @return: Empty list. diff --git a/nova/api/openstack/compute/plugins/v3/agents.py b/nova/api/openstack/compute/plugins/v3/agents.py index 4f8f426e7fdb..7aca52b9dbcf 100644 --- a/nova/api/openstack/compute/plugins/v3/agents.py +++ b/nova/api/openstack/compute/plugins/v3/agents.py @@ -28,8 +28,7 @@ authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) class AgentController(object): - """ - The agent is talking about guest agent.The host can use this for + """The agent is talking about guest agent.The host can use this for things like accessing files on the disk, configuring networking, or running other applications/scripts in the guest while it is running. Typically this uses some hypervisor-specific transport @@ -52,9 +51,7 @@ class AgentController(object): """ @extensions.expected_errors(()) def index(self, req): - """ - Return a list of all agent builds. Filter by hypervisor. - """ + """Return a list of all agent builds. Filter by hypervisor.""" context = req.environ['nova.context'] authorize(context) hypervisor = None diff --git a/nova/api/openstack/compute/plugins/v3/aggregates.py b/nova/api/openstack/compute/plugins/v3/aggregates.py index fd4b49adf476..1a9a18ad8831 100644 --- a/nova/api/openstack/compute/plugins/v3/aggregates.py +++ b/nova/api/openstack/compute/plugins/v3/aggregates.py @@ -73,8 +73,7 @@ class AggregateController(wsgi.Controller): @extensions.expected_errors((400, 409)) @wsgi.response(201) def create(self, req, body): - """ - Creates an aggregate, given its name and + """Creates an aggregate, given its name and optional availability zone. """ context = _get_context(req) diff --git a/nova/api/openstack/compute/plugins/v3/cells.py b/nova/api/openstack/compute/plugins/v3/cells.py index 90f79c2a1b49..d84e7506deb8 100644 --- a/nova/api/openstack/compute/plugins/v3/cells.py +++ b/nova/api/openstack/compute/plugins/v3/cells.py @@ -44,17 +44,14 @@ authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) def _filter_keys(item, keys): - """ - Filters all model attributes except for keys + """Filters all model attributes except for keys item is a dict - """ return dict((k, v) for k, v in item.iteritems() if k in keys) def _fixup_cell_info(cell_info, keys): - """ - If the transport_url is present in the cell, derive username, + """If the transport_url is present in the cell, derive username, rpc_host, and rpc_port from it. """ @@ -202,8 +199,7 @@ class CellsController(object): raise exc.HTTPBadRequest(explanation=msg) def _normalize_cell(self, cell, existing=None): - """ - Normalize input cell data. Normalizations include: + """Normalize input cell data. Normalizations include: * Converting cell['type'] to is_parent boolean. * Merging existing transport URL with transport information. diff --git a/nova/api/openstack/compute/plugins/v3/evacuate.py b/nova/api/openstack/compute/plugins/v3/evacuate.py index 8255681ba4f4..a925f2659ce0 100644 --- a/nova/api/openstack/compute/plugins/v3/evacuate.py +++ b/nova/api/openstack/compute/plugins/v3/evacuate.py @@ -42,8 +42,7 @@ class EvacuateController(wsgi.Controller): @wsgi.action('evacuate') @validation.schema(evacuate.evacuate) def _evacuate(self, req, id, body): - """ - Permit admins to evacuate a server from a failed host + """Permit admins to evacuate a server from a failed host to a new one. """ context = req.environ["nova.context"] diff --git a/nova/api/openstack/compute/plugins/v3/flavor_manage.py b/nova/api/openstack/compute/plugins/v3/flavor_manage.py index 9dc91d815416..8c95301066e9 100644 --- a/nova/api/openstack/compute/plugins/v3/flavor_manage.py +++ b/nova/api/openstack/compute/plugins/v3/flavor_manage.py @@ -24,9 +24,7 @@ authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) class FlavorManageController(wsgi.Controller): - """ - The Flavor Lifecycle API controller for the OpenStack API. - """ + """The Flavor Lifecycle API controller for the OpenStack API.""" _view_builder_class = flavors_view.V3ViewBuilder def __init__(self): @@ -90,9 +88,7 @@ class FlavorManageController(wsgi.Controller): class FlavorManage(extensions.V3APIExtensionBase): - """ - Flavor create/delete API support - """ + """Flavor create/delete API support.""" name = "FlavorManage" alias = ALIAS diff --git a/nova/api/openstack/compute/plugins/v3/hosts.py b/nova/api/openstack/compute/plugins/v3/hosts.py index e638e4ab1327..5087b0171e73 100644 --- a/nova/api/openstack/compute/plugins/v3/hosts.py +++ b/nova/api/openstack/compute/plugins/v3/hosts.py @@ -37,8 +37,7 @@ class HostController(wsgi.Controller): @extensions.expected_errors(()) def index(self, req): - """ - :returns: A dict in the format: + """:returns: A dict in the format: {'hosts': [{'host_name': 'some.host.name', 'service': 'cells', @@ -94,19 +93,17 @@ class HostController(wsgi.Controller): @extensions.expected_errors((400, 404, 501)) def update(self, req, id, body): - """ - :param body: example format {'host': {'status': 'enable', + """:param body: example format {'host': {'status': 'enable', 'maintenance_mode': 'enable'}} - :returns: + :returns: """ def read_enabled(orig_val, msg): - """ - :param orig_val: A string with either 'enable' or 'disable'. May - be surrounded by whitespace, and case doesn't - matter - :param msg: The message to be passed to HTTPBadRequest. A single - %s will be replaced with orig_val. - :returns: True for 'enabled' and False for 'disabled' + """:param orig_val: A string with either 'enable' or 'disable'. May + be surrounded by whitespace, and case doesn't + matter + :param msg: The message to be passed to HTTPBadRequest. A single + %s will be replaced with orig_val. + :returns: True for 'enabled' and False for 'disabled' """ val = orig_val.strip().lower() if val == "enable": diff --git a/nova/api/openstack/compute/plugins/v3/keypairs.py b/nova/api/openstack/compute/plugins/v3/keypairs.py index e8cdf40e61fc..414f4d18060d 100644 --- a/nova/api/openstack/compute/plugins/v3/keypairs.py +++ b/nova/api/openstack/compute/plugins/v3/keypairs.py @@ -52,8 +52,7 @@ class KeypairController(object): @wsgi.response(201) @validation.schema(keypairs.create) def create(self, req, body): - """ - Create or import keypair. + """Create or import keypair. Sending name will generate a key and return private_key and fingerprint. @@ -98,9 +97,7 @@ class KeypairController(object): @wsgi.response(204) @extensions.expected_errors(404) def delete(self, req, id): - """ - Delete a keypair with a given name - """ + """Delete a keypair with a given name.""" context = req.environ['nova.context'] authorize(context, action='delete') try: @@ -122,9 +119,7 @@ class KeypairController(object): @extensions.expected_errors(()) def index(self, req): - """ - List of keypairs for a user - """ + """List of keypairs for a user.""" context = req.environ['nova.context'] authorize(context, action='index') key_pairs = self.api.get_key_pairs(context, context.user_id) diff --git a/nova/api/openstack/compute/plugins/v3/server_password.py b/nova/api/openstack/compute/plugins/v3/server_password.py index b65d9aeceb91..aac9b830b432 100644 --- a/nova/api/openstack/compute/plugins/v3/server_password.py +++ b/nova/api/openstack/compute/plugins/v3/server_password.py @@ -44,8 +44,7 @@ class ServerPasswordController(object): @extensions.expected_errors(404) @wsgi.response(204) def clear(self, req, server_id): - """ - Removes the encrypted server password from the metadata server + """Removes the encrypted server password from the metadata server Note that this does not actually change the instance server password. diff --git a/nova/api/openstack/compute/plugins/v3/services.py b/nova/api/openstack/compute/plugins/v3/services.py index 0b40f4fd6d54..6e89bfeb5423 100644 --- a/nova/api/openstack/compute/plugins/v3/services.py +++ b/nova/api/openstack/compute/plugins/v3/services.py @@ -101,8 +101,8 @@ class ServiceController(wsgi.Controller): @extensions.expected_errors(()) def index(self, req): - """ - Return a list of all running services. Filter by host & service name. + """Return a list of all running services. Filter by host & service + name """ services = self._get_services_list(req) diff --git a/nova/api/openstack/compute/servers.py b/nova/api/openstack/compute/servers.py index 64be71d96fe9..ccab3665903a 100644 --- a/nova/api/openstack/compute/servers.py +++ b/nova/api/openstack/compute/servers.py @@ -1218,8 +1218,7 @@ class Controller(wsgi.Controller): return image_uuid def _image_from_req_data(self, data): - """ - Get image data from the request or raise appropriate + """Get image data from the request or raise appropriate exceptions If no image is supplied - checks to see if there is diff --git a/nova/api/openstack/compute/views/versions.py b/nova/api/openstack/compute/views/versions.py index 315acb6f7f5f..242d93f1ad23 100644 --- a/nova/api/openstack/compute/views/versions.py +++ b/nova/api/openstack/compute/views/versions.py @@ -27,9 +27,7 @@ def get_view_builder(req): class ViewBuilder(common.ViewBuilder): def __init__(self, base_url): - """ - :param base_url: url of the root wsgi application - """ + """:param base_url: url of the root wsgi application.""" self.base_url = base_url def build_choices(self, VERSIONS, req): diff --git a/nova/api/openstack/wsgi.py b/nova/api/openstack/wsgi.py index d172ba21c053..c65922f7ad40 100644 --- a/nova/api/openstack/wsgi.py +++ b/nova/api/openstack/wsgi.py @@ -86,8 +86,7 @@ class Request(webob.Request): self._extension_data = {'db_items': {}} def cache_db_items(self, key, items, item_key='id'): - """ - Allow API methods to store objects from a DB query to be + """Allow API methods to store objects from a DB query to be used by API extensions within the same API request. An instance of this class only lives for the lifetime of a @@ -99,8 +98,7 @@ class Request(webob.Request): db_items[item[item_key]] = item def get_db_items(self, key): - """ - Allow an API extension to get previously stored objects within + """Allow an API extension to get previously stored objects within the same API request. Note that the object data will be slightly stale. @@ -108,8 +106,7 @@ class Request(webob.Request): return self._extension_data['db_items'][key] def get_db_item(self, key, item_key): - """ - Allow an API extension to get a previously stored object + """Allow an API extension to get a previously stored object within the same API request. Note that the object data will be slightly stale. @@ -246,9 +243,8 @@ class JSONDeserializer(TextDeserializer): class XMLDeserializer(TextDeserializer): def __init__(self, metadata=None): - """ - :param metadata: information needed to deserialize xml into - a dictionary. + """:param metadata: information needed to deserialize xml into + a dictionary. """ super(XMLDeserializer, self).__init__() self.metadata = metadata or {} @@ -365,10 +361,9 @@ class JSONDictSerializer(DictSerializer): class XMLDictSerializer(DictSerializer): def __init__(self, metadata=None, xmlns=None): - """ - :param metadata: information needed to deserialize xml into - a dictionary. - :param xmlns: XML namespace to include with serialized xml + """:param metadata: information needed to deserialize xml into + a dictionary. + :param xmlns: XML namespace to include with serialized xml """ super(XMLDictSerializer, self).__init__() self.metadata = metadata or {} @@ -735,14 +730,15 @@ class Resource(wsgi.Application): def __init__(self, controller, action_peek=None, inherits=None, **deserializers): - """ - :param controller: object that implement methods created by routes lib - :param action_peek: dictionary of routines for peeking into an action - request body to determine the desired action - :param inherits: another resource object that this resource should - inherit extensions from. Any action extensions that - are applied to the parent resource will also apply - to this resource. + """:param controller: object that implement methods created by routes + lib + :param action_peek: dictionary of routines for peeking into an + action request body to determine the + desired action + :param inherits: another resource object that this resource should + inherit extensions from. Any action extensions that + are applied to the parent resource will also apply + to this resource. """ self.controller = controller @@ -1255,14 +1251,10 @@ class Fault(webob.exc.HTTPException): class RateLimitFault(webob.exc.HTTPException): - """ - Rate-limited request response. - """ + """Rate-limited request response.""" def __init__(self, message, details, retry_time): - """ - Initialize new `RateLimitFault` with relevant information. - """ + """Initialize new `RateLimitFault` with relevant information.""" hdrs = RateLimitFault._retry_after(retry_time) self.wrapped_exc = webob.exc.HTTPTooManyRequests(headers=hdrs) self.content = { @@ -1283,9 +1275,8 @@ class RateLimitFault(webob.exc.HTTPException): @webob.dec.wsgify(RequestClass=Request) def __call__(self, request): - """ - Return the wrapped exception with a serialized body conforming to our - error format. + """Return the wrapped exception with a serialized body conforming + to our error format. """ user_locale = request.best_match_language() content_type = request.best_match_content_type() diff --git a/nova/api/openstack/xmlutil.py b/nova/api/openstack/xmlutil.py index 7bc5714a3b2c..0a692ff5a929 100644 --- a/nova/api/openstack/xmlutil.py +++ b/nova/api/openstack/xmlutil.py @@ -888,9 +888,7 @@ class TemplateBuilder(object): def make_links(parent, selector=None): - """ - Attach an Atom element to the parent. - """ + """Attach an Atom element to the parent.""" elem = SubTemplateElement(parent, '{%s}link' % XMLNS_ATOM, selector=selector) @@ -905,8 +903,7 @@ def make_links(parent, selector=None): def make_flat_dict(name, selector=None, subselector=None, ns=None, colon_ns=False, root=None, ignore_sub_dicts=False): - """ - Utility for simple XML templates that traditionally used + """Utility for simple XML templates that traditionally used XMLDictSerializer with no metadata. Returns a template element where the top-level element has the given tag name, and where sub-elements have tag names derived from the object's keys and diff --git a/nova/api/sizelimit.py b/nova/api/sizelimit.py index 627d5cb63314..0248cbacb04f 100644 --- a/nova/api/sizelimit.py +++ b/nova/api/sizelimit.py @@ -37,9 +37,10 @@ CONF.register_opt(max_request_body_size_opt) class LimitingReader(object): """Reader to limit the size of an incoming request.""" def __init__(self, data, limit): - """ - :param data: Underlying data object - :param limit: maximum number of bytes the reader should allow + """Initialize a new `LimitingReader`. + + :param data: underlying data object + :param limit: maximum number of bytes the reader should allow """ self.data = data self.limit = limit diff --git a/nova/api/validation/__init__.py b/nova/api/validation/__init__.py index 2e8f8777a624..332317777cc7 100644 --- a/nova/api/validation/__init__.py +++ b/nova/api/validation/__init__.py @@ -22,8 +22,7 @@ from validators import _SchemaValidator def schema(request_body_schema): - """ - Register a schema to validate request body. + """Register a schema to validate request body. Registered schema will be used for validating request body just before API method executing. diff --git a/nova/cells/manager.py b/nova/cells/manager.py index b35be14c6647..5e9aee5bf272 100644 --- a/nova/cells/manager.py +++ b/nova/cells/manager.py @@ -274,8 +274,7 @@ class CellsManager(manager.Manager): return service def get_host_uptime(self, ctxt, host_name): - """ - Return host uptime for a compute host in a certain cell + """Return host uptime for a compute host in a certain cell :param host_name: fully qualified hostname. It should be in format of parent!child@host_id @@ -286,8 +285,7 @@ class CellsManager(manager.Manager): return response.value_or_raise() def service_update(self, ctxt, host_name, binary, params_to_update): - """ - Used to enable/disable a service. For compute services, setting to + """Used to enable/disable a service. For compute services, setting to disabled stops new builds arriving on that host. :param host_name: the name of the host machine that the service is diff --git a/nova/cells/messaging.py b/nova/cells/messaging.py index 6ab60251982a..69d1ff97a585 100644 --- a/nova/cells/messaging.py +++ b/nova/cells/messaging.py @@ -732,8 +732,7 @@ class _TargetedMessageMethods(_BaseMessageMethods): return jsonutils.to_primitive(service) def service_update(self, message, host_name, binary, params_to_update): - """ - Used to enable/disable a service. For compute services, setting to + """Used to enable/disable a service. For compute services, setting to disabled stops new builds arriving on that host. :param host_name: the name of the host machine that the service is @@ -1509,8 +1508,7 @@ class MessageRunner(object): def service_update(self, ctxt, cell_name, host_name, binary, params_to_update): - """ - Used to enable/disable a service. For compute services, setting to + """Used to enable/disable a service. For compute services, setting to disabled stops new builds arriving on that host. :param host_name: the name of the host machine that the service is diff --git a/nova/cells/rpcapi.py b/nova/cells/rpcapi.py index cfa3f3a98a86..adafd0cd39c6 100644 --- a/nova/cells/rpcapi.py +++ b/nova/cells/rpcapi.py @@ -244,8 +244,7 @@ class CellsAPI(object): return cctxt.call(context, 'get_host_uptime', host_name=host_name) def service_update(self, ctxt, host_name, binary, params_to_update): - """ - Used to enable/disable a service. For compute services, setting to + """Used to enable/disable a service. For compute services, setting to disabled stops new builds arriving on that host. :param host_name: the name of the host machine that the service is diff --git a/nova/cells/state.py b/nova/cells/state.py index e6dbc5822180..b9112bd6b8d8 100644 --- a/nova/cells/state.py +++ b/nova/cells/state.py @@ -421,8 +421,7 @@ class CellStateManager(base.Base): class CellStateManagerDB(CellStateManager): @utils.synchronized('cell-db-sync') def _cell_data_sync(self, force=False): - """ - Update cell status for all cells from the backing data store + """Update cell status for all cells from the backing data store when necessary. :param force: If True, cell status will be updated regardless @@ -456,8 +455,7 @@ class CellStateManagerFile(CellStateManager): super(CellStateManagerFile, self).__init__(cell_state_cls) def _cell_data_sync(self, force=False): - """ - Update cell status for all cells from the backing data store + """Update cell status for all cells from the backing data store when necessary. :param force: If True, cell status will be updated regardless diff --git a/nova/cells/weights/ram_by_instance_type.py b/nova/cells/weights/ram_by_instance_type.py index aa7fe768a720..1185f39571af 100644 --- a/nova/cells/weights/ram_by_instance_type.py +++ b/nova/cells/weights/ram_by_instance_type.py @@ -38,8 +38,7 @@ class RamByInstanceTypeWeigher(weights.BaseCellWeigher): return CONF.cells.ram_weight_multiplier def _weigh_object(self, cell, weight_properties): - """ - Use the 'ram_free' for a particular instance_type advertised from a + """Use the 'ram_free' for a particular instance_type advertised from a child cell's capacity to compute a weight. We want to direct the build to a cell with a higher capacity. Since higher weights win, we just return the number of units available for the instance_type. diff --git a/nova/cells/weights/weight_offset.py b/nova/cells/weights/weight_offset.py index b2d9f31e4100..e8797b0a5333 100644 --- a/nova/cells/weights/weight_offset.py +++ b/nova/cells/weights/weight_offset.py @@ -33,8 +33,7 @@ CONF.register_opts(weigher_opts, group='cells') class WeightOffsetWeigher(weights.BaseCellWeigher): - """ - Weight cell by weight_offset db field. + """Weight cell by weight_offset db field. Originally designed so you can set a default cell by putting its weight_offset to 999999999999999 (highest weight wins) """ diff --git a/nova/cmd/manage.py b/nova/cmd/manage.py index dc1fa9588d3c..ab0cc4757a38 100644 --- a/nova/cmd/manage.py +++ b/nova/cmd/manage.py @@ -223,8 +223,7 @@ class ProjectCommands(object): @args('--key', metavar='', help='Key') @args('--value', metavar='', help='Value') def quota(self, project_id, user_id=None, key=None, value=None): - """ - Create, update or display quotas for project/user + """Create, update or display quotas for project/user If no quota key is provided, the quota will be displayed. If a valid quota key is provided and it does not exist, @@ -401,8 +400,7 @@ class FloatingIpCommands(object): @staticmethod def address_to_hosts(addresses): - """ - Iterate over hosts within an address range. + """Iterate over hosts within an address range. If an explicit range specifier is missing, the parameter is interpreted as a specific individual address. @@ -679,8 +677,8 @@ class ServiceCommands(object): @args('--host', metavar='', help='Host') @args('--service', metavar='', help='Nova service') def list(self, host=None, service=None): - """ - Show a list of all running services. Filter by host & service name. + """Show a list of all running services. Filter by host & service + name """ servicegroup_api = servicegroup.API() ctxt = context.get_admin_context() diff --git a/nova/compute/__init__.py b/nova/compute/__init__.py index 0da62ccbabbc..17217fc74500 100644 --- a/nova/compute/__init__.py +++ b/nova/compute/__init__.py @@ -40,9 +40,8 @@ def API(*args, **kwargs): def HostAPI(*args, **kwargs): - """ - Returns the 'HostAPI' class from the same module as the configured compute - api + """Returns the 'HostAPI' class from the same module as the configured + compute api """ importutils = nova.openstack.common.importutils compute_api_class_name = _get_compute_api_class_name() @@ -52,8 +51,7 @@ def HostAPI(*args, **kwargs): def InstanceActionAPI(*args, **kwargs): - """ - Returns the 'InstanceActionAPI' class from the same module as the + """Returns the 'InstanceActionAPI' class from the same module as the configured compute api. """ importutils = nova.openstack.common.importutils diff --git a/nova/compute/api.py b/nova/compute/api.py index 22d01073db54..e425bb4bf743 100644 --- a/nova/compute/api.py +++ b/nova/compute/api.py @@ -219,8 +219,7 @@ def check_instance_cell(fn): def _diff_dict(orig, new): - """ - Return a dict describing how to change orig to new. The keys + """Return a dict describing how to change orig to new. The keys correspond to values that have changed; the value will be a list of one or two elements. The first element of the list will be either '+' or '-', indicating whether the key was updated or @@ -441,8 +440,7 @@ class API(base.Base): raise exception.InvalidMetadataSize(reason=msg) def _check_requested_secgroups(self, context, secgroups): - """ - Check if the security group requested exists and belongs to + """Check if the security group requested exists and belongs to the project. """ for secgroup in secgroups: @@ -455,8 +453,7 @@ class API(base.Base): def _check_requested_networks(self, context, requested_networks, max_count): - """ - Check if the networks requested belongs to the project + """Check if the networks requested belongs to the project and the fixed IP address for each network provided is within same the network block """ @@ -1267,8 +1264,7 @@ class API(base.Base): block_device_mapping=None, access_ip_v4=None, access_ip_v6=None, requested_networks=None, config_drive=None, auto_disk_config=None, scheduler_hints=None, legacy_bdm=True): - """ - Provision instances, sending instance information to the + """Provision instances, sending instance information to the scheduler. The scheduler will determine where the instance(s) go and will handle creating the DB entries. @@ -2110,8 +2106,7 @@ class API(base.Base): context, None, None, image) def _reset_image_metadata(): - """ - Remove old image properties that we're storing as instance + """Remove old image properties that we're storing as instance system metadata. These properties start with 'image_'. Then add the properties for the new image. """ @@ -2234,8 +2229,7 @@ class API(base.Base): @staticmethod def _resize_quota_delta(context, new_flavor, old_flavor, sense, compare): - """ - Calculate any quota adjustment required at a particular point + """Calculate any quota adjustment required at a particular point in the resize cycle. :param context: the request context @@ -2261,15 +2255,13 @@ class API(base.Base): @staticmethod def _upsize_quota_delta(context, new_flavor, old_flavor): - """ - Calculate deltas required to adjust quota for an instance upsize. + """Calculate deltas required to adjust quota for an instance upsize. """ return API._resize_quota_delta(context, new_flavor, old_flavor, 1, 1) @staticmethod def _reverse_upsize_quota_delta(context, migration_ref): - """ - Calculate deltas required to reverse a prior upsizing + """Calculate deltas required to reverse a prior upsizing quota adjustment. """ old_flavor = flavor_obj.Flavor.get_by_id( @@ -2281,8 +2273,7 @@ class API(base.Base): @staticmethod def _downsize_quota_delta(context, instance): - """ - Calculate deltas required to adjust quota for an instance downsize. + """Calculate deltas required to adjust quota for an instance downsize. """ old_flavor = instance.get_flavor('old') new_flavor = instance.get_flavor('new') @@ -3478,8 +3469,7 @@ class KeypairAPI(base.Base): class SecurityGroupAPI(base.Base, security_group_base.SecurityGroupBase): - """ - Sub-set of the Compute API related to managing security groups + """Sub-set of the Compute API related to managing security groups and security group rules """ @@ -3491,8 +3481,7 @@ class SecurityGroupAPI(base.Base, security_group_base.SecurityGroupBase): self.security_group_rpcapi = compute_rpcapi.SecurityGroupAPI() def validate_property(self, value, property, allowed): - """ - Validate given security group property. + """Validate given security group property. :param value: the value to validate, as a string or unicode :param property: the property, either 'name' or 'description' diff --git a/nova/compute/cells_api.py b/nova/compute/cells_api.py index 1f6dc417dc08..bc71b2b81e3f 100644 --- a/nova/compute/cells_api.py +++ b/nova/compute/cells_api.py @@ -536,8 +536,7 @@ class HostAPI(compute_api.HostAPI): db_service) def service_update(self, context, host_name, binary, params_to_update): - """ - Used to enable/disable a service. For compute services, setting to + """Used to enable/disable a service. For compute services, setting to disabled stops new builds arriving on that host. :param host_name: the name of the host machine that the service is diff --git a/nova/compute/manager.py b/nova/compute/manager.py index 145b6b335b19..783972a2e327 100644 --- a/nova/compute/manager.py +++ b/nova/compute/manager.py @@ -588,8 +588,7 @@ class ComputeManager(manager.Manager): return shared_storage def _complete_partial_deletion(self, context, instance): - """ - Complete deletion for instances in DELETED status but not marked as + """Complete deletion for instances in DELETED status but not marked as deleted in the DB """ instance.destroy() @@ -2698,8 +2697,7 @@ class ComputeManager(manager.Manager): @reverts_task_state @wrap_instance_event def rescue_instance(self, context, instance, rescue_password): - """ - Rescue an instance on this host. + """Rescue an instance on this host. :param rescue_password: password to set on rescue instance """ context = context.elevated() diff --git a/nova/compute/utils.py b/nova/compute/utils.py index 48d7079833ef..43022e3b2c3b 100644 --- a/nova/compute/utils.py +++ b/nova/compute/utils.py @@ -295,8 +295,7 @@ def notify_usage_exists(notifier, context, instance_ref, current_period=False, def notify_about_instance_usage(notifier, context, instance, event_suffix, network_info=None, system_metadata=None, extra_usage_info=None): - """ - Send a notification about an instance. + """Send a notification about an instance. :param notifier: a messaging.Notifier :param event_suffix: Event type like "delete.start" or "exists" @@ -321,8 +320,7 @@ def notify_about_instance_usage(notifier, context, instance, event_suffix, def notify_about_aggregate_update(context, event_suffix, aggregate_payload): - """ - Send a notification about aggregate update. + """Send a notification about aggregate update. :param event_suffix: Event type like "create.start" or "create.end" :param aggregate_payload: payload for aggregate update @@ -342,8 +340,7 @@ def notify_about_aggregate_update(context, event_suffix, aggregate_payload): def notify_about_host_update(context, event_suffix, host_payload): - """ - Send a notification about host update. + """Send a notification about host update. :param event_suffix: Event type like "create.start" or "create.end" :param host_payload: payload for host update. It is a dict and there diff --git a/nova/console/websocketproxy.py b/nova/console/websocketproxy.py index d2bb555bec00..e5bfb9ef1630 100644 --- a/nova/console/websocketproxy.py +++ b/nova/console/websocketproxy.py @@ -38,9 +38,7 @@ class NovaWebSocketProxy(websockify.WebSocketProxy): ssl_target=None, *args, **kwargs) def new_client(self): - """ - Called after a new WebSocket connection has been established. - """ + """Called after a new WebSocket connection has been established.""" # Reopen the eventlet hub to make sure we don't share an epoll # fd with parent and/or siblings, which would be bad from eventlet import hubs diff --git a/nova/context.py b/nova/context.py index 4ace6d974c2b..adcdc8d287b2 100644 --- a/nova/context.py +++ b/nova/context.py @@ -49,16 +49,16 @@ class RequestContext(object): request_id=None, auth_token=None, overwrite=True, quota_class=None, user_name=None, project_name=None, service_catalog=None, instance_lock_checked=False, **kwargs): - """ - :param read_deleted: 'no' indicates deleted records are hidden, 'yes' - indicates deleted records are visible, 'only' indicates that - *only* deleted records are visible. + """:param read_deleted: 'no' indicates deleted records are hidden, + 'yes' indicates deleted records are visible, + 'only' indicates that *only* deleted records are visible. - :param overwrite: Set to False to ensure that the greenthread local - copy of the index is not overwritten. - :param kwargs: Extra arguments that might be present, but we ignore - because they possibly came in from older rpc messages. + :param overwrite: Set to False to ensure that the greenthread local + copy of the index is not overwritten. + + :param kwargs: Extra arguments that might be present, but we ignore + because they possibly came in from older rpc messages. """ if kwargs: LOG.warn(_('Arguments dropped when creating context: %s') % diff --git a/nova/db/api.py b/nova/db/api.py index 2c5709551eb9..68069cf7871a 100644 --- a/nova/db/api.py +++ b/nova/db/api.py @@ -442,8 +442,7 @@ def migration_get_by_instance_and_status(context, instance_uuid, status): def migration_get_unconfirmed_by_dest_compute(context, confirm_window, dest_compute, use_slave=False): - """ - Finds all unconfirmed migrations within the confirmation window for + """Finds all unconfirmed migrations within the confirmation window for a specific destination compute host. """ return IMPL.migration_get_unconfirmed_by_dest_compute(context, diff --git a/nova/db/sqlalchemy/api.py b/nova/db/sqlalchemy/api.py index 7c9f05203f8d..e03aaf02a20e 100644 --- a/nova/db/sqlalchemy/api.py +++ b/nova/db/sqlalchemy/api.py @@ -1271,8 +1271,7 @@ def _fixed_ip_get_by_address(context, address, session=None, @require_admin_context def fixed_ip_get_by_address_detailed(context, address): - """ - :returns: a tuple of (models.FixedIp, models.Network, models.Instance) + """:returns: a tuple of (models.FixedIp, models.Network, models.Instance) """ try: result = model_query(context, models.FixedIp, @@ -3439,8 +3438,7 @@ def _block_device_mapping_get_query(context, session=None, def _scrub_empty_str_values(dct, keys_to_scrub): - """ - Remove any keys found in sequence keys_to_scrub from the dict + """Remove any keys found in sequence keys_to_scrub from the dict if they have the value ''. """ for key in keys_to_scrub: @@ -3579,8 +3577,7 @@ def _security_group_get_query(context, session=None, read_deleted=None, def _security_group_get_by_names(context, session, project_id, group_names): - """ - Get security group models for a project by a list of names. + """Get security group models for a project by a list of names. Raise SecurityGroupNotFoundForProject for a name not found. """ query = _security_group_get_query(context, session=session, @@ -4241,8 +4238,7 @@ def _flavor_get_query(context, session=None, read_deleted=None): def flavor_get_all(context, inactive=False, filters=None, sort_key='flavorid', sort_dir='asc', limit=None, marker=None): - """ - Returns all flavors. + """Returns all flavors. """ filters = filters or {} diff --git a/nova/db/sqlalchemy/models.py b/nova/db/sqlalchemy/models.py index d97e95f37a07..4f9bdde23d7a 100644 --- a/nova/db/sqlalchemy/models.py +++ b/nova/db/sqlalchemy/models.py @@ -282,8 +282,7 @@ class Instance(BASE, NovaBase): class InstanceInfoCache(BASE, NovaBase): - """ - Represents a cache of information about an instance + """Represents a cache of information about an instance """ __tablename__ = 'instance_info_caches' __table_args__ = ( @@ -1349,8 +1348,7 @@ class InstanceGroup(BASE, NovaBase): class PciDevice(BASE, NovaBase): - """ - Represents a PCI host device that can be passed through to instances. + """Represents a PCI host device that can be passed through to instances. """ __tablename__ = 'pci_devices' __table_args__ = ( diff --git a/nova/db/sqlalchemy/utils.py b/nova/db/sqlalchemy/utils.py index 650e77f599b3..0b0f2c9f959e 100644 --- a/nova/db/sqlalchemy/utils.py +++ b/nova/db/sqlalchemy/utils.py @@ -183,10 +183,9 @@ def _drop_unique_constraint_in_sqlite(migrate_engine, table_name, uc_name, def drop_unique_constraint(migrate_engine, table_name, uc_name, *columns, **col_name_col_instance): - """ - This method drops UC from table and works for mysql, postgresql and sqlite. - In mysql and postgresql we are able to use "alter table" construction. In - sqlite is only one way to drop UC: + """This method drops UC from table and works for mysql, postgresql and + sqlite. In mysql and postgresql we are able to use "alter table" + construction. In sqlite is only one way to drop UC: 1) Create new table with same columns, indexes and constraints (except one that we want to drop). 2) Copy data from old table to new. @@ -215,8 +214,7 @@ def drop_unique_constraint(migrate_engine, table_name, uc_name, *columns, def drop_old_duplicate_entries_from_table(migrate_engine, table_name, use_soft_delete, *uc_column_names): - """ - This method is used to drop all old rows that have the same values for + """This method is used to drop all old rows that have the same values for columns in uc_columns. """ meta = MetaData() @@ -257,9 +255,8 @@ def drop_old_duplicate_entries_from_table(migrate_engine, table_name, def check_shadow_table(migrate_engine, table_name): - """ - This method checks that table with ``table_name`` and corresponding shadow - table have same columns. + """This method checks that table with ``table_name`` and + corresponding shadow table have same columns. """ meta = MetaData() meta.bind = migrate_engine @@ -296,9 +293,8 @@ def check_shadow_table(migrate_engine, table_name): def create_shadow_table(migrate_engine, table_name=None, table=None, **col_name_col_instance): - """ - This method create shadow table for table with name ``table_name`` or table - instance ``table``. + """This method create shadow table for table with name ``table_name`` + or table instance ``table``. :param table_name: Autoload table with this name and create shadow table :param table: Autoloaded table, so just create corresponding shadow table. :param col_name_col_instance: contains pair column_name=column_instance. diff --git a/nova/image/glance.py b/nova/image/glance.py index 986394c47684..0814aecaddb3 100644 --- a/nova/image/glance.py +++ b/nova/image/glance.py @@ -142,8 +142,7 @@ def _create_glance_client(context, host, port, use_ssl, version=1): def get_api_servers(): - """ - Shuffle a list of CONF.glance_api_servers and return an iterator + """Shuffle a list of CONF.glance_api_servers and return an iterator that will cycle through the list, looping around to the beginning if necessary. """ @@ -195,8 +194,7 @@ class GlanceClientWrapper(object): self.use_ssl, version) def call(self, context, version, method, *args, **kwargs): - """ - Call a glance client method. If we get a connection error, + """Call a glance client method. If we get a connection error, retry the request according to CONF.glance_num_retries. """ retry_excs = (glanceclient.exc.ServiceUnavailable, diff --git a/nova/keymgr/conf_key_mgr.py b/nova/keymgr/conf_key_mgr.py index fa7680876870..4b9cb6720850 100644 --- a/nova/keymgr/conf_key_mgr.py +++ b/nova/keymgr/conf_key_mgr.py @@ -46,11 +46,11 @@ CONF.register_opts(key_mgr_opts, group='keymgr') class ConfKeyManager(single_key_mgr.SingleKeyManager): - """ - This key manager implementation supports all the methods specified by the - key manager interface. This implementation creates a single key in response - to all invocations of create_key. Side effects (e.g., raising exceptions) - for each method are handled as specified by the key manager interface. + """This key manager implementation supports all the methods specified by + the key manager interface. This implementation creates a single key in + response to all invocations of create_key. Side effects + (e.g., raising exceptions) for each method are handled + as specified by the key manager interface. """ def __init__(self): diff --git a/nova/keymgr/key.py b/nova/keymgr/key.py index 2f12332ef77c..54080ab64c43 100644 --- a/nova/keymgr/key.py +++ b/nova/keymgr/key.py @@ -54,9 +54,7 @@ class Key(object): class SymmetricKey(Key): - """ - This class represents symmetric keys - """ + """This class represents symmetric keys.""" def __init__(self, alg, key): """Create a new SymmetricKey object. diff --git a/nova/keymgr/mock_key_mgr.py b/nova/keymgr/mock_key_mgr.py index 06dc9739b32d..6af88683a1bc 100644 --- a/nova/keymgr/mock_key_mgr.py +++ b/nova/keymgr/mock_key_mgr.py @@ -41,8 +41,7 @@ LOG = logging.getLogger(__name__) class MockKeyManager(key_mgr.KeyManager): - """ - This mock key manager implementation supports all the methods specified + """This mock key manager implementation supports all the methods specified by the key manager interface. This implementation stores keys within a dictionary, and as a result, it is not acceptable for use across different services. Side effects (e.g., raising exceptions) for each method are diff --git a/nova/keymgr/single_key_mgr.py b/nova/keymgr/single_key_mgr.py index 5bf95166d655..586413525597 100644 --- a/nova/keymgr/single_key_mgr.py +++ b/nova/keymgr/single_key_mgr.py @@ -29,11 +29,11 @@ LOG = logging.getLogger(__name__) class SingleKeyManager(mock_key_mgr.MockKeyManager): - """ - This key manager implementation supports all the methods specified by the - key manager interface. This implementation creates a single key in response - to all invocations of create_key. Side effects (e.g., raising exceptions) - for each method are handled as specified by the key manager interface. + """This key manager implementation supports all the methods specified by + the key manager interface. This implementation creates a single key in + response to all invocations of create_key. Side effects + (e.g., raising exceptions) for each method are handled as specified by + the key manager interface. """ def __init__(self): diff --git a/nova/netconf.py b/nova/netconf.py index 712d797d6b66..e050bbb847ff 100644 --- a/nova/netconf.py +++ b/nova/netconf.py @@ -25,8 +25,7 @@ CONF = cfg.CONF def _get_my_ip(): - """ - Returns the actual ip of the local machine. + """Returns the actual ip of the local machine. This code figures out what source address would be used if some traffic were to be sent out to some well known address on the Internet. In this diff --git a/nova/network/api.py b/nova/network/api.py index 5870217fb48c..8d43e06903c9 100644 --- a/nova/network/api.py +++ b/nova/network/api.py @@ -36,8 +36,7 @@ LOG = logging.getLogger(__name__) def refresh_cache(f): - """ - Decorator to update the instance_info_cache + """Decorator to update the instance_info_cache Requires context and instance as function args """ diff --git a/nova/network/linux_net.py b/nova/network/linux_net.py index 81e49fa7cb93..0764da6b3cfc 100644 --- a/nova/network/linux_net.py +++ b/nova/network/linux_net.py @@ -1388,8 +1388,7 @@ def get_dev(network): class LinuxNetInterfaceDriver(object): - """ - Abstract class that defines generic network host API + """Abstract class that defines generic network host API for for all Linux interface drivers. """ diff --git a/nova/network/minidns.py b/nova/network/minidns.py index 81fbda690255..e67fe4f47add 100644 --- a/nova/network/minidns.py +++ b/nova/network/minidns.py @@ -28,8 +28,7 @@ LOG = logging.getLogger(__name__) class MiniDNS(dns_driver.DNSDriver): - """ - Trivial DNS driver. This will read/write to a local, flat file + """Trivial DNS driver. This will read/write to a local, flat file and have no effect on your actual DNS system. This class is strictly for testing purposes, and should keep you out of dependency hell. diff --git a/nova/pci/pci_utils.py b/nova/pci/pci_utils.py index 4490a488df4b..a9282ff15e35 100644 --- a/nova/pci/pci_utils.py +++ b/nova/pci/pci_utils.py @@ -46,8 +46,7 @@ def pci_device_prop_match(pci_dev, specs): def parse_address(address): - """ - Returns (domain, bus, slot, function) from PCI address that is stored in + """Returns (domain, bus, slot, function) from PCI address that is stored in PciDevice DB table. """ m = _PCI_ADDRESS_REGEX.match(address) diff --git a/nova/quota.py b/nova/quota.py index 745fe9eb7af6..10ba042cc3df 100644 --- a/nova/quota.py +++ b/nova/quota.py @@ -88,8 +88,7 @@ CONF.register_opts(quota_opts) class DbQuotaDriver(object): - """ - Driver to perform necessary checks to enforce quotas and obtain + """Driver to perform necessary checks to enforce quotas and obtain quota information. The default driver utilizes the local database. """ @@ -127,8 +126,7 @@ class DbQuotaDriver(object): def get_class_quotas(self, context, resources, quota_class, defaults=True): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given quota class. :param context: The request context, for access checks. @@ -201,8 +199,7 @@ class DbQuotaDriver(object): quota_class=None, defaults=True, usages=True, project_quotas=None, user_quotas=None): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given user and project. :param context: The request context, for access checks. @@ -244,8 +241,7 @@ class DbQuotaDriver(object): def get_project_quotas(self, context, resources, project_id, quota_class=None, defaults=True, usages=True, remains=False, project_quotas=None): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given project. :param context: The request context, for access checks. @@ -279,8 +275,7 @@ class DbQuotaDriver(object): def get_settable_quotas(self, context, resources, project_id, user_id=None): - """ - Given a list of resources, retrieve the range of settable quotas for + """Given a list of resources, retrieve the range of settable quotas for the given user or project. :param context: The request context, for access checks. @@ -317,8 +312,7 @@ class DbQuotaDriver(object): def _get_quotas(self, context, resources, keys, has_sync, project_id=None, user_id=None, project_quotas=None): - """ - A helper method which retrieves the quotas for the specific + """A helper method which retrieves the quotas for the specific resources identified by keys, and which apply to the current context. @@ -565,8 +559,7 @@ class DbQuotaDriver(object): user_id=user_id) def usage_reset(self, context, resources): - """ - Reset the usage records for a particular user on a list of + """Reset the usage records for a particular user on a list of resources. This will force that user's usage records to be refreshed the next time a reservation is made. @@ -595,8 +588,7 @@ class DbQuotaDriver(object): pass def destroy_all_by_project_and_user(self, context, project_id, user_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project and user. :param context: The request context, for access checks. @@ -607,8 +599,7 @@ class DbQuotaDriver(object): db.quota_destroy_all_by_project_and_user(context, project_id, user_id) def destroy_all_by_project(self, context, project_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project. :param context: The request context, for access checks. @@ -665,8 +656,7 @@ class NoopQuotaDriver(object): def get_class_quotas(self, context, resources, quota_class, defaults=True): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given quota class. :param context: The request context, for access checks. @@ -697,8 +687,7 @@ class NoopQuotaDriver(object): def get_user_quotas(self, context, resources, project_id, user_id, quota_class=None, defaults=True, usages=True): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given user and project. :param context: The request context, for access checks. @@ -722,8 +711,7 @@ class NoopQuotaDriver(object): def get_project_quotas(self, context, resources, project_id, quota_class=None, defaults=True, usages=True, remains=False): - """ - Given a list of resources, retrieve the quotas for the given + """Given a list of resources, retrieve the quotas for the given project. :param context: The request context, for access checks. @@ -747,8 +735,7 @@ class NoopQuotaDriver(object): def get_settable_quotas(self, context, resources, project_id, user_id=None): - """ - Given a list of resources, retrieve the range of settable quotas for + """Given a list of resources, retrieve the range of settable quotas for the given user or project. :param context: The request context, for access checks. @@ -862,8 +849,7 @@ class NoopQuotaDriver(object): pass def usage_reset(self, context, resources): - """ - Reset the usage records for a particular user on a list of + """Reset the usage records for a particular user on a list of resources. This will force that user's usage records to be refreshed the next time a reservation is made. @@ -878,8 +864,7 @@ class NoopQuotaDriver(object): pass def destroy_all_by_project_and_user(self, context, project_id, user_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project and user. :param context: The request context, for access checks. @@ -889,8 +874,7 @@ class NoopQuotaDriver(object): pass def destroy_all_by_project(self, context, project_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project. :param context: The request context, for access checks. @@ -913,8 +897,7 @@ class BaseResource(object): """Describe a single resource for quota checking.""" def __init__(self, name, flag=None): - """ - Initializes a Resource. + """Initializes a Resource. :param name: The name of the resource, i.e., "instances". :param flag: The name of the flag or configuration option @@ -926,8 +909,7 @@ class BaseResource(object): self.flag = flag def quota(self, driver, context, **kwargs): - """ - Given a driver and context, obtain the quota for this + """Given a driver and context, obtain the quota for this resource. :param driver: A quota driver. @@ -1023,14 +1005,12 @@ class AbsoluteResource(BaseResource): class CountableResource(AbsoluteResource): - """ - Describe a resource where the counts aren't based solely on the + """Describe a resource where the counts aren't based solely on the project ID. """ def __init__(self, name, count, flag=None): - """ - Initializes a CountableResource. + """Initializes a CountableResource. Countable resources are those resources which directly correspond to objects in the database, i.e., instances, cores, @@ -1185,8 +1165,7 @@ class QuotaEngine(object): remains=remains) def get_settable_quotas(self, context, project_id, user_id=None): - """ - Given a list of resources, retrieve the range of settable quotas for + """Given a list of resources, retrieve the range of settable quotas for the given user or project. :param context: The request context, for access checks. @@ -1342,8 +1321,7 @@ class QuotaEngine(object): LOG.debug(_("Rolled back reservations %s"), reservations) def usage_reset(self, context, resources): - """ - Reset the usage records for a particular user on a list of + """Reset the usage records for a particular user on a list of resources. This will force that user's usage records to be refreshed the next time a reservation is made. @@ -1359,8 +1337,7 @@ class QuotaEngine(object): self._driver.usage_reset(context, resources) def destroy_all_by_project_and_user(self, context, project_id, user_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project and user. :param context: The request context, for access checks. @@ -1372,8 +1349,7 @@ class QuotaEngine(object): project_id, user_id) def destroy_all_by_project(self, context, project_id): - """ - Destroy all quotas, usages, and reservations associated with a + """Destroy all quotas, usages, and reservations associated with a project. :param context: The request context, for access checks. diff --git a/nova/scheduler/filters/isolated_hosts_filter.py b/nova/scheduler/filters/isolated_hosts_filter.py index 6caaf5d4cc6b..a15193a8f6c8 100644 --- a/nova/scheduler/filters/isolated_hosts_filter.py +++ b/nova/scheduler/filters/isolated_hosts_filter.py @@ -40,8 +40,7 @@ class IsolatedHostsFilter(filters.BaseHostFilter): run_filter_once_per_request = True def host_passes(self, host_state, filter_properties): - """ - Result Matrix with 'restrict_isolated_hosts_to_isolated_images' set + """Result Matrix with 'restrict_isolated_hosts_to_isolated_images' set to True: | isolated_image | non_isolated_image -------------+----------------+------------------- diff --git a/nova/scheduler/filters/trusted_filter.py b/nova/scheduler/filters/trusted_filter.py index 2eac14174d62..edc1d25928ef 100644 --- a/nova/scheduler/filters/trusted_filter.py +++ b/nova/scheduler/filters/trusted_filter.py @@ -83,8 +83,7 @@ CONF.register_opts(trusted_opts, group=trust_group) class HTTPSClientAuthConnection(httplib.HTTPSConnection): - """ - Class to make a HTTPS connection, with support for full client-based + """Class to make a HTTPS connection, with support for full client-based SSL Authentication """ @@ -100,8 +99,7 @@ class HTTPSClientAuthConnection(httplib.HTTPSConnection): self.timeout = timeout def connect(self): - """ - Connect to a host on a given (SSL) port. + """Connect to a host on a given (SSL) port. If ca_file is pointing somewhere, use it to check Server Certificate. Redefined/copied and extended from httplib.py:1105 (Python 2.6.x). diff --git a/nova/scheduler/scheduler_options.py b/nova/scheduler/scheduler_options.py index 435f911b2ece..7dbbcd56e88f 100644 --- a/nova/scheduler/scheduler_options.py +++ b/nova/scheduler/scheduler_options.py @@ -44,8 +44,7 @@ LOG = logging.getLogger(__name__) class SchedulerOptions(object): - """ - SchedulerOptions monitors a local .json file for changes and loads it + """SchedulerOptions monitors a local .json file for changes and loads it if needed. This file is converted to a data structure and passed into the filtering and weighing functions which can use it for dynamic configuration. diff --git a/nova/servicegroup/drivers/db.py b/nova/servicegroup/drivers/db.py index 238e867aa469..ab39cde29124 100644 --- a/nova/servicegroup/drivers/db.py +++ b/nova/servicegroup/drivers/db.py @@ -72,8 +72,7 @@ class DbDriver(api.ServiceGroupDriver): return abs(elapsed) <= CONF.service_down_time def get_all(self, group_id): - """ - Returns ALL members of the given group + """Returns ALL members of the given group """ LOG.debug(_('DB_Driver: get_all members of the %s group') % group_id) rs = [] diff --git a/nova/servicegroup/drivers/mc.py b/nova/servicegroup/drivers/mc.py index a22aa7cf4d35..1bc6e7a1df10 100644 --- a/nova/servicegroup/drivers/mc.py +++ b/nova/servicegroup/drivers/mc.py @@ -70,8 +70,7 @@ class MemcachedDriver(api.ServiceGroupDriver): return self.mc.get(str(key)) is not None def get_all(self, group_id): - """ - Returns ALL members of the given group + """Returns ALL members of the given group """ LOG.debug(_('Memcached_Driver: get_all members of the %s group') % group_id) diff --git a/nova/test.py b/nova/test.py index 6b470ae5f5d5..cbf1d7246af3 100644 --- a/nova/test.py +++ b/nova/test.py @@ -321,8 +321,7 @@ class TimeOverride(fixtures.Fixture): class NoDBTestCase(TestCase): - """ - `NoDBTestCase` differs from TestCase in that DB access is not supported. + """`NoDBTestCase` differs from TestCase in that DB access is not supported. This makes tests run significantly faster. If possible, all new tests should derive from this class. """ diff --git a/nova/tests/api/ec2/test_api.py b/nova/tests/api/ec2/test_api.py index 04f5dd854080..c5c3a63457ad 100644 --- a/nova/tests/api/ec2/test_api.py +++ b/nova/tests/api/ec2/test_api.py @@ -282,10 +282,9 @@ class ApiEc2TestCase(test.TestCase): return self.http def test_return_valid_isoformat(self): - """ - Ensure that the ec2 api returns datetime in xs:dateTime - (which apparently isn't datetime.isoformat()) - NOTE(ken-pepple): https://bugs.launchpad.net/nova/+bug/721297 + """Ensure that the ec2 api returns datetime in xs:dateTime + (which apparently isn't datetime.isoformat()) + NOTE(ken-pepple): https://bugs.launchpad.net/nova/+bug/721297 """ conv = apirequest._database_to_isoformat # sqlite database representation with microseconds @@ -438,8 +437,7 @@ class ApiEc2TestCase(test.TestCase): 'test group') def test_authorize_revoke_security_group_cidr(self): - """ - Test that we can add and remove CIDR based rules + """Test that we can add and remove CIDR based rules to a security group """ self.expect_http() @@ -542,8 +540,7 @@ class ApiEc2TestCase(test.TestCase): self.assertEqual(rv[0].name, 'default') def test_authorize_revoke_security_group_cidr_v6(self): - """ - Test that we can add and remove CIDR based rules + """Test that we can add and remove CIDR based rules to a security group for IPv6 """ self.expect_http() @@ -594,8 +591,7 @@ class ApiEc2TestCase(test.TestCase): self.assertEqual(rv[0].name, 'default') def test_authorize_revoke_security_group_foreign_group(self): - """ - Test that we can grant and revoke another security group access + """Test that we can grant and revoke another security group access to a security group """ self.expect_http() diff --git a/nova/tests/api/ec2/test_cloud.py b/nova/tests/api/ec2/test_cloud.py index 70e27a468b2e..cb8a8de7938d 100644 --- a/nova/tests/api/ec2/test_cloud.py +++ b/nova/tests/api/ec2/test_cloud.py @@ -2439,8 +2439,7 @@ class CloudTestCase(test.TestCase): self._do_test_create_image(False) def test_create_image_instance_store(self): - """ - Ensure CreateImage fails as expected for an instance-store-backed + """Ensure CreateImage fails as expected for an instance-store-backed instance """ # enforce periodic tasks run in short time to avoid wait for 60s. diff --git a/nova/tests/api/ec2/test_error_response.py b/nova/tests/api/ec2/test_error_response.py index a446742adc42..925d6723ed5f 100644 --- a/nova/tests/api/ec2/test_error_response.py +++ b/nova/tests/api/ec2/test_error_response.py @@ -39,8 +39,7 @@ class TestServerExceptionEC2(Exception): class Ec2ErrorResponseTestCase(test.NoDBTestCase): - """ - Test EC2 error responses. + """Test EC2 error responses. This deals mostly with api/ec2/__init__.py code, especially the ec2_error_ex helper. @@ -85,17 +84,14 @@ class Ec2ErrorResponseTestCase(test.NoDBTestCase): self.assertEqual(requestid_e.text, self.context.request_id) def test_exception_ec2_4xx(self): - """ - Test response to EC2 exception with code = 400. - """ + """Test response to EC2 exception with code = 400.""" msg = "Test client failure." err = ec2.ec2_error_ex(TestClientExceptionEC2(msg), self.req) self._validate_ec2_error(err, TestClientExceptionEC2.code, TestClientExceptionEC2.ec2_code, msg) def test_exception_ec2_5xx(self): - """ - Test response to EC2 exception with code = 500. + """Test response to EC2 exception with code = 500. Expected errors are treated as client ones even with 5xx code. """ @@ -105,9 +101,7 @@ class Ec2ErrorResponseTestCase(test.NoDBTestCase): msg) def test_unexpected_exception_ec2_4xx(self): - """ - Test response to unexpected EC2 exception with code = 400. - """ + """Test response to unexpected EC2 exception with code = 400.""" msg = "Test unexpected client failure." err = ec2.ec2_error_ex(TestClientExceptionEC2(msg), self.req, unexpected=True) @@ -115,8 +109,7 @@ class Ec2ErrorResponseTestCase(test.NoDBTestCase): TestClientExceptionEC2.ec2_code, msg) def test_unexpected_exception_ec2_5xx(self): - """ - Test response to unexpected EC2 exception with code = 500. + """Test response to unexpected EC2 exception with code = 500. Server exception messages (with code >= 500 or without code) should be filtered as they might contain sensitive information. @@ -129,8 +122,7 @@ class Ec2ErrorResponseTestCase(test.NoDBTestCase): unknown_msg=True) def test_unexpected_exception_builtin(self): - """ - Test response to builtin unexpected exception. + """Test response to builtin unexpected exception. Server exception messages (with code >= 500 or without code) should be filtered as they might contain sensitive information. diff --git a/nova/tests/api/openstack/compute/contrib/test_floating_ip_dns.py b/nova/tests/api/openstack/compute/contrib/test_floating_ip_dns.py index 6049fd7baf37..685b25b3a8bd 100644 --- a/nova/tests/api/openstack/compute/contrib/test_floating_ip_dns.py +++ b/nova/tests/api/openstack/compute/contrib/test_floating_ip_dns.py @@ -41,8 +41,7 @@ floating_ip_id = '1' def _quote_domain(domain): - """ - Domain names tend to have .'s in them. Urllib doesn't quote dots, + """Domain names tend to have .'s in them. Urllib doesn't quote dots, but Routes tends to choke on them, so we need an extra level of by-hand quoting here. This function needs to duplicate the one in python-novaclient/novaclient/v1_1/floating_ip_dns.py diff --git a/nova/tests/api/openstack/compute/contrib/test_hosts.py b/nova/tests/api/openstack/compute/contrib/test_hosts.py index 2174cba36bcd..eb06fdea4d37 100644 --- a/nova/tests/api/openstack/compute/contrib/test_hosts.py +++ b/nova/tests/api/openstack/compute/contrib/test_hosts.py @@ -39,9 +39,8 @@ def stub_service_get_by_host_and_topic(context, host_name, topic): def stub_set_host_enabled(context, host_name, enabled): - """ - Simulates three possible behaviours for VM drivers or compute drivers when - enabling or disabling a host. + """Simulates three possible behaviours for VM drivers or compute + drivers when enabling or disabling a host. 'enabled' means new instances can go to this host 'disabled' means they can't diff --git a/nova/tests/api/openstack/compute/plugins/v3/test_block_device_mapping.py b/nova/tests/api/openstack/compute/plugins/v3/test_block_device_mapping.py index d2b4a90d801b..d81f4989b0ba 100644 --- a/nova/tests/api/openstack/compute/plugins/v3/test_block_device_mapping.py +++ b/nova/tests/api/openstack/compute/plugins/v3/test_block_device_mapping.py @@ -102,8 +102,7 @@ class BlockDeviceMappingTest(test.TestCase): override_controller=self.no_volumes_controller) def test_create_instance_with_volumes_enabled_no_image(self): - """ - Test that the create will fail if there is no image + """Test that the create will fail if there is no image and no bdms supplied in the request """ old_create = compute_api.API.create diff --git a/nova/tests/api/openstack/compute/plugins/v3/test_flavors.py b/nova/tests/api/openstack/compute/plugins/v3/test_flavors.py index 16f992ba4930..25c0cfeb5600 100644 --- a/nova/tests/api/openstack/compute/plugins/v3/test_flavors.py +++ b/nova/tests/api/openstack/compute/plugins/v3/test_flavors.py @@ -525,9 +525,7 @@ class FlavorDisabledTest(test.TestCase): class DisabledFlavorsWithRealDBTest(test.TestCase): - """ - Tests that disabled flavors should not be shown nor listed. - """ + """Tests that disabled flavors should not be shown nor listed.""" def setUp(self): super(DisabledFlavorsWithRealDBTest, self).setUp() self.controller = flavors.FlavorsController() @@ -588,12 +586,11 @@ class DisabledFlavorsWithRealDBTest(test.TestCase): self.assertEqual(db_flavorids, api_flavorids) def test_show_should_include_disabled_flavor_for_user(self): - """ - Counterintuitively we should show disabled flavors to all users and not - just admins. The reason is that, when a user performs a server-show - request, we want to be able to display the pretty flavor name ('512 MB - Instance') and not just the flavor-id even if the flavor id has been - marked disabled. + """Counterintuitively we should show disabled flavors to all users + and not just admins. The reason is that, when a user performs a + server-show request, we want to be able to display the pretty + flavor name ('512 MB Instance') and not just the flavor-id even if + the flavor id has been marked disabled. """ self.context.is_admin = False diff --git a/nova/tests/api/openstack/compute/plugins/v3/test_hosts.py b/nova/tests/api/openstack/compute/plugins/v3/test_hosts.py index 5b4da1f82673..2029ae9002a8 100644 --- a/nova/tests/api/openstack/compute/plugins/v3/test_hosts.py +++ b/nova/tests/api/openstack/compute/plugins/v3/test_hosts.py @@ -37,9 +37,8 @@ def stub_service_get_by_host_and_topic(context, host_name, topic): def stub_set_host_enabled(context, host_name, enabled): - """ - Simulates three possible behaviours for VM drivers or compute drivers when - enabling or disabling a host. + """Simulates three possible behaviours for VM drivers or compute + drivers when enabling or disabling a host. 'enabled' means new instances can go to this host 'disabled' means they can't diff --git a/nova/tests/api/openstack/compute/plugins/v3/test_multiple_create.py b/nova/tests/api/openstack/compute/plugins/v3/test_multiple_create.py index 5f726652bf33..72a246f3bb72 100644 --- a/nova/tests/api/openstack/compute/plugins/v3/test_multiple_create.py +++ b/nova/tests/api/openstack/compute/plugins/v3/test_multiple_create.py @@ -407,8 +407,7 @@ class ServersControllerCreateTest(test.TestCase): self.assertTrue(len(reservation_id) > 1) def test_create_multiple_instances_with_multiple_volume_bdm(self): - """ - Test that a BadRequest is raised if multiple instances + """Test that a BadRequest is raised if multiple instances are requested with a list of block device mappings for volumes. """ min_count = 2 @@ -431,8 +430,7 @@ class ServersControllerCreateTest(test.TestCase): self._test_create_extra, params, no_image=True) def test_create_multiple_instances_with_single_volume_bdm(self): - """ - Test that a BadRequest is raised if multiple instances + """Test that a BadRequest is raised if multiple instances are requested to boot from a single volume. """ min_count = 2 diff --git a/nova/tests/api/openstack/compute/plugins/v3/test_servers.py b/nova/tests/api/openstack/compute/plugins/v3/test_servers.py index 8f25dd2bbb73..7b9a52378ff5 100644 --- a/nova/tests/api/openstack/compute/plugins/v3/test_servers.py +++ b/nova/tests/api/openstack/compute/plugins/v3/test_servers.py @@ -1229,12 +1229,11 @@ class ServersControllerTest(ControllerTest): self.assertEqual(s['metadata']['seq'], str(i + 1)) def test_get_all_server_details_with_host(self): - ''' - We want to make sure that if two instances are on the same host, then - they return the same host_id. If two instances are on different hosts, - they should return different host_ids. In this test, there are 5 - instances - 2 on one host and 3 on another. - ''' + """We want to make sure that if two instances are on the same host, + then they return the same host_id. If two instances are on different + hosts, they should return different host_ids. In this test, + there are 5 instances - 2 on one host and 3 on another. + """ def return_servers_with_host(context, *args, **kwargs): return [fakes.stub_instance(i + 1, 'fake', 'fake', host=i % 2, @@ -2896,8 +2895,7 @@ class ServersViewBuilderTest(test.TestCase): class ServersAllExtensionsTestCase(test.TestCase): - """ - Servers tests using default API router with all extensions enabled. + """Servers tests using default API router with all extensions enabled. The intent here is to catch cases where extensions end up throwing an exception because of a malformed request before the core API @@ -2957,9 +2955,7 @@ class ServersAllExtensionsTestCase(test.TestCase): class ServersInvalidRequestTestCase(test.TestCase): - """ - Tests of places we throw 400 Bad Request from - """ + """Tests of places we throw 400 Bad Request from.""" def setUp(self): super(ServersInvalidRequestTestCase, self).setUp() diff --git a/nova/tests/api/openstack/compute/test_flavors.py b/nova/tests/api/openstack/compute/test_flavors.py index 427b31dd92b1..0993da090cc2 100644 --- a/nova/tests/api/openstack/compute/test_flavors.py +++ b/nova/tests/api/openstack/compute/test_flavors.py @@ -695,9 +695,7 @@ class FlavorsXMLSerializationTest(test.TestCase): class DisabledFlavorsWithRealDBTest(test.TestCase): - """ - Tests that disabled flavors should not be shown nor listed. - """ + """Tests that disabled flavors should not be shown nor listed.""" def setUp(self): super(DisabledFlavorsWithRealDBTest, self).setUp() self.controller = flavors.Controller() @@ -759,9 +757,8 @@ class DisabledFlavorsWithRealDBTest(test.TestCase): self.assertEqual(db_flavorids, api_flavorids) def test_show_should_include_disabled_flavor_for_user(self): - """ - Counterintuitively we should show disabled flavors to all users and not - just admins. The reason is that, when a user performs a server-show + """Counterintuitively we should show disabled flavors to all users and + not just admins. The reason is that, when a user performs a server-show request, we want to be able to display the pretty flavor name ('512 MB Instance') and not just the flavor-id even if the flavor id has been marked disabled. diff --git a/nova/tests/api/openstack/compute/test_images.py b/nova/tests/api/openstack/compute/test_images.py index d5a97b78fbbc..7326c264cf39 100644 --- a/nova/tests/api/openstack/compute/test_images.py +++ b/nova/tests/api/openstack/compute/test_images.py @@ -39,8 +39,7 @@ NOW_API_FORMAT = "2010-10-11T10:30:22Z" class ImagesControllerTest(test.NoDBTestCase): - """ - Test of the OpenStack API /images application controller w/Glance. + """Test of the OpenStack API /images application controller w/Glance. """ def setUp(self): diff --git a/nova/tests/api/openstack/compute/test_limits.py b/nova/tests/api/openstack/compute/test_limits.py index 13c7943ac0cd..c41c29da4e50 100644 --- a/nova/tests/api/openstack/compute/test_limits.py +++ b/nova/tests/api/openstack/compute/test_limits.py @@ -73,9 +73,7 @@ class BaseLimitTestSuite(test.NoDBTestCase): class LimitsControllerTest(BaseLimitTestSuite): - """ - Tests for `limits.LimitsController` class. - """ + """Tests for `limits.LimitsController` class.""" def setUp(self): """Run before each test.""" @@ -321,9 +319,7 @@ class MockLimiter(limits.Limiter): class LimitMiddlewareTest(BaseLimitTestSuite): - """ - Tests for the `limits.RateLimitingMiddleware` class. - """ + """Tests for the `limits.RateLimitingMiddleware` class.""" @webob.dec.wsgify def _empty_app(self, request): @@ -397,9 +393,7 @@ class LimitMiddlewareTest(BaseLimitTestSuite): class LimitTest(BaseLimitTestSuite): - """ - Tests for the `limits.Limit` class. - """ + """Tests for the `limits.Limit` class.""" def test_GET_no_delay(self): # Test a limit handles 1 GET per second. @@ -429,8 +423,7 @@ class LimitTest(BaseLimitTestSuite): class ParseLimitsTest(BaseLimitTestSuite): - """ - Tests for the default limits parser in the in-memory + """Tests for the default limits parser in the in-memory `limits.Limiter` class. """ @@ -495,9 +488,7 @@ class ParseLimitsTest(BaseLimitTestSuite): class LimiterTest(BaseLimitTestSuite): - """ - Tests for the in-memory `limits.Limiter` class. - """ + """Tests for the in-memory `limits.Limiter` class.""" def setUp(self): """Run before each test.""" @@ -518,8 +509,7 @@ class LimiterTest(BaseLimitTestSuite): return sum(item for item in results if item) def test_no_delay_GET(self): - """ - Simple test to ensure no delay on a single call for a limit verb we + """Simple test to ensure no delay on a single call for a limit verb we didn"t set. """ delay = self.limiter.check_for_delay("GET", "/anything") @@ -531,8 +521,7 @@ class LimiterTest(BaseLimitTestSuite): self.assertEqual(delay, (None, None)) def test_delay_PUT(self): - """ - Ensure the 11th PUT will result in a delay of 6.0 seconds until + """Ensure the 11th PUT will result in a delay of 6.0 seconds until the next request will be granced. """ expected = [None] * 10 + [6.0] @@ -541,8 +530,7 @@ class LimiterTest(BaseLimitTestSuite): self.assertEqual(expected, results) def test_delay_POST(self): - """ - Ensure the 8th POST will result in a delay of 6.0 seconds until + """Ensure the 8th POST will result in a delay of 6.0 seconds until the next request will be granced. """ expected = [None] * 7 @@ -564,10 +552,9 @@ class LimiterTest(BaseLimitTestSuite): self.assertEqual(expected, results) def test_delay_PUT_servers(self): - """ - Ensure PUT on /servers limits at 5 requests, and PUT elsewhere is still - OK after 5 requests...but then after 11 total requests, PUT limiting - kicks in. + """Ensure PUT on /servers limits at 5 requests, and PUT elsewhere is + still OK after 5 requests...but then after 11 total requests, PUT + limiting kicks in. """ # First 6 requests on PUT /servers expected = [None] * 5 + [12.0] @@ -580,8 +567,7 @@ class LimiterTest(BaseLimitTestSuite): self.assertEqual(expected, results) def test_delay_PUT_wait(self): - """ - Ensure after hitting the limit and then waiting for the correct + """Ensure after hitting the limit and then waiting for the correct amount of time, the limit will be lifted. """ expected = [None] * 10 + [6.0] @@ -665,9 +651,7 @@ class LimiterTest(BaseLimitTestSuite): class WsgiLimiterTest(BaseLimitTestSuite): - """ - Tests for `limits.WsgiLimiter` class. - """ + """Tests for `limits.WsgiLimiter` class.""" def setUp(self): """Run before each test.""" @@ -736,9 +720,7 @@ class WsgiLimiterTest(BaseLimitTestSuite): class FakeHttplibSocket(object): - """ - Fake `httplib.HTTPResponse` replacement. - """ + """Fake `httplib.HTTPResponse` replacement.""" def __init__(self, response_string): """Initialize new `FakeHttplibSocket`.""" @@ -750,20 +732,15 @@ class FakeHttplibSocket(object): class FakeHttplibConnection(object): - """ - Fake `httplib.HTTPConnection`. - """ + """Fake `httplib.HTTPConnection`.""" def __init__(self, app, host): - """ - Initialize `FakeHttplibConnection`. - """ + """Initialize `FakeHttplibConnection`.""" self.app = app self.host = host def request(self, method, path, body="", headers=None): - """ - Requests made via this connection actually get translated and routed + """Requests made via this connection actually get translated and routed into our WSGI app, we then wait for the response and turn it back into an `httplib.HTTPResponse`. """ @@ -826,13 +803,10 @@ def wire_HTTPConnection_to_WSGI(host, app): class WsgiLimiterProxyTest(BaseLimitTestSuite): - """ - Tests for the `limits.WsgiLimiterProxy` class. - """ + """Tests for the `limits.WsgiLimiterProxy` class.""" def setUp(self): - """ - Do some nifty HTTP/WSGI magic which allows for WSGI to be called + """Do some nifty HTTP/WSGI magic which allows for WSGI to be called directly by something like the `httplib` library. """ super(WsgiLimiterProxyTest, self).setUp() diff --git a/nova/tests/api/openstack/compute/test_servers.py b/nova/tests/api/openstack/compute/test_servers.py index a9df6099a1d2..a93bdc3389c8 100644 --- a/nova/tests/api/openstack/compute/test_servers.py +++ b/nova/tests/api/openstack/compute/test_servers.py @@ -1141,12 +1141,11 @@ class ServersControllerTest(ControllerTest): self.assertEqual(s['metadata']['seq'], str(i + 1)) def test_get_all_server_details_with_host(self): - ''' - We want to make sure that if two instances are on the same host, then - they return the same hostId. If two instances are on different hosts, - they should return different hostId's. In this test, there are 5 - instances - 2 on one host and 3 on another. - ''' + """We want to make sure that if two instances are on the same host, + then they return the same hostId. If two instances are on different + hosts, they should return different hostId's. In this test, there + are 5 instances - 2 on one host and 3 on another. + """ def return_servers_with_host(context, *args, **kwargs): return [fakes.stub_instance(i + 1, 'fake', 'fake', host=i % 2, @@ -2002,8 +2001,7 @@ class ServersControllerCreateTest(test.TestCase): self.assertTrue(len(reservation_id) > 1) def test_create_multiple_instances_with_multiple_volume_bdm(self): - """ - Test that a BadRequest is raised if multiple instances + """Test that a BadRequest is raised if multiple instances are requested with a list of block device mappings for volumes. """ self.ext_mgr.extensions = {'os-multiple-create': 'fake'} @@ -2027,8 +2025,7 @@ class ServersControllerCreateTest(test.TestCase): self._test_create_extra, params, no_image=True) def test_create_multiple_instances_with_single_volume_bdm(self): - """ - Test that a BadRequest is raised if multiple instances + """Test that a BadRequest is raised if multiple instances are requested to boot from a single volume. """ self.ext_mgr.extensions = {'os-multiple-create': 'fake'} @@ -2505,8 +2502,7 @@ class ServersControllerCreateTest(test.TestCase): self._test_create_extra(params) def test_create_instance_with_volumes_enabled_no_image(self): - """ - Test that the create will fail if there is no image + """Test that the create will fail if there is no image and no bdms supplied in the request """ self.ext_mgr.extensions = {'os-volumes': 'fake'} @@ -2533,8 +2529,7 @@ class ServersControllerCreateTest(test.TestCase): self._test_create_extra, {}, no_image=True) def test_create_instance_with_volumes_enabled_and_bdms_no_image(self): - """ - Test that the create works if there is no image supplied but + """Test that the create works if there is no image supplied but os-volumes extension is enabled and bdms are supplied """ self.ext_mgr.extensions = {'os-volumes': 'fake'} @@ -4657,8 +4652,7 @@ class ServerXMLSerializationTest(test.TestCase): class ServersAllExtensionsTestCase(test.TestCase): - """ - Servers tests using default API router with all extensions enabled. + """Servers tests using default API router with all extensions enabled. The intent here is to catch cases where extensions end up throwing an exception because of a malformed request before the core API @@ -4717,9 +4711,7 @@ class ServersAllExtensionsTestCase(test.TestCase): class ServersUnprocessableEntityTestCase(test.TestCase): - """ - Tests of places we throw 422 Unprocessable Entity from - """ + """Tests of places we throw 422 Unprocessable Entity from.""" def setUp(self): super(ServersUnprocessableEntityTestCase, self).setUp() diff --git a/nova/tests/api/openstack/compute/test_versions.py b/nova/tests/api/openstack/compute/test_versions.py index fdd8fc650831..51cd9a1f0b82 100644 --- a/nova/tests/api/openstack/compute/test_versions.py +++ b/nova/tests/api/openstack/compute/test_versions.py @@ -435,8 +435,7 @@ class VersionsTest(test.NoDBTestCase): [{'rel': 'self', 'href': 'http://localhost/v3/images/1'}])) def test_multi_choice_server_atom(self): - """ - Make sure multi choice responses do not have content-type + """Make sure multi choice responses do not have content-type application/atom+xml (should use default of json) """ req = webob.Request.blank('/servers') diff --git a/nova/tests/api/openstack/fakes.py b/nova/tests/api/openstack/fakes.py index 7b7df563b47f..414839970d2c 100644 --- a/nova/tests/api/openstack/fakes.py +++ b/nova/tests/api/openstack/fakes.py @@ -288,9 +288,8 @@ def _make_image_fixtures(): def stub_out_glanceclient_create(stubs, sent_to_glance): - """ - We return the metadata sent to glance by modifying the sent_to_glance dict - in place. + """We return the metadata sent to glance by modifying the sent_to_glance + dict in place """ orig_add_image = glanceclient.v1.images.ImageManager.create diff --git a/nova/tests/api/openstack/test_common.py b/nova/tests/api/openstack/test_common.py index 34c16032cf7e..9a656b9f2907 100644 --- a/nova/tests/api/openstack/test_common.py +++ b/nova/tests/api/openstack/test_common.py @@ -36,10 +36,9 @@ ATOMNS = "{http://www.w3.org/2005/Atom}" class LimiterTest(test.TestCase): - """ - Unit tests for the `nova.api.openstack.common.limited` method which takes - in a list of items and, depending on the 'offset' and 'limit' GET params, - returns a subset or complete set of the given items. + """Unit tests for the `nova.api.openstack.common.limited` method which + takes in a list of items and, depending on the 'offset' and 'limit' GET + params, returns a subset or complete set of the given items. """ def setUp(self): @@ -160,8 +159,7 @@ class LimiterTest(test.TestCase): class PaginationParamsTest(test.TestCase): - """ - Unit tests for the `nova.api.openstack.common.get_pagination_params` + """Unit tests for the `nova.api.openstack.common.get_pagination_params` method which takes in a request object and returns 'marker' and 'limit' GET params. """ diff --git a/nova/tests/compute/test_compute.py b/nova/tests/compute/test_compute.py index c1e762ff9629..207fe0711189 100644 --- a/nova/tests/compute/test_compute.py +++ b/nova/tests/compute/test_compute.py @@ -106,8 +106,7 @@ def fake_not_implemented(*args, **kwargs): def get_primitive_instance_by_uuid(context, instance_uuid): - """ - Helper method to get an instance and then convert it to + """Helper method to get an instance and then convert it to a primitive form using jsonutils. """ instance = db.instance_get_by_uuid(context, instance_uuid) @@ -1670,8 +1669,7 @@ class ComputeTestCase(BaseTestCase): self.assertEqual(len(bdms), 0) def test_run_terminate_no_image(self): - """ - Make sure instance started without image (from volume) + """Make sure instance started without image (from volume) can be termintad without issues """ params = {'image_ref': ''} @@ -2604,8 +2602,7 @@ class ComputeTestCase(BaseTestCase): self._objectify(inst_ref), [], []) def test_set_admin_password_driver_not_authorized(self): - """ - Ensure expected exception is raised if set_admin_password not + """Ensure expected exception is raised if set_admin_password not authorized. """ exc = exception.NotAuthorized(_('Internal error')) @@ -2616,8 +2613,7 @@ class ComputeTestCase(BaseTestCase): expected_exception) def test_set_admin_password_driver_not_implemented(self): - """ - Ensure expected exception is raised if set_admin_password not + """Ensure expected exception is raised if set_admin_password not implemented by driver. """ exc = NotImplementedError() @@ -4664,8 +4660,7 @@ class ComputeTestCase(BaseTestCase): def _test_finish_revert_resize(self, power_on, remove_old_vm_state=False): - """ - Convenience method that does most of the work for the + """Convenience method that does most of the work for the test_finish_revert_resize tests. :param power_on -- True if testing resize from ACTIVE state, False if testing resize from STOPPED state. @@ -9731,8 +9726,7 @@ class ComputePolicyTestCase(BaseTestCase): class DisabledInstanceTypesTestCase(BaseTestCase): - """ - Some instance-types are marked 'disabled' which means that they will not + """Some instance-types are marked 'disabled' which means that they will not show up in customer-facing listings. We do, however, want those instance-types to be available for emergency migrations and for rebuilding of existing instances. diff --git a/nova/tests/db/test_db_api.py b/nova/tests/db/test_db_api.py index f9552f8dcba4..761587b3606f 100644 --- a/nova/tests/db/test_db_api.py +++ b/nova/tests/db/test_db_api.py @@ -6386,9 +6386,7 @@ class ArchiveTestCase(test.TestCase): self.uuid_tablenames_to_cleanup.add(tablename) def _test_archive_deleted_rows_for_one_uuid_table(self, tablename): - """ - :returns: 0 on success, 1 if no uuid column, 2 if insert failed - """ + """:returns: 0 on success, 1 if no uuid column, 2 if insert failed.""" main_table = db_utils.get_table(self.engine, tablename) if not hasattr(main_table.c, "uuid"): # Not a uuid table, so skip it. diff --git a/nova/tests/db/test_migrations.py b/nova/tests/db/test_migrations.py index a0ff67537839..ae4578457ff8 100644 --- a/nova/tests/db/test_migrations.py +++ b/nova/tests/db/test_migrations.py @@ -64,8 +64,7 @@ LOG = logging.getLogger(__name__) def _get_connect_string(backend, user, passwd, database): - """ - Try to get a connection with a very specific set of values, if we get + """Try to get a connection with a very specific set of values, if we get these then we'll run the tests, otherwise they are skipped """ if backend == "postgres": @@ -154,8 +153,7 @@ class CommonTestsMixIn(object): self._test_mysql_opportunistically() def test_mysql_connect_fail(self): - """ - Test that we can trigger a mysql connection failure and we fail + """Test that we can trigger a mysql connection failure and we fail gracefully to ensure we don't break people without mysql """ if _is_backend_avail('mysql', "openstack_cifail", self.PASSWD, @@ -166,8 +164,7 @@ class CommonTestsMixIn(object): self._test_postgresql_opportunistically() def test_postgresql_connect_fail(self): - """ - Test that we can trigger a postgres connection failure and we fail + """Test that we can trigger a postgres connection failure and we fail gracefully to ensure we don't break people without postgres """ if _is_backend_avail('postgres', "openstack_cifail", self.PASSWD, diff --git a/nova/tests/image/test_glance.py b/nova/tests/image/test_glance.py index b550864cda69..abb69e10cfd2 100644 --- a/nova/tests/image/test_glance.py +++ b/nova/tests/image/test_glance.py @@ -88,8 +88,7 @@ class TestGlanceSerializer(test.NoDBTestCase): class TestGlanceImageService(test.NoDBTestCase): - """ - Tests the Glance image service. + """Tests the Glance image service. At a high level, the translations involved are: @@ -191,8 +190,7 @@ class TestGlanceImageService(test.NoDBTestCase): self.assertThat(image_metas[0], matchers.DictMatches(expected)) def test_create_without_instance_id(self): - """ - Ensure we can create an image without having to specify an + """Ensure we can create an image without having to specify an instance_id. Public images are an example of an image not tied to an instance. """ diff --git a/nova/tests/integrated/test_api_samples.py b/nova/tests/integrated/test_api_samples.py index 00f0c0be4218..63ad236d1cee 100644 --- a/nova/tests/integrated/test_api_samples.py +++ b/nova/tests/integrated/test_api_samples.py @@ -1690,8 +1690,7 @@ class ServicesJsonTest(ApiSampleTestBaseV2): self._verify_response('service-disable-put-resp', subs, response, 200) def test_service_detail(self): - """ - Return a list of all running services with the disable reason + """Return a list of all running services with the disable reason information if that exists. """ self.stubs.Set(extensions.ExtensionManager, "is_loaded", @@ -1725,8 +1724,7 @@ class ServicesXmlTest(ServicesJsonTest): class ExtendedServicesJsonTest(ApiSampleTestBaseV2): - """ - This extension is extending the functionalities of the + """This extension is extending the functionalities of the Services extension so the funcionalities introduced by this extension are tested in the ServicesJsonTest and ServicesXmlTest classes. """ @@ -1758,8 +1756,7 @@ class ExtendedServicesDeleteJsonTest(ApiSampleTestBaseV2): timeutils.clear_time_override() def test_service_detail(self, *mocks): - """ - Return a list of all running services with the disable reason + """Return a list of all running services with the disable reason information if that exists. """ response = self._do_get('os-services') diff --git a/nova/tests/matchers.py b/nova/tests/matchers.py index 6504fa6a8ab5..8107250d4c57 100644 --- a/nova/tests/matchers.py +++ b/nova/tests/matchers.py @@ -316,8 +316,7 @@ class XMLExpectedChild(XMLMismatch): class XMLMatchState(object): - """ - Maintain some state for matching. + """Maintain some state for matching. Tracks the XML node path and saves the expected and actual full XML text, for use by the XMLMismatch subclasses. @@ -339,8 +338,7 @@ class XMLMatchState(object): return '/' + '/'.join(self.path) def node(self, tag, idx): - """ - Adds tag and index to the path; they will be popped off when + """Adds tag and index to the path; they will be popped off when the corresponding 'with' statement exits. :param tag: The element tag diff --git a/nova/tests/test_flavors.py b/nova/tests/test_flavors.py index eb1d238d491f..cc8e8b6dd5f6 100644 --- a/nova/tests/test_flavors.py +++ b/nova/tests/test_flavors.py @@ -216,8 +216,7 @@ class InstanceTypeTestCase(test.TestCase): self.assertEqual(inst_type_name, deleted_inst_type["name"]) def test_read_deleted_false_converting_flavorid(self): - """ - Ensure deleted flavors are not returned when not needed (for + """Ensure deleted flavors are not returned when not needed (for example when creating a server and attempting to translate from flavorid to instance_type_id. """ diff --git a/nova/tests/virt/libvirt/test_libvirt.py b/nova/tests/virt/libvirt/test_libvirt.py index c1a100f556c0..bc600ddd9412 100644 --- a/nova/tests/virt/libvirt/test_libvirt.py +++ b/nova/tests/virt/libvirt/test_libvirt.py @@ -6209,9 +6209,7 @@ class LibvirtConnTestCase(test.TestCase): self.assertTrue(conn._is_storage_shared_with('foo', '/path')) def test_create_domain_define_xml_fails(self): - """ - Tests that the xml is logged when defining the domain fails. - """ + """Tests that the xml is logged when defining the domain fails.""" fake_xml = "this is a test" def fake_defineXML(xml): @@ -6234,8 +6232,8 @@ class LibvirtConnTestCase(test.TestCase): self.assertTrue(self.log_error_called) def test_create_domain_with_flags_fails(self): - """ - Tests that the xml is logged when creating the domain with flags fails. + """Tests that the xml is logged when creating the domain with flags + fails """ fake_xml = "this is a test" fake_domain = FakeVirtDomain(fake_xml) @@ -6261,9 +6259,8 @@ class LibvirtConnTestCase(test.TestCase): self.assertTrue(self.log_error_called) def test_create_domain_enable_hairpin_fails(self): - """ - Tests that the xml is logged when enabling hairpin mode for the domain - fails. + """Tests that the xml is logged when enabling hairpin mode for the + domain fails. """ utils.reset_is_neutron() fake_xml = "this is a test" @@ -6372,8 +6369,7 @@ class LibvirtConnTestCase(test.TestCase): conn.get_spice_console, self.context, instance) def _test_attach_detach_interface_get_config(self, method_name): - """ - Tests that the get_config() method is properly called in + """Tests that the get_config() method is properly called in attach_interface() and detach_interface(). method_name: either \"attach_interface\" or \"detach_interface\" @@ -6416,15 +6412,13 @@ class LibvirtConnTestCase(test.TestCase): raise ValueError("Unhandled method %" % method_name) def test_attach_interface_get_config(self): - """ - Tests that the get_config() method is properly called in + """Tests that the get_config() method is properly called in attach_interface(). """ self._test_attach_detach_interface_get_config("attach_interface") def test_detach_interface_get_config(self): - """ - Tests that the get_config() method is properly called in + """Tests that the get_config() method is properly called in detach_interface(). """ self._test_attach_detach_interface_get_config("detach_interface") diff --git a/nova/tests/virt/vmwareapi/test_driver_api.py b/nova/tests/virt/vmwareapi/test_driver_api.py index dc7f576c0d90..92b67e8c8187 100644 --- a/nova/tests/virt/vmwareapi/test_driver_api.py +++ b/nova/tests/virt/vmwareapi/test_driver_api.py @@ -389,8 +389,7 @@ class VMwareAPIVMTestCase(test.NoDBTestCase): self.assertIsNotNone(vm_util.vm_ref_cache_get(self.uuid)) def _check_vm_record(self, num_instances=1): - """ - Check if the spawned VM's properties correspond to the instance in + """Check if the spawned VM's properties correspond to the instance in the db. """ instances = self.conn.list_instances() @@ -436,8 +435,7 @@ class VMwareAPIVMTestCase(test.NoDBTestCase): self.assertTrue(found_iface_id) def _check_vm_info(self, info, pwr_state=power_state.RUNNING): - """ - Check if the get_info returned values correspond to the instance + """Check if the get_info returned values correspond to the instance object in the db. """ mem_kib = long(self.type_data['memory_mb']) << 10 @@ -1129,9 +1127,7 @@ class VMwareAPIVMTestCase(test.NoDBTestCase): None, None) def _test_finish_migration(self, power_on, resize_instance=False): - """ - Tests the finish_migration method on vmops - """ + """Tests the finish_migration method on vmops.""" self.power_on_called = False @@ -1178,9 +1174,7 @@ class VMwareAPIVMTestCase(test.NoDBTestCase): self.instance, None) def _test_finish_revert_migration(self, power_on): - """ - Tests the finish_revert_migration method on vmops - """ + """Tests the finish_revert_migration method on vmops.""" # setup the test instance in the database self._create_vm() diff --git a/nova/tests/virt/xenapi/test_xenapi.py b/nova/tests/virt/xenapi/test_xenapi.py index 05174548561e..d3cd12bde241 100644 --- a/nova/tests/virt/xenapi/test_xenapi.py +++ b/nova/tests/virt/xenapi/test_xenapi.py @@ -165,8 +165,7 @@ def get_fake_device_info(): def stub_vm_utils_with_vdi_attached_here(function): - """ - vm_utils.with_vdi_attached_here needs to be stubbed out because it + """vm_utils.with_vdi_attached_here needs to be stubbed out because it calls down to the filesystem to attach a vdi. This provides a decorator to handle that. """ diff --git a/nova/utils.py b/nova/utils.py index 65d99aa3f1ff..58754fc3813f 100644 --- a/nova/utils.py +++ b/nova/utils.py @@ -458,8 +458,7 @@ def check_isinstance(obj, cls): def parse_server_string(server_str): - """ - Parses the given server_string and returns a list of host and port. + """Parses the given server_string and returns a list of host and port. If it's not a combination of host part and port, the port element is a null string. If the input is invalid expression, return a null list. @@ -989,8 +988,7 @@ def spawn_n(func, *args, **kwargs): def is_none_string(val): - """ - Check if a string represents a None value. + """Check if a string represents a None value. """ if not isinstance(val, six.string_types): return False diff --git a/nova/virt/baremetal/tilera.py b/nova/virt/baremetal/tilera.py index 0a9bb9312174..a93e09056c1d 100644 --- a/nova/virt/baremetal/tilera.py +++ b/nova/virt/baremetal/tilera.py @@ -81,8 +81,7 @@ def get_partition_sizes(instance): def get_tftp_image_info(instance): - """ - Generate the paths for tftp files for this instance. + """Generate the paths for tftp files for this instance. Raises NovaException if - instance does not contain kernel_id @@ -297,8 +296,7 @@ class Tilera(base.NodeDriver): os.path.join(CONF.baremetal.tftp_root, instance['uuid'])) def _iptables_set(self, node_ip, user_data): - """ - Sets security setting (iptables:port) if needed. + """Sets security setting (iptables:port) if needed. iptables -A INPUT -p tcp ! -s $IP --dport $PORT -j DROP /tftpboot/iptables_rule script sets iptables rule on the given node. diff --git a/nova/virt/baremetal/tilera_pdu.py b/nova/virt/baremetal/tilera_pdu.py index 6c09d9ea4517..87d8435bf4d6 100644 --- a/nova/virt/baremetal/tilera_pdu.py +++ b/nova/virt/baremetal/tilera_pdu.py @@ -93,8 +93,7 @@ class Pdu(base.PowerManager): "to PDU")) def _exec_pdutool(self, mode): - """ - Changes power state of the given node. + """Changes power state of the given node. According to the mode (1-ON, 2-OFF, 3-REBOOT), power state can be changed. /tftpboot/pdu_mgr script handles power management of diff --git a/nova/virt/baremetal/volume_driver.py b/nova/virt/baremetal/volume_driver.py index 5c19fb2fca58..51ae1053b798 100644 --- a/nova/virt/baremetal/volume_driver.py +++ b/nova/virt/baremetal/volume_driver.py @@ -289,13 +289,9 @@ class LibvirtVolumeDriver(VolumeDriver): instance=instance) def get_all_block_devices(self): - """ - Return all block devices in use on this node. - """ + """Return all block devices in use on this node.""" return _list_backingstore_path() def get_hypervisor_version(self): - """ - A dummy method for LibvirtBaseVolumeDriver.connect_volume. - """ + """A dummy method for LibvirtBaseVolumeDriver.connect_volume.""" return 1 diff --git a/nova/virt/block_device.py b/nova/virt/block_device.py index 7814ba40116c..319a3682e68b 100644 --- a/nova/virt/block_device.py +++ b/nova/virt/block_device.py @@ -123,8 +123,7 @@ class DriverBlockDevice(dict): return dict((key, self.get(key)) for key in self._legacy_fields) def attach(self, **kwargs): - """ - Make the device available to be used by VMs. + """Make the device available to be used by VMs. To be overriden in subclasses with the connecting logic for the type of device the subclass represents. diff --git a/nova/virt/cpu.py b/nova/virt/cpu.py index 1935462730e0..855347913c5f 100644 --- a/nova/virt/cpu.py +++ b/nova/virt/cpu.py @@ -33,8 +33,7 @@ CONF.register_opts(virt_cpu_opts) def get_cpuset_ids(): - """ - Parsing vcpu_pin_set config. + """Parsing vcpu_pin_set config. Returns a list of pcpu ids can be used by instances. """ diff --git a/nova/virt/disk/vfs/guestfs.py b/nova/virt/disk/vfs/guestfs.py index 55f8d736c9ec..37486791fccf 100644 --- a/nova/virt/disk/vfs/guestfs.py +++ b/nova/virt/disk/vfs/guestfs.py @@ -28,8 +28,7 @@ guestfs = None class VFSGuestFS(vfs.VFS): - """ - This class implements a VFS module that uses the libguestfs APIs + """This class implements a VFS module that uses the libguestfs APIs to access the disk image. The disk image is never mapped into the host filesystem, thus avoiding any potential for symlink attacks from the guest filesystem. diff --git a/nova/virt/disk/vfs/localfs.py b/nova/virt/disk/vfs/localfs.py index cca6f88b0e93..e59d8daa33ff 100644 --- a/nova/virt/disk/vfs/localfs.py +++ b/nova/virt/disk/vfs/localfs.py @@ -29,8 +29,7 @@ LOG = logging.getLogger(__name__) class VFSLocalFS(vfs.VFS): - """ - os.path.join() with safety check for injected file paths. + """os.path.join() with safety check for injected file paths. Join the supplied path components and make sure that the resulting path we are injecting into is within the diff --git a/nova/virt/driver.py b/nova/virt/driver.py index 4c92faba437b..6de571722e2b 100644 --- a/nova/virt/driver.py +++ b/nova/virt/driver.py @@ -200,16 +200,14 @@ class ComputeDriver(object): return {'memory_mb': 0} def list_instances(self): - """ - Return the names of all the instances known to the virtualization + """Return the names of all the instances known to the virtualization layer, as a list. """ # TODO(Vek): Need to pass context in for access to auth_token raise NotImplementedError() def list_instance_uuids(self): - """ - Return the UUIDS of all the instances known to the virtualization + """Return the UUIDS of all the instances known to the virtualization layer, as a list. """ raise NotImplementedError() @@ -258,8 +256,7 @@ class ComputeDriver(object): def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): - """ - Create a new instance/VM/domain on the virtualization platform. + """Create a new instance/VM/domain on the virtualization platform. Once this successfully completes, the instance should be running (power_state.RUNNING). @@ -398,8 +395,7 @@ class ComputeDriver(object): raise NotImplementedError() def get_host_ip_addr(self): - """ - Retrieves the IP address of the dom0 + """Retrieves the IP address of the dom0 """ # TODO(Vek): Need to pass context in for access to auth_token raise NotImplementedError() @@ -439,8 +435,7 @@ class ComputeDriver(object): def migrate_disk_and_power_off(self, context, instance, dest, flavor, network_info, block_device_info=None): - """ - Transfers the disk of a running instance in multiple phases, turning + """Transfers the disk of a running instance in multiple phases, turning off the instance before the end. :param instance: nova.objects.instance.Instance @@ -448,8 +443,7 @@ class ComputeDriver(object): raise NotImplementedError() def snapshot(self, context, instance, image_id, update_task_state): - """ - Snapshots the specified instance. + """Snapshots the specified instance. :param context: security context :param instance: nova.objects.instance.Instance @@ -490,8 +484,7 @@ class ComputeDriver(object): def finish_revert_migration(self, context, instance, network_info, block_device_info=None, power_on=True): - """ - Finish reverting a resize. + """Finish reverting a resize. :param context: the context for the finish_revert_migration :param instance: nova.objects.instance.Instance being migrated/resized @@ -528,8 +521,7 @@ class ComputeDriver(object): raise NotImplementedError() def resume(self, context, instance, network_info, block_device_info=None): - """ - resume the specified instance. + """resume the specified instance. :param context: the context for the resume :param instance: nova.objects.instance.Instance being resumed @@ -862,8 +854,7 @@ class ComputeDriver(object): raise NotImplementedError() def set_admin_password(self, context, instance, new_pass=None): - """ - Set the root password on the specified instance. + """Set the root password on the specified instance. :param instance: nova.objects.instance.Instance :param new_password: the new password @@ -871,8 +862,7 @@ class ComputeDriver(object): raise NotImplementedError() def inject_file(self, instance, b64_path, b64_contents): - """ - Writes a file on the specified instance. + """Writes a file on the specified instance. The first parameter is an instance of nova.compute.service.Instance, and so the instance is being specified as instance.name. The second @@ -884,8 +874,7 @@ class ComputeDriver(object): raise NotImplementedError() def change_instance_metadata(self, context, instance, diff): - """ - Applies a diff to the instance metadata. + """Applies a diff to the instance metadata. This is an optional driver method which is used to publish changes to the instance's metadata to the hypervisor. If the @@ -983,8 +972,7 @@ class ComputeDriver(object): raise NotImplementedError() def block_stats(self, instance_name, disk_id): - """ - Return performance counters associated with the given disk_id on the + """Return performance counters associated with the given disk_id on the given instance_name. These are returned as [rd_req, rd_bytes, wr_req, wr_bytes, errs], where rd indicates read, wr indicates write, req is the total number of I/O requests made, bytes is the total number of @@ -1003,9 +991,8 @@ class ComputeDriver(object): raise NotImplementedError() def interface_stats(self, instance_name, iface_id): - """ - Return performance counters associated with the given iface_id on the - given instance_id. These are returned as [rx_bytes, rx_packets, + """Return performance counters associated with the given iface_id + on the given instance_id. These are returned as [rx_bytes, rx_packets, rx_errs, rx_drop, tx_bytes, tx_packets, tx_errs, tx_drop], where rx indicates receive, tx indicates transmit, bytes and packets indicate the total number of bytes or packets transferred, and errs and dropped @@ -1076,8 +1063,7 @@ class ComputeDriver(object): pass def manage_image_cache(self, context, all_instances): - """ - Manage the driver's local image cache. + """Manage the driver's local image cache. Some drivers chose to cache images for instances on disk. This method is an opportunity to do management of that cache which isn't directly @@ -1212,8 +1198,7 @@ class ComputeDriver(object): def volume_snapshot_create(self, context, instance, volume_id, create_info): - """ - Snapshots volumes attached to a specified instance. + """Snapshots volumes attached to a specified instance. :param context: request context :param instance: nova.objects.instance.Instance that has the volume @@ -1231,8 +1216,7 @@ class ComputeDriver(object): def volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info): - """ - Snapshots volumes attached to a specified instance. + """Snapshots volumes attached to a specified instance. :param context: request context :param instance: nova.objects.instance.Instance that has the volume diff --git a/nova/virt/hyperv/hostutils.py b/nova/virt/hyperv/hostutils.py index 0a9bfdcaf7a2..e7f453413240 100644 --- a/nova/virt/hyperv/hostutils.py +++ b/nova/virt/hyperv/hostutils.py @@ -44,8 +44,7 @@ class HostUtils(object): return ctypes.windll.kernel32.IsProcessorFeaturePresent(feature_key) def get_memory_info(self): - """ - Returns a tuple with total visible memory and free physical memory + """Returns a tuple with total visible memory and free physical memory expressed in kB. """ mem_info = self._conn_cimv2.query("SELECT TotalVisibleMemorySize, " @@ -55,8 +54,7 @@ class HostUtils(object): long(mem_info.FreePhysicalMemory)) def get_volume_info(self, drive): - """ - Returns a tuple with total size and free space + """Returns a tuple with total size and free space expressed in bytes. """ logical_disk = self._conn_cimv2.query("SELECT Size, FreeSpace " diff --git a/nova/virt/hyperv/volumeops.py b/nova/virt/hyperv/volumeops.py index 230f6debdf93..2965c34917ed 100644 --- a/nova/virt/hyperv/volumeops.py +++ b/nova/virt/hyperv/volumeops.py @@ -54,8 +54,7 @@ CONF.import_opt('my_ip', 'nova.netconf') class VolumeOps(object): - """ - Management class for Volume-related tasks + """Management class for Volume-related tasks """ def __init__(self): @@ -108,8 +107,7 @@ class VolumeOps(object): self._get_mounted_disk_from_lun(target_iqn, target_lun, True) def attach_volume(self, connection_info, instance_name, ebs_root=False): - """ - Attach a volume to the SCSI controller or to the IDE controller if + """Attach a volume to the SCSI controller or to the IDE controller if ebs_root is True """ target_iqn = None diff --git a/nova/virt/libvirt/driver.py b/nova/virt/libvirt/driver.py index 23d9bb13fb94..fd8fb11ec487 100644 --- a/nova/virt/libvirt/driver.py +++ b/nova/virt/libvirt/driver.py @@ -1796,8 +1796,7 @@ class LibvirtDriver(driver.ComputeDriver): def _volume_snapshot_delete(self, context, instance, volume_id, snapshot_id, delete_info=None): - """ - Note: + """Note: if file being merged into == active image: do a blockRebase (pull) operation else: @@ -3536,9 +3535,7 @@ class LibvirtDriver(driver.ComputeDriver): return domain def get_all_block_devices(self): - """ - Return all block devices in use on this node. - """ + """Return all block devices in use on this node.""" devices = [] for dom_id in self.list_instance_ids(): try: @@ -3559,8 +3556,7 @@ class LibvirtDriver(driver.ComputeDriver): return devices def get_disks(self, instance_name): - """ - Note that this function takes an instance name. + """Note that this function takes an instance name. Returns a list of all block devices for this domain. """ @@ -3577,8 +3573,7 @@ class LibvirtDriver(driver.ComputeDriver): for target in doc.findall('devices/disk/target')]) def get_interfaces(self, xml): - """ - Note that this function takes a domain xml. + """Note that this function takes a domain xml. Returns a list of all network interfaces for this instance. """ @@ -3952,9 +3947,7 @@ class LibvirtDriver(driver.ComputeDriver): return vol_usage def block_stats(self, instance_name, disk): - """ - Note that this function takes an instance name. - """ + """Note that this function takes an instance name.""" try: domain = self._lookup_by_name(instance_name) return domain.blockStats(disk) @@ -3970,9 +3963,7 @@ class LibvirtDriver(driver.ComputeDriver): 'Cannot get block stats for device'), instance_name) def interface_stats(self, instance_name, interface): - """ - Note that this function takes an instance name. - """ + """Note that this function takes an instance name.""" domain = self._lookup_by_name(instance_name) return domain.interfaceStats(interface) @@ -4450,16 +4441,15 @@ class LibvirtDriver(driver.ComputeDriver): def _create_images_and_backing(self, context, instance, instance_dir, disk_info_json): - """ - :param context: security context - :param instance: - nova.db.sqlalchemy.models.Instance object - instance object that is migrated. - :param instance_dir: - instance path to use, calculated externally to handle block - migrating an instance with an old style instance path - :param disk_info_json: - json strings specified in get_instance_disk_info + """:param context: security context + :param instance: + nova.db.sqlalchemy.models.Instance object + instance object that is migrated. + :param instance_dir: + instance path to use, calculated externally to handle block + migrating an instance with an old style instance path + :param disk_info_json: + json strings specified in get_instance_disk_info """ if not disk_info_json: diff --git a/nova/virt/libvirt/firewall.py b/nova/virt/libvirt/firewall.py index bbea588a65c1..24f5f8f96ac9 100644 --- a/nova/virt/libvirt/firewall.py +++ b/nova/virt/libvirt/firewall.py @@ -31,8 +31,7 @@ libvirt = None class NWFilterFirewall(base_firewall.FirewallDriver): - """ - This class implements a network filtering mechanism by using + """This class implements a network filtering mechanism by using libvirt's nwfilter. all instances get a filter ("nova-base") applied. This filter provides some basic security such as protection against MAC @@ -62,8 +61,7 @@ class NWFilterFirewall(base_firewall.FirewallDriver): @staticmethod def nova_no_nd_reflection_filter(): - """ - This filter protects false positives on IPv6 Duplicate Address + """This filter protects false positives on IPv6 Duplicate Address Detection(DAD). """ return ''' @@ -186,8 +184,7 @@ class NWFilterFirewall(base_firewall.FirewallDriver): return xml def get_base_filter_list(self, instance, allow_dhcp): - """ - Obtain a list of base filters to apply to an instance. + """Obtain a list of base filters to apply to an instance. The return value should be a list of strings, each specifying a filter name. Subclasses can override this function to add additional filters as needed. Additional diff --git a/nova/virt/libvirt/volume.py b/nova/virt/libvirt/volume.py index c380d5aa4618..d0b9b85e2d52 100644 --- a/nova/virt/libvirt/volume.py +++ b/nova/virt/libvirt/volume.py @@ -665,9 +665,8 @@ class LibvirtNFSVolumeDriver(LibvirtBaseVolumeDriver): return conf def _ensure_mounted(self, nfs_export, options=None): - """ - @type nfs_export: string - @type options: string + """@type nfs_export: string + @type options: string """ mount_path = os.path.join(CONF.libvirt.nfs_mount_point_base, utils.get_hash_str(nfs_export)) @@ -797,9 +796,8 @@ class LibvirtGlusterfsVolumeDriver(LibvirtBaseVolumeDriver): return conf def _ensure_mounted(self, glusterfs_export, options=None): - """ - @type glusterfs_export: string - @type options: string + """@type glusterfs_export: string + @type options: string """ mount_path = os.path.join(CONF.libvirt.glusterfs_mount_point_base, utils.get_hash_str(glusterfs_export)) diff --git a/nova/virt/vmwareapi/driver.py b/nova/virt/vmwareapi/driver.py index 0897b205cbba..e2dd02d774cf 100644 --- a/nova/virt/vmwareapi/driver.py +++ b/nova/virt/vmwareapi/driver.py @@ -392,8 +392,7 @@ class VMwareVCDriver(VMwareESXDriver): def migrate_disk_and_power_off(self, context, instance, dest, flavor, network_info, block_device_info=None): - """ - Transfers the disk of a running instance in multiple phases, turning + """Transfers the disk of a running instance in multiple phases, turning off the instance before the end. """ _vmops = self._get_vmops_for_compute_node(instance['node']) @@ -690,8 +689,7 @@ class VMwareVCDriver(VMwareESXDriver): class VMwareAPISession(object): - """ - Sets up a session with the VC/ESX host and handles all + """Sets up a session with the VC/ESX host and handles all the calls made to the host. """ @@ -771,8 +769,7 @@ class VMwareAPISession(object): return active def _call_method(self, module, method, *args, **kwargs): - """ - Calls a method within the module specified with + """Calls a method within the module specified with args provided. """ args = list(args) @@ -868,8 +865,7 @@ class VMwareAPISession(object): loop.stop() def _wait_for_task(self, task_ref): - """ - Return a Deferred that will give the result of the given task. + """Return a Deferred that will give the result of the given task. The task is polled until it completes. """ done = event.Event() @@ -885,8 +881,7 @@ class VMwareAPISession(object): return ret_val def _poll_task(self, task_ref, done): - """ - Poll the given task, and fires the given Deferred if we + """Poll the given task, and fires the given Deferred if we get a result. """ try: diff --git a/nova/virt/vmwareapi/error_util.py b/nova/virt/vmwareapi/error_util.py index 831f229a7a71..44aab09f9b41 100644 --- a/nova/virt/vmwareapi/error_util.py +++ b/nova/virt/vmwareapi/error_util.py @@ -73,16 +73,14 @@ class VimFaultException(Exception): class FaultCheckers(object): - """ - Methods for fault checking of SOAP response. Per Method error handlers + """Methods for fault checking of SOAP response. Per Method error handlers for which we desire error checking are defined. SOAP faults are embedded in the SOAP messages as properties and not as SOAP faults. """ @staticmethod def retrievepropertiesex_fault_checker(resp_obj): - """ - Checks the RetrievePropertiesEx response for errors. Certain faults + """Checks the RetrievePropertiesEx response for errors. Certain faults are sent as part of the SOAP body as property of missingSet. For example NotAuthenticated fault. """ diff --git a/nova/virt/vmwareapi/fake.py b/nova/virt/vmwareapi/fake.py index 5a452823713a..c8e1f96cb6b0 100644 --- a/nova/virt/vmwareapi/fake.py +++ b/nova/virt/vmwareapi/fake.py @@ -208,16 +208,14 @@ class ManagedObject(object): self.mo_id)) def set(self, attr, val): - """ - Sets an attribute value. Not using the __setattr__ directly for we + """Sets an attribute value. Not using the __setattr__ directly for we want to set attributes of the type 'a.b.c' and using this function class we set the same. """ self.__setattr__(attr, val) def get(self, attr): - """ - Gets an attribute. Used as an intermediary to get nested + """Gets an attribute. Used as an intermediary to get nested property like 'a.b.c' value. """ return self.__getattr__(attr) @@ -265,9 +263,7 @@ class DataObject(object): class HostInternetScsiHba(DataObject): - """ - iSCSI Host Bus Adapter - """ + """iSCSI Host Bus Adapter""" def __init__(self): super(HostInternetScsiHba, self).__init__() @@ -316,9 +312,7 @@ class FileLocked(DataObject): class VirtualDisk(DataObject): - """ - Virtual Disk class. - """ + """Virtual Disk class.""" def __init__(self, controllerKey=0, unitNumber=0): super(VirtualDisk, self).__init__() @@ -433,8 +427,7 @@ class VirtualMachine(ManagedObject): self.set("summary.runtime", runtime) def reconfig(self, factory, val): - """ - Called to reconfigure the VM. Actually customizes the property + """Called to reconfigure the VM. Actually customizes the property setting of the Virtual Machine object. """ try: @@ -956,8 +949,7 @@ class FakeVim(object): """Fake VIM Class.""" def __init__(self, protocol="https", host="localhost", trace=None): - """ - Initializes the suds client object, sets the service content + """Initializes the suds client object, sets the service content contents and the cookies for the session. """ self._session = None diff --git a/nova/virt/vmwareapi/host.py b/nova/virt/vmwareapi/host.py index ca9e066906e6..015b43b7d0f0 100644 --- a/nova/virt/vmwareapi/host.py +++ b/nova/virt/vmwareapi/host.py @@ -29,9 +29,7 @@ LOG = logging.getLogger(__name__) class Host(object): - """ - Implements host related operations. - """ + """Implements host related operations.""" def __init__(self, session): self._session = session diff --git a/nova/virt/vmwareapi/network_util.py b/nova/virt/vmwareapi/network_util.py index 502e3f390a6a..bec420ee2465 100644 --- a/nova/virt/vmwareapi/network_util.py +++ b/nova/virt/vmwareapi/network_util.py @@ -29,8 +29,7 @@ LOG = logging.getLogger(__name__) def get_network_with_the_name(session, network_name="vmnet0", cluster=None): - """ - Gets reference to the network whose name is passed as the + """Gets reference to the network whose name is passed as the argument. """ host = vm_util.get_host_ref(session, cluster) @@ -80,8 +79,7 @@ def get_network_with_the_name(session, network_name="vmnet0", cluster=None): def get_vswitch_for_vlan_interface(session, vlan_interface, cluster=None): - """ - Gets the vswitch associated with the physical network adapter + """Gets the vswitch associated with the physical network adapter with the name supplied. """ # Get the list of vSwicthes on the Host System @@ -141,8 +139,7 @@ def get_vlanid_and_vswitch_for_portgroup(session, pg_name, cluster=None): def create_port_group(session, pg_name, vswitch_name, vlan_id=0, cluster=None): - """ - Creates a port group on the host system with the vlan tags + """Creates a port group on the host system with the vlan tags supplied. VLAN id 0 means no vlan id association. """ client_factory = session._get_vim().client.factory diff --git a/nova/virt/vmwareapi/vim.py b/nova/virt/vmwareapi/vim.py index 9ec0cc85f00a..7aa235b36ac9 100644 --- a/nova/virt/vmwareapi/vim.py +++ b/nova/virt/vmwareapi/vim.py @@ -99,8 +99,7 @@ class Vim: def __init__(self, protocol="https", host="localhost"): - """ - Creates the necessary Communication interfaces and gets the + """Creates the necessary Communication interfaces and gets the ServiceContent for initiating SOAP transactions. protocol: http or https @@ -122,8 +121,7 @@ class Vim: @staticmethod def get_wsdl_url(protocol, host_name): - """ - allows override of the wsdl location, making this static + """Allows override of the wsdl location, making this static means we can test the logic outside of the constructor without forcing the test environment to have multiple valid wsdl locations to test against. @@ -141,8 +139,7 @@ class Vim: @staticmethod def get_soap_url(protocol, host_name): - """ - Calculates the location of the SOAP services + """Calculates the location of the SOAP services for a particular server. Created as a static method for testing. @@ -161,8 +158,7 @@ class Vim: def __getattr__(self, attr_name): """Makes the API calls and gets the result.""" def vim_request_handler(managed_object, **kwargs): - """ - Builds the SOAP message and parses the response for fault + """Builds the SOAP message and parses the response for fault checking and other errors. managed_object : Managed Object Reference or Managed diff --git a/nova/virt/vmwareapi/vim_util.py b/nova/virt/vmwareapi/vim_util.py index 1ac52d3251b1..c6eb58d3b2b8 100644 --- a/nova/virt/vmwareapi/vim_util.py +++ b/nova/virt/vmwareapi/vim_util.py @@ -57,8 +57,7 @@ def build_traversal_spec(client_factory, name, spec_type, path, skip, def build_recursive_traversal_spec(client_factory): - """ - Builds the Recursive Traversal Spec to traverse the object managed + """Builds the Recursive Traversal Spec to traverse the object managed object hierarchy. """ visit_folders_select_spec = build_selection_spec(client_factory, @@ -258,8 +257,7 @@ def get_prop_filter_spec(client_factory, obj_spec, prop_spec): def get_properties_for_a_collection_of_objects(vim, type, obj_list, properties): - """ - Gets the list of properties for the collection of + """Gets the list of properties for the collection of objects of the type specified. """ client_factory = vim.client.factory diff --git a/nova/virt/vmwareapi/vm_util.py b/nova/virt/vmwareapi/vm_util.py index ba341c9b61eb..77634cb7582d 100644 --- a/nova/virt/vmwareapi/vm_util.py +++ b/nova/virt/vmwareapi/vm_util.py @@ -91,8 +91,7 @@ def build_datastore_path(datastore_name, path): def split_datastore_path(datastore_path): - """ - Split the VMware style datastore path to get the Datastore + """Split the VMware style datastore path to get the Datastore name and the entity path. """ spl = datastore_path.split('[', 1)[1].split(']', 1) @@ -173,8 +172,7 @@ def get_vm_resize_spec(client_factory, instance): def create_controller_spec(client_factory, key, adapter_type="lsiLogic"): - """ - Builds a Config Spec for the LSI or Bus Logic Controller's addition + """Builds a Config Spec for the LSI or Bus Logic Controller's addition which acts as the controller for the virtual hard disk to be attached to the VM. """ @@ -199,8 +197,7 @@ def create_controller_spec(client_factory, key, adapter_type="lsiLogic"): def create_network_spec(client_factory, vif_info): - """ - Builds a config spec for the addition of a new network + """Builds a config spec for the addition of a new network adapter to the VM. """ network_spec = client_factory.create('ns0:VirtualDeviceConfigSpec') @@ -393,8 +390,7 @@ def _is_scsi_controller(device): def _find_allocated_slots(devices): - """ - Return dictionary which maps controller_key to list of allocated unit + """Return dictionary which maps controller_key to list of allocated unit numbers for that controller_key. """ taken = {} @@ -411,8 +407,7 @@ def _find_allocated_slots(devices): def allocate_controller_key_and_unit_number(client_factory, devices, adapter_type): - """ - This function inspects the current set of hardware devices and returns + """This function inspects the current set of hardware devices and returns controller_key and unit_number that can be used for attaching a new virtual disk to adapter with the given adapter_type. """ @@ -520,8 +515,7 @@ def create_virtual_disk_spec(client_factory, controller_key, linked_clone=False, unit_number=None, device_name=None): - """ - Builds spec for the creation of a new/ attaching of an already existing + """Builds spec for the creation of a new/ attaching of an already existing Virtual Disk to the VM. """ virtual_device_config = client_factory.create( @@ -577,8 +571,7 @@ def create_virtual_disk_spec(client_factory, controller_key, def detach_virtual_disk_spec(client_factory, device, destroy_disk=False): - """ - Builds spec for the detach of an already existing Virtual Disk from VM. + """Builds spec for the detach of an already existing Virtual Disk from VM. """ virtual_device_config = client_factory.create( 'ns0:VirtualDeviceConfigSpec') @@ -871,8 +864,7 @@ def get_host_ref_from_id(session, host_id, property_list=None): def get_host_id_from_vm_ref(session, vm_ref): - """ - This method allows you to find the managed object + """This method allows you to find the managed object ID of the host running a VM. Since vMotion can change the value, you should not presume that this is a value that you can cache for very long and @@ -909,8 +901,7 @@ def get_host_id_from_vm_ref(session, vm_ref): def property_from_property_set(property_name, property_set): - ''' - Use this method to filter property collector results. + '''Use this method to filter property collector results. Because network traffic is expensive, multiple VMwareAPI calls will sometimes pile-up properties diff --git a/nova/virt/vmwareapi/vmops.py b/nova/virt/vmwareapi/vmops.py index 2d64602a42e6..52120768d98c 100644 --- a/nova/virt/vmwareapi/vmops.py +++ b/nova/virt/vmwareapi/vmops.py @@ -182,8 +182,7 @@ class VMwareVMOps(object): def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info, block_device_info=None, instance_name=None, power_on=True): - """ - Creates a VM instance. + """Creates a VM instance. Steps followed are: @@ -224,8 +223,7 @@ class VMwareVMOps(object): # hard to maintain file. At some future date, refactor this method to # be a full-fledged method. This will also make unit testing easier. def _get_image_properties(root_size): - """ - Get the Size of the flat vmdk file that is there on the storage + """Get the Size of the flat vmdk file that is there on the storage repository. """ image_ref = instance.get('image_ref') @@ -888,8 +886,7 @@ class VMwareVMOps(object): _upload_vmdk_to_image_repository() def _clean_temp_data(): - """ - Delete temporary vmdk files generated in image handling + """Delete temporary vmdk files generated in image handling operations. """ # The data file is the one occupying space, and likelier to see @@ -955,8 +952,7 @@ class VMwareVMOps(object): LOG.debug(_("Did hard reboot of VM"), instance=instance) def _delete(self, instance, network_info): - """ - Destroy a VM instance. Steps followed are: + """Destroy a VM instance. Steps followed are: 1. Power off the VM, if it is in poweredOn state. 2. Destroy the VM. """ @@ -978,8 +974,7 @@ class VMwareVMOps(object): def destroy(self, instance, network_info, destroy_disks=True, instance_name=None): - """ - Destroy a VM instance. Steps followed are: + """Destroy a VM instance. Steps followed are: 1. Power off the VM, if it is in poweredOn state. 2. Un-register a VM. 3. Delete the contents of the folder holding the VM related data. @@ -1230,8 +1225,7 @@ class VMwareVMOps(object): def migrate_disk_and_power_off(self, context, instance, dest, flavor): - """ - Transfers the disk of a running instance in multiple phases, turning + """Transfers the disk of a running instance in multiple phases, turning off the instance before the end. """ # 0. Zero out the progress to begin @@ -1504,9 +1498,8 @@ class VMwareVMOps(object): return machine_id_str def _set_machine_id(self, client_factory, instance, network_info): - """ - Set the machine id of the VM for guest tools to pick up and reconfigure - the network interfaces. + """Set the machine id of the VM for guest tools to pick up + and reconfigure the network interfaces. """ vm_ref = vm_util.get_vm_ref(self._session, instance) @@ -1524,9 +1517,7 @@ class VMwareVMOps(object): instance=instance) def _set_vnc_config(self, client_factory, instance, port): - """ - Set the vnc configuration of the VM. - """ + """Set the vnc configuration of the VM.""" vm_ref = vm_util.get_vm_ref(self._session, instance) vnc_config_spec = vm_util.get_vnc_config_spec( @@ -1623,8 +1614,7 @@ class VMwareVMOps(object): return file_exists def _mkdir(self, ds_path, ds_ref): - """ - Creates a directory at the path specified. If it is just "NAME", + """Creates a directory at the path specified. If it is just "NAME", then a directory with this name is created at the topmost level of the DataStore. """ diff --git a/nova/virt/vmwareapi/vmware_images.py b/nova/virt/vmwareapi/vmware_images.py index d36a0a64ecc6..2ae050ce22da 100644 --- a/nova/virt/vmwareapi/vmware_images.py +++ b/nova/virt/vmwareapi/vmware_images.py @@ -172,8 +172,7 @@ def upload_image(context, image, instance, **kwargs): def get_vmdk_size_and_properties(context, image, instance): - """ - Get size of the vmdk file that is to be downloaded for attach in spawn. + """Get size of the vmdk file that is to be downloaded for attach in spawn. Need this to create the dummy virtual disk for the meta-data file. The geometry of the disk created depends on the size. """ diff --git a/nova/virt/vmwareapi/volume_util.py b/nova/virt/vmwareapi/volume_util.py index 4ae92f5593ac..f0b689e29ae8 100644 --- a/nova/virt/vmwareapi/volume_util.py +++ b/nova/virt/vmwareapi/volume_util.py @@ -33,9 +33,7 @@ class StorageError(Exception): def get_host_iqn(session, cluster=None): - """ - Return the host iSCSI IQN. - """ + """Return the host iSCSI IQN.""" host_mor = vm_util.get_host_ref(session, cluster) hbas_ret = session._call_method(vim_util, "get_dynamic_property", host_mor, "HostSystem", @@ -53,9 +51,7 @@ def get_host_iqn(session, cluster=None): def find_st(session, data, cluster=None): - """ - Return the iSCSI Target given a volume info. - """ + """Return the iSCSI Target given a volume info.""" target_portal = data['target_portal'] target_iqn = data['target_iqn'] host_mor = vm_util.get_host_ref(session, cluster) @@ -126,9 +122,7 @@ def find_st(session, data, cluster=None): def rescan_iscsi_hba(session, cluster=None): - """ - Rescan the iSCSI HBA to discover iSCSI targets. - """ + """Rescan the iSCSI HBA to discover iSCSI targets.""" host_mor = vm_util.get_host_ref(session, cluster) storage_system_mor = session._call_method(vim_util, "get_dynamic_property", host_mor, "HostSystem", diff --git a/nova/virt/vmwareapi/volumeops.py b/nova/virt/vmwareapi/volumeops.py index abf391fcb3d7..315376cb96c1 100644 --- a/nova/virt/vmwareapi/volumeops.py +++ b/nova/virt/vmwareapi/volumeops.py @@ -32,9 +32,7 @@ LOG = logging.getLogger(__name__) class VMwareVolumeOps(object): - """ - Management class for Volume-related tasks - """ + """Management class for Volume-related tasks.""" def __init__(self, session, cluster=None, vc_support=False): self._session = session @@ -45,9 +43,7 @@ class VMwareVolumeOps(object): adapter_type, disk_type, vmdk_path=None, disk_size=None, linked_clone=False, device_name=None): - """ - Attach disk to VM by reconfiguration. - """ + """Attach disk to VM by reconfiguration.""" instance_name = instance['name'] client_factory = self._session._get_vim().client.factory devices = self._session._call_method(vim_util, @@ -117,9 +113,7 @@ class VMwareVolumeOps(object): def detach_disk_from_vm(self, vm_ref, instance, device, destroy_disk=False): - """ - Detach disk from VM by reconfiguration. - """ + """Detach disk from VM by reconfiguration.""" instance_name = instance['name'] client_factory = self._session._get_vim().client.factory vmdk_detach_config_spec = vm_util.get_vmdk_detach_config_spec( diff --git a/nova/virt/xenapi/agent.py b/nova/virt/xenapi/agent.py index 2b4495dfe6ea..6c95b17997b1 100644 --- a/nova/virt/xenapi/agent.py +++ b/nova/virt/xenapi/agent.py @@ -367,8 +367,7 @@ class XenAPIBasedAgent(object): def find_guest_agent(base_dir): - """ - tries to locate a guest agent at the path + """tries to locate a guest agent at the path specified by agent_rel_path """ if CONF.xenserver.disable_agent: @@ -415,8 +414,7 @@ def should_use_agent(instance): class SimpleDH(object): - """ - This class wraps all the functionality needed to implement + """This class wraps all the functionality needed to implement basic Diffie-Hellman-Merkle key exchange in Python. It features intelligent defaults for the prime and base numbers needed for the calculation, while allowing you to supply your own. It requires that diff --git a/nova/virt/xenapi/fake.py b/nova/virt/xenapi/fake.py index 9508f92d2b30..e852bfd4448b 100644 --- a/nova/virt/xenapi/fake.py +++ b/nova/virt/xenapi/fake.py @@ -468,9 +468,7 @@ class Failure(Exception): class SessionBase(object): - """ - Base class for Fake Sessions - """ + """Base class for Fake Sessions.""" def __init__(self, uri): self._session = None diff --git a/nova/virt/xenapi/host.py b/nova/virt/xenapi/host.py index 1a5db26711b8..f06bee1fbbe1 100644 --- a/nova/virt/xenapi/host.py +++ b/nova/virt/xenapi/host.py @@ -37,9 +37,7 @@ LOG = logging.getLogger(__name__) class Host(object): - """ - Implements host related operations. - """ + """Implements host related operations.""" def __init__(self, session, virtapi): self._session = session self._virtapi = virtapi @@ -166,15 +164,13 @@ class HostState(object): :returns: a list of pci devices available for pci passthrough. """ def _compile_hex(pattern): - """ - Return a compiled regular expression pattern into which we have + """Return a compiled regular expression pattern into which we have replaced occurrences of hex by [\da-fA-F]. """ return re.compile(pattern.replace("hex", r"[\da-fA-F]")) def _parse_pci_device_string(dev_string): - """ - Exctract information from the device string about the slot, the + """Exctract information from the device string about the slot, the vendor and the product ID. The string is as follow: "Slot:\tBDF\nClass:\txxxx\nVendor:\txxxx\nDevice:\txxxx\n..." Return a dictionary with informations about the device. diff --git a/nova/virt/xenapi/network_utils.py b/nova/virt/xenapi/network_utils.py index 2dcb43883230..772017cbdf68 100644 --- a/nova/virt/xenapi/network_utils.py +++ b/nova/virt/xenapi/network_utils.py @@ -33,8 +33,7 @@ def find_network_with_name_label(session, name_label): def find_network_with_bridge(session, bridge): - """ - Return the network on which the bridge is attached, if found. + """Return the network on which the bridge is attached, if found. The bridge is defined in the nova db and can be found either in the 'bridge' or 'name_label' fields of the XenAPI network record. """ diff --git a/nova/virt/xenapi/pool.py b/nova/virt/xenapi/pool.py index cde596bfd155..723cd50e08bc 100644 --- a/nova/virt/xenapi/pool.py +++ b/nova/virt/xenapi/pool.py @@ -45,9 +45,7 @@ CONF.import_opt('host', 'nova.netconf') class ResourcePool(object): - """ - Implements resource pool operations. - """ + """Implements resource pool operations.""" def __init__(self, session, virtapi): host_rec = session.call_xenapi('host.get_record', session.host_ref) self._host_name = host_rec['hostname'] diff --git a/nova/virt/xenapi/vm_utils.py b/nova/virt/xenapi/vm_utils.py index a30c13131321..b72604b65c2c 100644 --- a/nova/virt/xenapi/vm_utils.py +++ b/nova/virt/xenapi/vm_utils.py @@ -1072,8 +1072,7 @@ def _make_partition(session, dev, partition_start, partition_end): def _generate_disk(session, instance, vm_ref, userdevice, name_label, disk_type, size_mb, fs_type): - """ - Steps to programmatically generate a disk: + """Steps to programmatically generate a disk: 1. Create VDI of desired size @@ -2466,8 +2465,7 @@ def _mounted_processing(device, key, net, metadata): def _prepare_injectables(inst, network_info): - """ - prepares the ssh key and the network configuration file to be + """prepares the ssh key and the network configuration file to be injected into the disk image """ #do the import here - Jinja2 will be loaded only if injection is performed diff --git a/nova/virt/xenapi/vmops.py b/nova/virt/xenapi/vmops.py index 7438e095eb85..9aaaeb4e499c 100644 --- a/nova/virt/xenapi/vmops.py +++ b/nova/virt/xenapi/vmops.py @@ -153,9 +153,7 @@ def make_step_decorator(context, instance, update_instance_progress, class VMOps(object): - """ - Management class for VM-related tasks - """ + """Management class for VM-related tasks.""" def __init__(self, session, virtapi): self.compute_api = compute.API() self._session = session @@ -1153,8 +1151,7 @@ class VMOps(object): @staticmethod def _sanitize_xenstore_key(key): - """ - Xenstore only allows the following characters as keys: + """Xenstore only allows the following characters as keys: ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz @@ -1638,8 +1635,7 @@ class VMOps(object): return info_dict def inject_network_info(self, instance, network_info, vm_ref=None): - """ - Generate the network info and make calls to place it into the + """Generate the network info and make calls to place it into the xenstore and the xenstore param list. vm_ref can be passed in because it will sometimes be different than what vm_utils.lookup(session, instance['name']) will find (ex: rescue) @@ -1734,8 +1730,7 @@ class VMOps(object): update_hostname() def _write_to_xenstore(self, instance, path, value, vm_ref=None): - """ - Writes the passed value to the xenstore record for the given VM + """Writes the passed value to the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the write process. """ @@ -1744,8 +1739,7 @@ class VMOps(object): value=jsonutils.dumps(value)) def _delete_from_xenstore(self, instance, path, vm_ref=None): - """ - Deletes the value from the xenstore record for the given VM at + """Deletes the value from the xenstore record for the given VM at the specified location. A XenAPIPlugin.PluginError will be raised if any error is encountered in the delete process. """ @@ -1754,8 +1748,7 @@ class VMOps(object): def _make_plugin_call(self, plugin, method, instance=None, vm_ref=None, **addl_args): - """ - Abstracts out the process of calling a method of a xenapi plugin. + """Abstracts out the process of calling a method of a xenapi plugin. Any errors raised by the plugin will in turn raise a RuntimeError here. """ args = {} @@ -1791,8 +1784,7 @@ class VMOps(object): return domid def _add_to_param_xenstore(self, vm_ref, key, val): - """ - Takes a key/value pair and adds it to the xenstore parameter + """Takes a key/value pair and adds it to the xenstore parameter record for the given vm instance. If the key exists in xenstore, it is overwritten """ @@ -1800,8 +1792,7 @@ class VMOps(object): self._session.call_xenapi('VM.add_to_xenstore_data', vm_ref, key, val) def _remove_from_param_xenstore(self, vm_ref, key): - """ - Takes a single key and removes it from the xenstore parameter + """Takes a single key and removes it from the xenstore parameter record data for the given VM. If the key doesn't exist, the request is ignored. """ diff --git a/nova/virt/xenapi/volume_utils.py b/nova/virt/xenapi/volume_utils.py index a884b29dbd7b..bc88f0b8efb9 100644 --- a/nova/virt/xenapi/volume_utils.py +++ b/nova/virt/xenapi/volume_utils.py @@ -86,18 +86,14 @@ def introduce_sr(session, sr_uuid, label, params): def forget_sr(session, sr_ref): - """ - Forgets the storage repository without destroying the VDIs within - """ + """Forgets the storage repository without destroying the VDIs within.""" LOG.debug(_('Forgetting SR...')) unplug_pbds(session, sr_ref) session.call_xenapi("SR.forget", sr_ref) def find_sr_by_uuid(session, sr_uuid): - """ - Return the storage repository given a uuid. - """ + """Return the storage repository given a uuid.""" try: return session.call_xenapi("SR.get_by_uuid", sr_uuid) except session.XenAPI.Failure as exc: @@ -249,8 +245,7 @@ def parse_sr_info(connection_data, description=''): def parse_volume_info(connection_data): - """ - Parse device_path and mountpoint as they can be used by XenAPI. + """Parse device_path and mountpoint as they can be used by XenAPI. In particular, the mountpoint (e.g. /dev/sdc) must be translated into a numeric literal. """ diff --git a/nova/virt/xenapi/volumeops.py b/nova/virt/xenapi/volumeops.py index 38d9539406df..bf50c78e2551 100644 --- a/nova/virt/xenapi/volumeops.py +++ b/nova/virt/xenapi/volumeops.py @@ -29,18 +29,14 @@ LOG = logging.getLogger(__name__) class VolumeOps(object): - """ - Management class for Volume-related tasks - """ + """Management class for Volume-related tasks.""" def __init__(self, session): self._session = session def attach_volume(self, connection_info, instance_name, mountpoint, hotplug=True): - """ - Attach volume storage to VM instance. - """ + """Attach volume storage to VM instance.""" # NOTE: No Resource Pool concept so far LOG.debug(_('Attach_volume: %(connection_info)s, %(instance_name)s,' @@ -63,8 +59,7 @@ class VolumeOps(object): return (sr_uuid, vdi_uuid) def connect_volume(self, connection_info): - """ - Attach volume storage to the hypervisor without attaching to a VM + """Attach volume storage to the hypervisor without attaching to a VM Used to attach the just the SR - e.g. for during live migration """ diff --git a/plugins/xenserver/xenapi/etc/xapi.d/plugins/utils.py b/plugins/xenserver/xenapi/etc/xapi.d/plugins/utils.py index 0d1f4a2fd942..55b6dece994d 100644 --- a/plugins/xenserver/xenapi/etc/xapi.d/plugins/utils.py +++ b/plugins/xenserver/xenapi/etc/xapi.d/plugins/utils.py @@ -118,8 +118,7 @@ def run_command(cmd, cmd_input=None, ok_exit_codes=None): def make_staging_area(sr_path): - """ - The staging area is a place where we can temporarily store and + """The staging area is a place where we can temporarily store and manipulate VHDs. The use of the staging area is different for upload and download: @@ -205,8 +204,7 @@ def _assert_vhd_not_hidden(path): def _validate_vhd(vdi_path): - """ - This checks for several errors in the VHD structure. + """This checks for several errors in the VHD structure. Most notably, it checks that the timestamp in the footer is correct, but may pick up other errors also. @@ -248,8 +246,7 @@ def _validate_vhd(vdi_path): def _validate_vdi_chain(vdi_path): - """ - This check ensures that the parent pointers on the VHDs are valid + """This check ensures that the parent pointers on the VHDs are valid before we move the VDI chain to the SR. This is *very* important because a bad parent pointer will corrupt the SR causing a cascade of failures. diff --git a/tox.ini b/tox.ini index f4f19cb5f9b8..09522903c340 100644 --- a/tox.ini +++ b/tox.ini @@ -45,7 +45,7 @@ commands = {posargs} # E125 is deliberately excluded. See https://github.com/jcrocholl/pep8/issues/126 # The rest of the ignores are TODOs -ignore = E121,E122,E123,E124,E125,E126,E127,E128,E711,E712,H404,F811,F841,H803 +ignore = E121,E122,E123,E124,E125,E126,E127,E128,E711,E712,F811,F841,H803 exclude = .venv,.git,.tox,dist,doc,*openstack/common*,*lib/python*,*egg,build,tools [hacking]