summaryrefslogtreecommitdiff
path: root/openstackclient/compute/v2
diff options
context:
space:
mode:
Diffstat (limited to 'openstackclient/compute/v2')
-rw-r--r--openstackclient/compute/v2/agent.py81
-rw-r--r--openstackclient/compute/v2/aggregate.py148
-rw-r--r--openstackclient/compute/v2/console.py34
-rw-r--r--openstackclient/compute/v2/flavor.py210
-rw-r--r--openstackclient/compute/v2/host.py62
-rw-r--r--openstackclient/compute/v2/hypervisor.py111
-rw-r--r--openstackclient/compute/v2/hypervisor_stats.py18
-rw-r--r--openstackclient/compute/v2/keypair.py73
-rw-r--r--openstackclient/compute/v2/server.py599
-rw-r--r--openstackclient/compute/v2/server_backup.py1
-rw-r--r--openstackclient/compute/v2/server_event.py11
-rw-r--r--openstackclient/compute/v2/server_group.py13
-rw-r--r--openstackclient/compute/v2/server_image.py7
-rw-r--r--openstackclient/compute/v2/server_migration.py79
-rw-r--r--openstackclient/compute/v2/service.py152
-rw-r--r--openstackclient/compute/v2/usage.py90
16 files changed, 943 insertions, 746 deletions
diff --git a/openstackclient/compute/v2/agent.py b/openstackclient/compute/v2/agent.py
index 15fb0f9c..9b07df6e 100644
--- a/openstackclient/compute/v2/agent.py
+++ b/openstackclient/compute/v2/agent.py
@@ -37,36 +37,20 @@ class CreateAgent(command.ShowOne):
def get_parser(self, prog_name):
parser = super(CreateAgent, self).get_parser(prog_name)
- parser.add_argument(
- "os",
- metavar="<os>",
- help=_("Type of OS")
- )
+ parser.add_argument("os", metavar="<os>", help=_("Type of OS"))
parser.add_argument(
"architecture",
metavar="<architecture>",
- help=_("Type of architecture")
- )
- parser.add_argument(
- "version",
- metavar="<version>",
- help=_("Version")
- )
- parser.add_argument(
- "url",
- metavar="<url>",
- help=_("URL")
- )
- parser.add_argument(
- "md5hash",
- metavar="<md5hash>",
- help=_("MD5 hash")
+ help=_("Type of architecture"),
)
+ parser.add_argument("version", metavar="<version>", help=_("Version"))
+ parser.add_argument("url", metavar="<url>", help=_("URL"))
+ parser.add_argument("md5hash", metavar="<md5hash>", help=_("MD5 hash"))
parser.add_argument(
"hypervisor",
metavar="<hypervisor>",
default="xen",
- help=_("Type of hypervisor")
+ help=_("Type of hypervisor"),
)
return parser
@@ -78,7 +62,7 @@ class CreateAgent(command.ShowOne):
parsed_args.version,
parsed_args.url,
parsed_args.md5hash,
- parsed_args.hypervisor
+ parsed_args.hypervisor,
)
agent = compute_client.agents.create(*args)._info.copy()
return zip(*sorted(agent.items()))
@@ -95,10 +79,7 @@ class DeleteAgent(command.Command):
def get_parser(self, prog_name):
parser = super(DeleteAgent, self).get_parser(prog_name)
parser.add_argument(
- "id",
- metavar="<id>",
- nargs='+',
- help=_("ID of agent(s) to delete")
+ "id", metavar="<id>", nargs='+', help=_("ID of agent(s) to delete")
)
return parser
@@ -110,13 +91,17 @@ class DeleteAgent(command.Command):
compute_client.agents.delete(id)
except Exception as e:
result += 1
- LOG.error(_("Failed to delete agent with ID '%(id)s': %(e)s"),
- {'id': id, 'e': e})
+ LOG.error(
+ _("Failed to delete agent with ID '%(id)s': %(e)s"),
+ {'id': id, 'e': e},
+ )
if result > 0:
total = len(parsed_args.id)
- msg = (_("%(result)s of %(total)s agents failed "
- "to delete.") % {'result': result, 'total': total})
+ msg = _("%(result)s of %(total)s agents failed " "to delete.") % {
+ 'result': result,
+ 'total': total,
+ }
raise exceptions.CommandError(msg)
@@ -133,7 +118,7 @@ class ListAgent(command.Lister):
parser.add_argument(
"--hypervisor",
metavar="<hypervisor>",
- help=_("Type of hypervisor")
+ help=_("Type of hypervisor"),
)
return parser
@@ -146,13 +131,19 @@ class ListAgent(command.Lister):
"Architecture",
"Version",
"Md5Hash",
- "URL"
+ "URL",
)
data = compute_client.agents.list(parsed_args.hypervisor)
- return (columns,
- (utils.get_item_properties(
- s, columns,
- ) for s in data))
+ return (
+ columns,
+ (
+ utils.get_item_properties(
+ s,
+ columns,
+ )
+ for s in data
+ ),
+ )
class SetAgent(command.Command):
@@ -165,26 +156,18 @@ class SetAgent(command.Command):
def get_parser(self, prog_name):
parser = super(SetAgent, self).get_parser(prog_name)
- parser.add_argument(
- "id",
- metavar="<id>",
- help=_("ID of the agent")
- )
+ parser.add_argument("id", metavar="<id>", help=_("ID of the agent"))
parser.add_argument(
"--agent-version",
dest="version",
metavar="<version>",
- help=_("Version of the agent")
+ help=_("Version of the agent"),
)
parser.add_argument(
- "--url",
- metavar="<url>",
- help=_("URL of the agent")
+ "--url", metavar="<url>", help=_("URL of the agent")
)
parser.add_argument(
- "--md5hash",
- metavar="<md5hash>",
- help=_("MD5 hash of the agent")
+ "--md5hash", metavar="<md5hash>", help=_("MD5 hash of the agent")
)
return parser
diff --git a/openstackclient/compute/v2/aggregate.py b/openstackclient/compute/v2/aggregate.py
index 37522a78..49b58d17 100644
--- a/openstackclient/compute/v2/aggregate.py
+++ b/openstackclient/compute/v2/aggregate.py
@@ -47,7 +47,8 @@ def _get_aggregate_columns(item):
}
hidden_columns = ['links', 'location']
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class AddAggregateHost(command.ShowOne):
@@ -58,12 +59,10 @@ class AddAggregateHost(command.ShowOne):
parser.add_argument(
'aggregate',
metavar='<aggregate>',
- help=_("Aggregate (name or ID)")
+ help=_("Aggregate (name or ID)"),
)
parser.add_argument(
- 'host',
- metavar='<host>',
- help=_("Host to add to <aggregate>")
+ 'host', metavar='<host>', help=_("Host to add to <aggregate>")
)
return parser
@@ -71,14 +70,17 @@ class AddAggregateHost(command.ShowOne):
compute_client = self.app.client_manager.sdk_connection.compute
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
aggregate = compute_client.add_host_to_aggregate(
- aggregate.id, parsed_args.host)
+ aggregate.id, parsed_args.host
+ )
display_columns, columns = _get_aggregate_columns(aggregate)
data = utils.get_item_properties(
- aggregate, columns, formatters=_aggregate_formatters)
+ aggregate, columns, formatters=_aggregate_formatters
+ )
return (display_columns, data)
@@ -88,22 +90,22 @@ class CreateAggregate(command.ShowOne):
def get_parser(self, prog_name):
parser = super(CreateAggregate, self).get_parser(prog_name)
parser.add_argument(
- "name",
- metavar="<name>",
- help=_("New aggregate name")
+ "name", metavar="<name>", help=_("New aggregate name")
)
parser.add_argument(
"--zone",
metavar="<availability-zone>",
- help=_("Availability zone name")
+ help=_("Availability zone name"),
)
parser.add_argument(
"--property",
metavar="<key=value>",
action=parseractions.KeyValueAction,
dest="properties",
- help=_("Property to add to this aggregate "
- "(repeat option to set multiple properties)")
+ help=_(
+ "Property to add to this aggregate "
+ "(repeat option to set multiple properties)"
+ ),
)
return parser
@@ -125,7 +127,8 @@ class CreateAggregate(command.ShowOne):
display_columns, columns = _get_aggregate_columns(aggregate)
data = utils.get_item_properties(
- aggregate, columns, formatters=_aggregate_formatters)
+ aggregate, columns, formatters=_aggregate_formatters
+ )
return (display_columns, data)
@@ -138,7 +141,7 @@ class DeleteAggregate(command.Command):
'aggregate',
metavar='<aggregate>',
nargs='+',
- help=_("Aggregate(s) to delete (name or ID)")
+ help=_("Aggregate(s) to delete (name or ID)"),
)
return parser
@@ -148,19 +151,26 @@ class DeleteAggregate(command.Command):
for a in parsed_args.aggregate:
try:
aggregate = compute_client.find_aggregate(
- a, ignore_missing=False)
+ a, ignore_missing=False
+ )
compute_client.delete_aggregate(
- aggregate.id, ignore_missing=False)
+ aggregate.id, ignore_missing=False
+ )
except Exception as e:
result += 1
- LOG.error(_("Failed to delete aggregate with name or "
- "ID '%(aggregate)s': %(e)s"),
- {'aggregate': a, 'e': e})
+ LOG.error(
+ _(
+ "Failed to delete aggregate with name or "
+ "ID '%(aggregate)s': %(e)s"
+ ),
+ {'aggregate': a, 'e': e},
+ )
if result > 0:
total = len(parsed_args.aggregate)
- msg = (_("%(result)s of %(total)s aggregates failed "
- "to delete.") % {'result': result, 'total': total})
+ msg = _(
+ "%(result)s of %(total)s aggregates failed " "to delete."
+ ) % {'result': result, 'total': total}
raise exceptions.CommandError(msg)
@@ -173,7 +183,7 @@ class ListAggregate(command.Lister):
'--long',
action='store_true',
default=False,
- help=_("List additional fields in output")
+ help=_("List additional fields in output"),
)
return parser
@@ -212,7 +222,9 @@ class ListAggregate(command.Lister):
data = (
utils.get_item_properties(
s, columns, formatters=_aggregate_formatters
- ) for s in aggregates)
+ )
+ for s in aggregates
+ )
return (column_headers, data)
@@ -224,12 +236,10 @@ class RemoveAggregateHost(command.ShowOne):
parser.add_argument(
'aggregate',
metavar='<aggregate>',
- help=_("Aggregate (name or ID)")
+ help=_("Aggregate (name or ID)"),
)
parser.add_argument(
- 'host',
- metavar='<host>',
- help=_("Host to remove from <aggregate>")
+ 'host', metavar='<host>', help=_("Host to remove from <aggregate>")
)
return parser
@@ -237,14 +247,17 @@ class RemoveAggregateHost(command.ShowOne):
compute_client = self.app.client_manager.sdk_connection.compute
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
aggregate = compute_client.remove_host_from_aggregate(
- aggregate.id, parsed_args.host)
+ aggregate.id, parsed_args.host
+ )
display_columns, columns = _get_aggregate_columns(aggregate)
data = utils.get_item_properties(
- aggregate, columns, formatters=_aggregate_formatters)
+ aggregate, columns, formatters=_aggregate_formatters
+ )
return (display_columns, data)
@@ -256,40 +269,42 @@ class SetAggregate(command.Command):
parser.add_argument(
'aggregate',
metavar='<aggregate>',
- help=_("Aggregate to modify (name or ID)")
+ help=_("Aggregate to modify (name or ID)"),
)
parser.add_argument(
- '--name',
- metavar='<name>',
- help=_("Set aggregate name")
+ '--name', metavar='<name>', help=_("Set aggregate name")
)
parser.add_argument(
"--zone",
metavar="<availability-zone>",
- help=_("Set availability zone name")
+ help=_("Set availability zone name"),
)
parser.add_argument(
"--property",
metavar="<key=value>",
action=parseractions.KeyValueAction,
dest="properties",
- help=_("Property to set on <aggregate> "
- "(repeat option to set multiple properties)")
+ help=_(
+ "Property to set on <aggregate> "
+ "(repeat option to set multiple properties)"
+ ),
)
parser.add_argument(
"--no-property",
action="store_true",
- help=_("Remove all properties from <aggregate> "
- "(specify both --property and --no-property to "
- "overwrite the current properties)"),
+ help=_(
+ "Remove all properties from <aggregate> "
+ "(specify both --property and --no-property to "
+ "overwrite the current properties)"
+ ),
)
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.sdk_connection.compute
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
kwargs = {}
if parsed_args.name:
@@ -303,10 +318,13 @@ class SetAggregate(command.Command):
if parsed_args.no_property:
# NOTE(RuiChen): "availability_zone" can not be unset from
# properties. It is already excluded from show and create output.
- properties.update({
- key: None for key in aggregate.metadata.keys()
- if key != 'availability_zone'
- })
+ properties.update(
+ {
+ key: None
+ for key in aggregate.metadata.keys()
+ if key != 'availability_zone'
+ }
+ )
if parsed_args.properties:
properties.update(parsed_args.properties)
@@ -323,15 +341,15 @@ class ShowAggregate(command.ShowOne):
parser.add_argument(
'aggregate',
metavar='<aggregate>',
- help=_("Aggregate to display (name or ID)")
+ help=_("Aggregate to display (name or ID)"),
)
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.sdk_connection.compute
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
# Remove availability_zone from metadata because Nova doesn't
if 'availability_zone' in aggregate.metadata:
@@ -339,7 +357,8 @@ class ShowAggregate(command.ShowOne):
display_columns, columns = _get_aggregate_columns(aggregate)
data = utils.get_item_properties(
- aggregate, columns, formatters=_aggregate_formatters)
+ aggregate, columns, formatters=_aggregate_formatters
+ )
return (display_columns, data)
@@ -351,7 +370,7 @@ class UnsetAggregate(command.Command):
parser.add_argument(
"aggregate",
metavar="<aggregate>",
- help=_("Aggregate to modify (name or ID)")
+ help=_("Aggregate to modify (name or ID)"),
)
parser.add_argument(
"--property",
@@ -359,15 +378,18 @@ class UnsetAggregate(command.Command):
action="append",
default=[],
dest="properties",
- help=_("Property to remove from aggregate "
- "(repeat option to remove multiple properties)")
+ help=_(
+ "Property to remove from aggregate "
+ "(repeat option to remove multiple properties)"
+ ),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
properties = {key: None for key in parsed_args.properties}
@@ -385,14 +407,16 @@ class CacheImageForAggregate(command.Command):
parser.add_argument(
'aggregate',
metavar='<aggregate>',
- help=_("Aggregate (name or ID)")
+ help=_("Aggregate (name or ID)"),
)
parser.add_argument(
'image',
metavar='<image>',
nargs='+',
- help=_("Image ID to request caching for aggregate (name or ID). "
- "May be specified multiple times.")
+ help=_(
+ "Image ID to request caching for aggregate (name or ID). "
+ "May be specified multiple times."
+ ),
)
return parser
@@ -407,12 +431,14 @@ class CacheImageForAggregate(command.Command):
raise exceptions.CommandError(msg)
aggregate = compute_client.find_aggregate(
- parsed_args.aggregate, ignore_missing=False)
+ parsed_args.aggregate, ignore_missing=False
+ )
images = []
for img in parsed_args.image:
image = self.app.client_manager.sdk_connection.image.find_image(
- img, ignore_missing=False)
+ img, ignore_missing=False
+ )
images.append(image.id)
compute_client.aggregate_precache_images(aggregate.id, images)
diff --git a/openstackclient/compute/v2/console.py b/openstackclient/compute/v2/console.py
index 0ab5c8a2..bd6d5584 100644
--- a/openstackclient/compute/v2/console.py
+++ b/openstackclient/compute/v2/console.py
@@ -28,7 +28,8 @@ def _get_console_columns(item):
column_map = {}
hidden_columns = ['id', 'links', 'location', 'name']
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class ShowConsoleLog(command.Command):
@@ -39,7 +40,7 @@ class ShowConsoleLog(command.Command):
parser.add_argument(
'server',
metavar='<server>',
- help=_("Server to show console log (name or ID)")
+ help=_("Server to show console log (name or ID)"),
)
parser.add_argument(
'--lines',
@@ -47,8 +48,10 @@ class ShowConsoleLog(command.Command):
type=int,
default=None,
action=parseractions.NonNegativeAction,
- help=_("Number of lines to display from the end of the log "
- "(default=all)")
+ help=_(
+ "Number of lines to display from the end of the log "
+ "(default=all)"
+ ),
)
return parser
@@ -56,12 +59,12 @@ class ShowConsoleLog(command.Command):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- name_or_id=parsed_args.server,
- ignore_missing=False
+ name_or_id=parsed_args.server, ignore_missing=False
)
output = compute_client.get_server_console_output(
- server.id, length=parsed_args.lines)
+ server.id, length=parsed_args.lines
+ )
data = None
if output:
data = output.get('output', None)
@@ -79,7 +82,7 @@ class ShowConsoleURL(command.ShowOne):
parser.add_argument(
'server',
metavar='<server>',
- help=_("Server to show URL (name or ID)")
+ help=_("Server to show URL (name or ID)"),
)
type_group = parser.add_mutually_exclusive_group()
type_group.add_argument(
@@ -88,21 +91,21 @@ class ShowConsoleURL(command.ShowOne):
action='store_const',
const='novnc',
default='novnc',
- help=_("Show noVNC console URL (default)")
+ help=_("Show noVNC console URL (default)"),
)
type_group.add_argument(
'--xvpvnc',
dest='url_type',
action='store_const',
const='xvpvnc',
- help=_("Show xvpvnc console URL")
+ help=_("Show xvpvnc console URL"),
)
type_group.add_argument(
'--spice',
dest='url_type',
action='store_const',
const='spice-html5',
- help=_("Show SPICE console URL")
+ help=_("Show SPICE console URL"),
)
type_group.add_argument(
'--rdp',
@@ -130,11 +133,12 @@ class ShowConsoleURL(command.ShowOne):
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server,
- ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
- data = compute_client.create_console(server.id,
- console_type=parsed_args.url_type)
+ data = compute_client.create_console(
+ server.id, console_type=parsed_args.url_type
+ )
display_columns, columns = _get_console_columns(data)
data = utils.get_dict_properties(data, columns)
diff --git a/openstackclient/compute/v2/flavor.py b/openstackclient/compute/v2/flavor.py
index bc8f758b..d670720c 100644
--- a/openstackclient/compute/v2/flavor.py
+++ b/openstackclient/compute/v2/flavor.py
@@ -34,7 +34,7 @@ LOG = logging.getLogger(__name__)
_formatters = {
'extra_specs': format_columns.DictColumn,
- 'properties': format_columns.DictColumn
+ 'properties': format_columns.DictColumn,
}
@@ -45,12 +45,12 @@ def _get_flavor_columns(item):
'extra_specs': 'properties',
'ephemeral': 'OS-FLV-EXT-DATA:ephemeral',
'is_disabled': 'OS-FLV-DISABLED:disabled',
- 'is_public': 'os-flavor-access:is_public'
-
+ 'is_public': 'os-flavor-access:is_public',
}
hidden_columns = ['links', 'location', 'original_name']
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class CreateFlavor(command.ShowOne):
@@ -59,56 +59,50 @@ class CreateFlavor(command.ShowOne):
def get_parser(self, prog_name):
parser = super(CreateFlavor, self).get_parser(prog_name)
parser.add_argument(
- "name",
- metavar="<flavor-name>",
- help=_("New flavor name")
- )
- parser.add_argument(
- "--id",
- metavar="<id>",
- help=_("Unique flavor ID")
+ "name", metavar="<flavor-name>", help=_("New flavor name")
)
+ parser.add_argument("--id", metavar="<id>", help=_("Unique flavor ID"))
parser.add_argument(
"--ram",
type=int,
metavar="<size-mb>",
default=256,
- help=_("Memory size in MB (default 256M)")
+ help=_("Memory size in MB (default 256M)"),
)
parser.add_argument(
"--disk",
type=int,
metavar="<size-gb>",
default=0,
- help=_("Disk size in GB (default 0G)")
+ help=_("Disk size in GB (default 0G)"),
)
parser.add_argument(
"--ephemeral",
type=int,
metavar="<size-gb>",
default=0,
- help=_("Ephemeral disk size in GB (default 0G)")
+ help=_("Ephemeral disk size in GB (default 0G)"),
)
parser.add_argument(
"--swap",
type=int,
metavar="<size-mb>",
default=0,
- help=_("Additional swap space size in MB (default 0M)")
+ help=_("Additional swap space size in MB (default 0M)"),
)
parser.add_argument(
"--vcpus",
type=int,
metavar="<vcpus>",
default=1,
- help=_("Number of vcpus (default 1)")
+ help=_("Number of vcpus (default 1)"),
)
parser.add_argument(
"--rxtx-factor",
type=float,
metavar="<factor>",
default=1.0,
- help=_("RX/TX factor (default 1.0)")
+ help=_("RX/TX factor (default 1.0)"),
)
public_group = parser.add_mutually_exclusive_group()
public_group.add_argument(
@@ -116,33 +110,39 @@ class CreateFlavor(command.ShowOne):
dest="public",
action="store_true",
default=True,
- help=_("Flavor is available to other projects (default)")
+ help=_("Flavor is available to other projects (default)"),
)
public_group.add_argument(
"--private",
dest="public",
action="store_false",
- help=_("Flavor is not available to other projects")
+ help=_("Flavor is not available to other projects"),
)
parser.add_argument(
"--property",
metavar="<key=value>",
action=parseractions.KeyValueAction,
dest="properties",
- help=_("Property to add for this flavor "
- "(repeat option to set multiple properties)")
+ help=_(
+ "Property to add for this flavor "
+ "(repeat option to set multiple properties)"
+ ),
)
parser.add_argument(
'--project',
metavar='<project>',
- help=_("Allow <project> to access private flavor (name or ID) "
- "(Must be used with --private option)"),
+ help=_(
+ "Allow <project> to access private flavor (name or ID) "
+ "(Must be used with --private option)"
+ ),
)
parser.add_argument(
'--description',
metavar='<description>',
- help=_("Description for the flavor.(Supported by API versions "
- "'2.55' - '2.latest'")
+ help=_(
+ "Description for the flavor.(Supported by API versions "
+ "'2.55' - '2.latest'"
+ ),
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
@@ -186,22 +186,25 @@ class CreateFlavor(command.ShowOne):
parsed_args.project,
parsed_args.project_domain,
).id
- compute_client.flavor_add_tenant_access(
- flavor.id, project_id)
+ compute_client.flavor_add_tenant_access(flavor.id, project_id)
except Exception as e:
- msg = _("Failed to add project %(project)s access to "
- "flavor: %(e)s")
+ msg = _(
+ "Failed to add project %(project)s access to "
+ "flavor: %(e)s"
+ )
LOG.error(msg, {'project': parsed_args.project, 'e': e})
if parsed_args.properties:
try:
flavor = compute_client.create_flavor_extra_specs(
- flavor, parsed_args.properties)
+ flavor, parsed_args.properties
+ )
except Exception as e:
LOG.error(_("Failed to set flavor properties: %s"), e)
display_columns, columns = _get_flavor_columns(flavor)
- data = utils.get_dict_properties(flavor, columns,
- formatters=_formatters)
+ data = utils.get_dict_properties(
+ flavor, columns, formatters=_formatters
+ )
return (display_columns, data)
@@ -215,7 +218,7 @@ class DeleteFlavor(command.Command):
"flavor",
metavar="<flavor>",
nargs='+',
- help=_("Flavor(s) to delete (name or ID)")
+ help=_("Flavor(s) to delete (name or ID)"),
)
return parser
@@ -228,13 +231,20 @@ class DeleteFlavor(command.Command):
compute_client.delete_flavor(flavor.id)
except Exception as e:
result += 1
- LOG.error(_("Failed to delete flavor with name or "
- "ID '%(flavor)s': %(e)s"), {'flavor': f, 'e': e})
+ LOG.error(
+ _(
+ "Failed to delete flavor with name or "
+ "ID '%(flavor)s': %(e)s"
+ ),
+ {'flavor': f, 'e': e},
+ )
if result > 0:
total = len(parsed_args.flavor)
- msg = (_("%(result)s of %(total)s flavors failed "
- "to delete.") % {'result': result, 'total': total})
+ msg = _("%(result)s of %(total)s flavors failed " "to delete.") % {
+ 'result': result,
+ 'total': total,
+ }
raise exceptions.CommandError(msg)
@@ -249,20 +259,20 @@ class ListFlavor(command.Lister):
dest="public",
action="store_true",
default=True,
- help=_("List only public flavors (default)")
+ help=_("List only public flavors (default)"),
)
public_group.add_argument(
"--private",
dest="public",
action="store_false",
- help=_("List only private flavors")
+ help=_("List only private flavors"),
)
public_group.add_argument(
"--all",
dest="all",
action="store_true",
default=False,
- help=_("List all flavors, whether public or private")
+ help=_("List all flavors, whether public or private"),
)
parser.add_argument(
'--min-disk',
@@ -280,12 +290,12 @@ class ListFlavor(command.Lister):
'--long',
action='store_true',
default=False,
- help=_("List additional fields in output")
+ help=_("List additional fields in output"),
)
parser.add_argument(
'--marker',
metavar="<flavor-id>",
- help=_("The last flavor ID of the previous page")
+ help=_("The last flavor ID of the previous page"),
)
parser.add_argument(
'--limit',
@@ -308,9 +318,7 @@ class ListFlavor(command.Lister):
# and flavors from their own projects only.
is_public = None if parsed_args.all else parsed_args.public
- query_attrs = {
- 'is_public': is_public
- }
+ query_attrs = {'is_public': is_public}
if parsed_args.marker:
query_attrs['marker'] = parsed_args.marker
@@ -343,7 +351,7 @@ class ListFlavor(command.Lister):
"disk",
"ephemeral",
"vcpus",
- "is_public"
+ "is_public",
)
if parsed_args.long:
columns += (
@@ -359,7 +367,7 @@ class ListFlavor(command.Lister):
"Disk",
"Ephemeral",
"VCPUs",
- "Is Public"
+ "Is Public",
)
if parsed_args.long:
column_headers += (
@@ -385,36 +393,43 @@ class SetFlavor(command.Command):
parser.add_argument(
"flavor",
metavar="<flavor>",
- help=_("Flavor to modify (name or ID)")
+ help=_("Flavor to modify (name or ID)"),
)
parser.add_argument(
"--no-property",
action="store_true",
- help=_("Remove all properties from this flavor "
- "(specify both --no-property and --property"
- " to remove the current properties before setting"
- " new properties.)"),
+ help=_(
+ "Remove all properties from this flavor "
+ "(specify both --no-property and --property"
+ " to remove the current properties before setting"
+ " new properties.)"
+ ),
)
parser.add_argument(
"--property",
metavar="<key=value>",
action=parseractions.KeyValueAction,
dest="properties",
- help=_("Property to add or modify for this flavor "
- "(repeat option to set multiple properties)")
+ help=_(
+ "Property to add or modify for this flavor "
+ "(repeat option to set multiple properties)"
+ ),
)
parser.add_argument(
'--project',
metavar='<project>',
- help=_('Set flavor access to project (name or ID) '
- '(admin only)'),
+ help=_(
+ 'Set flavor access to project (name or ID) ' '(admin only)'
+ ),
)
identity_common.add_project_domain_option_to_parser(parser)
parser.add_argument(
'--description',
metavar='<description>',
- help=_("Set description for the flavor.(Supported by API "
- "versions '2.55' - '2.latest'")
+ help=_(
+ "Set description for the flavor.(Supported by API "
+ "versions '2.55' - '2.latest'"
+ ),
)
return parser
@@ -425,9 +440,8 @@ class SetFlavor(command.Command):
try:
flavor = compute_client.find_flavor(
- parsed_args.flavor,
- get_extra_specs=True,
- ignore_missing=False)
+ parsed_args.flavor, get_extra_specs=True, ignore_missing=False
+ )
except sdk_exceptions.ResourceNotFound as e:
raise exceptions.CommandError(e.message)
@@ -440,14 +454,16 @@ class SetFlavor(command.Command):
raise exceptions.CommandError(msg)
compute_client.update_flavor(
- flavor=flavor.id, description=parsed_args.description)
+ flavor=flavor.id, description=parsed_args.description
+ )
result = 0
if parsed_args.no_property:
try:
for key in flavor.extra_specs.keys():
compute_client.delete_flavor_extra_specs_property(
- flavor.id, key)
+ flavor.id, key
+ )
except Exception as e:
LOG.error(_("Failed to clear flavor properties: %s"), e)
result += 1
@@ -455,7 +471,8 @@ class SetFlavor(command.Command):
if parsed_args.properties:
try:
compute_client.create_flavor_extra_specs(
- flavor.id, parsed_args.properties)
+ flavor.id, parsed_args.properties
+ )
except Exception as e:
LOG.error(_("Failed to set flavor properties: %s"), e)
result += 1
@@ -472,14 +489,16 @@ class SetFlavor(command.Command):
parsed_args.project_domain,
).id
compute_client.flavor_add_tenant_access(
- flavor.id, project_id)
+ flavor.id, project_id
+ )
except Exception as e:
LOG.error(_("Failed to set flavor access to project: %s"), e)
result += 1
if result > 0:
- raise exceptions.CommandError(_("Command Failed: One or more of"
- " the operations failed"))
+ raise exceptions.CommandError(
+ _("Command Failed: One or more of" " the operations failed")
+ )
class ShowFlavor(command.ShowOne):
@@ -490,27 +509,32 @@ class ShowFlavor(command.ShowOne):
parser.add_argument(
"flavor",
metavar="<flavor>",
- help=_("Flavor to display (name or ID)")
+ help=_("Flavor to display (name or ID)"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
flavor = compute_client.find_flavor(
- parsed_args.flavor, get_extra_specs=True, ignore_missing=False)
+ parsed_args.flavor, get_extra_specs=True, ignore_missing=False
+ )
access_projects = None
# get access projects list of this flavor
if not flavor.is_public:
try:
flavor_access = compute_client.get_flavor_access(
- flavor=flavor.id)
+ flavor=flavor.id
+ )
access_projects = [
utils.get_field(access, 'tenant_id')
- for access in flavor_access]
+ for access in flavor_access
+ ]
except Exception as e:
- msg = _("Failed to get access projects list "
- "for flavor '%(flavor)s': %(e)s")
+ msg = _(
+ "Failed to get access projects list "
+ "for flavor '%(flavor)s': %(e)s"
+ )
LOG.error(msg, {'flavor': parsed_args.flavor, 'e': e})
# Since we need to inject "access_project_id" into resource - convert
@@ -520,7 +544,8 @@ class ShowFlavor(command.ShowOne):
display_columns, columns = _get_flavor_columns(flavor)
data = utils.get_dict_properties(
- flavor, columns, formatters=_formatters)
+ flavor, columns, formatters=_formatters
+ )
return (display_columns, data)
@@ -533,21 +558,25 @@ class UnsetFlavor(command.Command):
parser.add_argument(
"flavor",
metavar="<flavor>",
- help=_("Flavor to modify (name or ID)")
+ help=_("Flavor to modify (name or ID)"),
)
parser.add_argument(
"--property",
metavar="<key>",
action='append',
dest="properties",
- help=_("Property to remove from flavor "
- "(repeat option to unset multiple properties)")
+ help=_(
+ "Property to remove from flavor "
+ "(repeat option to unset multiple properties)"
+ ),
)
parser.add_argument(
'--project',
metavar='<project>',
- help=_('Remove flavor access from project (name or ID) '
- '(admin only)'),
+ help=_(
+ 'Remove flavor access from project (name or ID) '
+ '(admin only)'
+ ),
)
identity_common.add_project_domain_option_to_parser(parser)
@@ -559,9 +588,8 @@ class UnsetFlavor(command.Command):
try:
flavor = compute_client.find_flavor(
- parsed_args.flavor,
- get_extra_specs=True,
- ignore_missing=False)
+ parsed_args.flavor, get_extra_specs=True, ignore_missing=False
+ )
except sdk_exceptions.ResourceNotFound as e:
raise exceptions.CommandError(_(e.message))
@@ -570,7 +598,8 @@ class UnsetFlavor(command.Command):
for key in parsed_args.properties:
try:
compute_client.delete_flavor_extra_specs_property(
- flavor.id, key)
+ flavor.id, key
+ )
except sdk_exceptions.SDKException as e:
LOG.error(_("Failed to unset flavor property: %s"), e)
result += 1
@@ -587,12 +616,15 @@ class UnsetFlavor(command.Command):
parsed_args.project_domain,
).id
compute_client.flavor_remove_tenant_access(
- flavor.id, project_id)
+ flavor.id, project_id
+ )
except Exception as e:
- LOG.error(_("Failed to remove flavor access from project: %s"),
- e)
+ LOG.error(
+ _("Failed to remove flavor access from project: %s"), e
+ )
result += 1
if result > 0:
- raise exceptions.CommandError(_("Command Failed: One or more of"
- " the operations failed"))
+ raise exceptions.CommandError(
+ _("Command Failed: One or more of" " the operations failed")
+ )
diff --git a/openstackclient/compute/v2/host.py b/openstackclient/compute/v2/host.py
index e6dd3a6f..a5946d1d 100644
--- a/openstackclient/compute/v2/host.py
+++ b/openstackclient/compute/v2/host.py
@@ -29,17 +29,13 @@ class ListHost(command.Lister):
parser.add_argument(
"--zone",
metavar="<zone>",
- help=_("Only return hosts in the availability zone")
+ help=_("Only return hosts in the availability zone"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
- columns = (
- "Host Name",
- "Service",
- "Zone"
- )
+ columns = ("Host Name", "Service", "Zone")
self.log.warning(
"API has been deprecated. "
@@ -48,9 +44,11 @@ class ListHost(command.Lister):
# doing this since openstacksdk has decided not to support this
# deprecated command
- hosts = compute_client.get(
- '/os-hosts', microversion='2.1'
- ).json().get('hosts')
+ hosts = (
+ compute_client.get('/os-hosts', microversion='2.1')
+ .json()
+ .get('hosts')
+ )
if parsed_args.zone is not None:
filtered_hosts = []
@@ -69,31 +67,25 @@ class SetHost(command.Command):
def get_parser(self, prog_name):
parser = super(SetHost, self).get_parser(prog_name)
parser.add_argument(
- "host",
- metavar="<host>",
- help=_("Host to modify (name only)")
+ "host", metavar="<host>", help=_("Host to modify (name only)")
)
status = parser.add_mutually_exclusive_group()
status.add_argument(
- '--enable',
- action='store_true',
- help=_("Enable the host")
+ '--enable', action='store_true', help=_("Enable the host")
)
status.add_argument(
- '--disable',
- action='store_true',
- help=_("Disable the host")
+ '--disable', action='store_true', help=_("Disable the host")
)
maintenance = parser.add_mutually_exclusive_group()
maintenance.add_argument(
'--enable-maintenance',
action='store_true',
- help=_("Enable maintenance mode for the host")
+ help=_("Enable maintenance mode for the host"),
)
maintenance.add_argument(
'--disable-maintenance',
action='store_true',
- help=_("Disable maintenance mode for the host")
+ help=_("Disable maintenance mode for the host"),
)
return parser
@@ -111,10 +103,7 @@ class SetHost(command.Command):
compute_client = self.app.client_manager.compute
- compute_client.api.host_set(
- parsed_args.host,
- **kwargs
- )
+ compute_client.api.host_set(parsed_args.host, **kwargs)
class ShowHost(command.Lister):
@@ -122,22 +111,12 @@ class ShowHost(command.Lister):
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
- parser.add_argument(
- "host",
- metavar="<host>",
- help=_("Name of host")
- )
+ parser.add_argument("host", metavar="<host>", help=_("Name of host"))
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
- columns = (
- "Host",
- "Project",
- "CPU",
- "Memory MB",
- "Disk GB"
- )
+ columns = ("Host", "Project", "CPU", "Memory MB", "Disk GB")
self.log.warning(
"API has been deprecated. "
@@ -146,10 +125,13 @@ class ShowHost(command.Lister):
# doing this since openstacksdk has decided not to support this
# deprecated command
- resources = compute_client.get(
- '/os-hosts/' + parsed_args.host,
- microversion='2.1'
- ).json().get('host')
+ resources = (
+ compute_client.get(
+ '/os-hosts/' + parsed_args.host, microversion='2.1'
+ )
+ .json()
+ .get('host')
+ )
data = []
if resources is not None:
diff --git a/openstackclient/compute/v2/hypervisor.py b/openstackclient/compute/v2/hypervisor.py
index 971e3d2a..ddfd3e8d 100644
--- a/openstackclient/compute/v2/hypervisor.py
+++ b/openstackclient/compute/v2/hypervisor.py
@@ -33,32 +33,37 @@ def _get_hypervisor_columns(item, client):
hidden_columns = ['location', 'servers']
if sdk_utils.supports_microversion(client, '2.88'):
- hidden_columns.extend([
- 'current_workload',
- 'disk_available',
- 'local_disk_free',
- 'local_disk_size',
- 'local_disk_used',
- 'memory_free',
- 'memory_size',
- 'memory_used',
- 'running_vms',
- 'vcpus_used',
- 'vcpus',
- ])
+ hidden_columns.extend(
+ [
+ 'current_workload',
+ 'disk_available',
+ 'local_disk_free',
+ 'local_disk_size',
+ 'local_disk_used',
+ 'memory_free',
+ 'memory_size',
+ 'memory_used',
+ 'running_vms',
+ 'vcpus_used',
+ 'vcpus',
+ ]
+ )
else:
- column_map.update({
- 'disk_available': 'disk_available_least',
- 'local_disk_free': 'free_disk_gb',
- 'local_disk_size': 'local_gb',
- 'local_disk_used': 'local_gb_used',
- 'memory_free': 'free_ram_mb',
- 'memory_used': 'memory_mb_used',
- 'memory_size': 'memory_mb',
- })
+ column_map.update(
+ {
+ 'disk_available': 'disk_available_least',
+ 'local_disk_free': 'free_disk_gb',
+ 'local_disk_size': 'local_gb',
+ 'local_disk_used': 'local_gb_used',
+ 'memory_free': 'free_ram_mb',
+ 'memory_used': 'memory_mb_used',
+ 'memory_size': 'memory_mb',
+ }
+ )
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class ListHypervisor(command.Lister):
@@ -73,7 +78,7 @@ class ListHypervisor(command.Lister):
"Filter hypervisors using <hostname> substring"
"Hypervisor Type and Host IP are not returned "
"when using microversion 2.52 or lower"
- )
+ ),
)
parser.add_argument(
'--marker',
@@ -99,7 +104,7 @@ class ListHypervisor(command.Lister):
parser.add_argument(
'--long',
action='store_true',
- help=_("List additional fields in output")
+ help=_("List additional fields in output"),
)
return parser
@@ -109,9 +114,7 @@ class ListHypervisor(command.Lister):
list_opts = {}
if parsed_args.matching and (parsed_args.marker or parsed_args.limit):
- msg = _(
- '--matching is not compatible with --marker or --limit'
- )
+ msg = _('--matching is not compatible with --marker or --limit')
raise exceptions.CommandError(msg)
if parsed_args.marker:
@@ -140,15 +143,9 @@ class ListHypervisor(command.Lister):
"Hypervisor Hostname",
"Hypervisor Type",
"Host IP",
- "State"
- )
- columns = (
- 'id',
- 'name',
- 'hypervisor_type',
- 'host_ip',
- 'state'
+ "State",
)
+ columns = ('id', 'name', 'hypervisor_type', 'host_ip', 'state')
if parsed_args.long:
if not sdk_utils.supports_microversion(compute_client, '2.88'):
@@ -156,13 +153,13 @@ class ListHypervisor(command.Lister):
'vCPUs Used',
'vCPUs',
'Memory MB Used',
- 'Memory MB'
+ 'Memory MB',
)
columns += (
'vcpus_used',
'vcpus',
'memory_used',
- 'memory_size'
+ 'memory_size',
)
data = compute_client.hypervisors(**list_opts, details=True)
@@ -181,14 +178,15 @@ class ShowHypervisor(command.ShowOne):
parser.add_argument(
"hypervisor",
metavar="<hypervisor>",
- help=_("Hypervisor to display (name or ID)")
+ help=_("Hypervisor to display (name or ID)"),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
hypervisor = compute_client.find_hypervisor(
- parsed_args.hypervisor, ignore_missing=False).copy()
+ parsed_args.hypervisor, ignore_missing=False
+ ).copy()
# Some of the properties in the hypervisor object need to be processed
# before they get reported to the user. We spend this section
@@ -208,14 +206,18 @@ class ShowHypervisor(command.ShowOne):
if cell:
# The host aggregates are also prefixed by "<cell>@"
- member_of = [aggregate.name
- for aggregate in aggregates
- if cell in aggregate.name and
- service_host in aggregate.hosts]
+ member_of = [
+ aggregate.name
+ for aggregate in aggregates
+ if cell in aggregate.name
+ and service_host in aggregate.hosts
+ ]
else:
- member_of = [aggregate.name
- for aggregate in aggregates
- if service_host in aggregate.hosts]
+ member_of = [
+ aggregate.name
+ for aggregate in aggregates
+ if service_host in aggregate.hosts
+ ]
hypervisor['aggregates'] = member_of
try:
@@ -225,14 +227,16 @@ class ShowHypervisor(command.ShowOne):
else:
del hypervisor['uptime']
uptime = compute_client.get_hypervisor_uptime(
- hypervisor['id'])['uptime']
+ hypervisor['id']
+ )['uptime']
# Extract data from uptime value
# format: 0 up 0, 0 users, load average: 0, 0, 0
# example: 17:37:14 up 2:33, 3 users,
# load average: 0.33, 0.36, 0.34
m = re.match(
r"\s*(.+)\sup\s+(.+),\s+(.+)\susers?,\s+load average:\s(.+)",
- uptime)
+ uptime,
+ )
if m:
hypervisor['host_time'] = m.group(1)
hypervisor['uptime'] = m.group(2)
@@ -250,11 +254,14 @@ class ShowHypervisor(command.ShowOne):
# string; on earlier fields, do this manually
hypervisor['cpu_info'] = json.loads(hypervisor['cpu_info'] or '{}')
display_columns, columns = _get_hypervisor_columns(
- hypervisor, compute_client)
+ hypervisor, compute_client
+ )
data = utils.get_dict_properties(
- hypervisor, columns,
+ hypervisor,
+ columns,
formatters={
'cpu_info': format_columns.DictColumn,
- })
+ },
+ )
return display_columns, data
diff --git a/openstackclient/compute/v2/hypervisor_stats.py b/openstackclient/compute/v2/hypervisor_stats.py
index cb63a800..63ca71fd 100644
--- a/openstackclient/compute/v2/hypervisor_stats.py
+++ b/openstackclient/compute/v2/hypervisor_stats.py
@@ -29,11 +29,11 @@ def _get_hypervisor_stat_columns(item):
'memory_free': 'free_ram_mb',
'memory_size': 'memory_mb',
'memory_used': 'memory_mb_used',
-
}
hidden_columns = ['id', 'links', 'location', 'name']
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class ShowHypervisorStats(command.ShowOne):
@@ -41,19 +41,17 @@ class ShowHypervisorStats(command.ShowOne):
def take_action(self, parsed_args):
# The command is deprecated since it is being dropped in Nova.
- self.log.warning(
- _("This command is deprecated.")
- )
+ self.log.warning(_("This command is deprecated."))
compute_client = self.app.client_manager.sdk_connection.compute
# We do API request directly cause this deprecated method is not and
# will not be supported by OpenStackSDK.
response = compute_client.get(
- '/os-hypervisors/statistics',
- microversion='2.1')
+ '/os-hypervisors/statistics', microversion='2.1'
+ )
hypervisor_stats = response.json().get('hypervisor_statistics')
display_columns, columns = _get_hypervisor_stat_columns(
- hypervisor_stats)
- data = utils.get_dict_properties(
- hypervisor_stats, columns)
+ hypervisor_stats
+ )
+ data = utils.get_dict_properties(hypervisor_stats, columns)
return (display_columns, data)
diff --git a/openstackclient/compute/v2/keypair.py b/openstackclient/compute/v2/keypair.py
index 3a5513ef..3e16feab 100644
--- a/openstackclient/compute/v2/keypair.py
+++ b/openstackclient/compute/v2/keypair.py
@@ -45,12 +45,15 @@ def _generate_keypair():
private_key = key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.OpenSSH,
- serialization.NoEncryption()
- ).decode()
- public_key = key.public_key().public_bytes(
- serialization.Encoding.OpenSSH,
- serialization.PublicFormat.OpenSSH
+ serialization.NoEncryption(),
).decode()
+ public_key = (
+ key.public_key()
+ .public_bytes(
+ serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH
+ )
+ .decode()
+ )
return Keypair(private_key, public_key)
@@ -65,7 +68,8 @@ def _get_keypair_columns(item, hide_pub_key=False, hide_priv_key=False):
if hide_priv_key:
hidden_columns.append('private_key')
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class CreateKeypair(command.ShowOne):
@@ -74,9 +78,7 @@ class CreateKeypair(command.ShowOne):
def get_parser(self, prog_name):
parser = super(CreateKeypair, self).get_parser(prog_name)
parser.add_argument(
- 'name',
- metavar='<name>',
- help=_("New public or private key name")
+ 'name', metavar='<name>', help=_("New public or private key name")
)
key_group = parser.add_mutually_exclusive_group()
key_group.add_argument(
@@ -96,7 +98,7 @@ class CreateKeypair(command.ShowOne):
help=_(
"Filename for private key to save. "
"If not used, print private key in console."
- )
+ ),
)
parser.add_argument(
'--type',
@@ -122,9 +124,7 @@ class CreateKeypair(command.ShowOne):
compute_client = self.app.client_manager.sdk_connection.compute
identity_client = self.app.client_manager.identity
- kwargs = {
- 'name': parsed_args.name
- }
+ kwargs = {'name': parsed_args.name}
if parsed_args.public_key:
generated_keypair = None
@@ -134,7 +134,8 @@ class CreateKeypair(command.ShowOne):
except IOError as e:
msg = _("Key file %(public_key)s not found: %(exception)s")
raise exceptions.CommandError(
- msg % {
+ msg
+ % {
"public_key": parsed_args.public_key,
"exception": e,
}
@@ -158,7 +159,8 @@ class CreateKeypair(command.ShowOne):
"%(exception)s"
)
raise exceptions.CommandError(
- msg % {
+ msg
+ % {
"private_key": parsed_args.private_key,
"exception": e,
}
@@ -195,7 +197,8 @@ class CreateKeypair(command.ShowOne):
# For now, duplicate nova keypair-add command output
if parsed_args.public_key or parsed_args.private_key:
display_columns, columns = _get_keypair_columns(
- keypair, hide_pub_key=True, hide_priv_key=True)
+ keypair, hide_pub_key=True, hide_priv_key=True
+ )
data = utils.get_item_properties(keypair, columns)
return (display_columns, data)
@@ -213,7 +216,7 @@ class DeleteKeypair(command.Command):
'name',
metavar='<key>',
nargs='+',
- help=_("Name of key(s) to delete (name only)")
+ help=_("Name of key(s) to delete (name only)"),
)
parser.add_argument(
'--user',
@@ -250,16 +253,21 @@ class DeleteKeypair(command.Command):
for n in parsed_args.name:
try:
compute_client.delete_keypair(
- n, **kwargs, ignore_missing=False)
+ n, **kwargs, ignore_missing=False
+ )
except Exception as e:
result += 1
- LOG.error(_("Failed to delete key with name "
- "'%(name)s': %(e)s"), {'name': n, 'e': e})
+ LOG.error(
+ _("Failed to delete key with name " "'%(name)s': %(e)s"),
+ {'name': n, 'e': e},
+ )
if result > 0:
total = len(parsed_args.name)
- msg = (_("%(result)s of %(total)s keys failed "
- "to delete.") % {'result': result, 'total': total})
+ msg = _("%(result)s of %(total)s keys failed " "to delete.") % {
+ 'result': result,
+ 'total': total,
+ }
raise exceptions.CommandError(msg)
@@ -337,9 +345,7 @@ class ListKeypair(command.Lister):
# NOTE(stephenfin): Because we're doing this client-side, we
# can't really rely on the marker, because we don't know what
# user the marker is associated with
- msg = _(
- '--project is not compatible with --marker'
- )
+ msg = _('--project is not compatible with --marker')
# NOTE(stephenfin): This is done client side because nova doesn't
# currently support doing so server-side. If this is slow, we can
@@ -374,13 +380,10 @@ class ListKeypair(command.Lister):
else:
data = compute_client.keypairs(**kwargs)
- columns = (
- "Name",
- "Fingerprint"
- )
+ columns = ("Name", "Fingerprint")
if sdk_utils.supports_microversion(compute_client, '2.2'):
- columns += ("Type", )
+ columns += ("Type",)
return (
columns,
@@ -396,13 +399,13 @@ class ShowKeypair(command.ShowOne):
parser.add_argument(
'name',
metavar='<key>',
- help=_("Public or private key to display (name only)")
+ help=_("Public or private key to display (name only)"),
)
parser.add_argument(
'--public-key',
action='store_true',
default=False,
- help=_("Show only bare public key paired with the generated key")
+ help=_("Show only bare public key paired with the generated key"),
)
parser.add_argument(
'--user',
@@ -436,11 +439,13 @@ class ShowKeypair(command.ShowOne):
).id
keypair = compute_client.find_keypair(
- parsed_args.name, **kwargs, ignore_missing=False)
+ parsed_args.name, **kwargs, ignore_missing=False
+ )
if not parsed_args.public_key:
display_columns, columns = _get_keypair_columns(
- keypair, hide_pub_key=True)
+ keypair, hide_pub_key=True
+ )
data = utils.get_item_properties(keypair, columns)
return (display_columns, data)
else:
diff --git a/openstackclient/compute/v2/server.py b/openstackclient/compute/v2/server.py
index b3da7321..cde4ab05 100644
--- a/openstackclient/compute/v2/server.py
+++ b/openstackclient/compute/v2/server.py
@@ -48,14 +48,14 @@ class PowerStateColumn(cliff_columns.FormattableColumn):
"""Generate a formatted string of a server's power state."""
power_states = [
- 'NOSTATE', # 0x00
- 'Running', # 0x01
- '', # 0x02
- 'Paused', # 0x03
- 'Shutdown', # 0x04
- '', # 0x05
- 'Crashed', # 0x06
- 'Suspended' # 0x07
+ 'NOSTATE', # 0x00
+ 'Running', # 0x01
+ '', # 0x02
+ 'Paused', # 0x03
+ 'Shutdown', # 0x04
+ '', # 0x05
+ 'Crashed', # 0x06
+ 'Suspended', # 0x07
]
def human_readable(self):
@@ -70,15 +70,20 @@ class AddressesColumn(cliff_columns.FormattableColumn):
def human_readable(self):
try:
- return utils.format_dict_of_list({
- k: [i['addr'] for i in v if 'addr' in i]
- for k, v in self._value.items()})
+ return utils.format_dict_of_list(
+ {
+ k: [i['addr'] for i in v if 'addr' in i]
+ for k, v in self._value.items()
+ }
+ )
except Exception:
return 'N/A'
def machine_readable(self):
- return {k: [i['addr'] for i in v if 'addr' in i]
- for k, v in self._value.items()}
+ return {
+ k: [i['addr'] for i in v if 'addr' in i]
+ for k, v in self._value.items()
+ }
class HostColumn(cliff_columns.FormattableColumn):
@@ -120,8 +125,7 @@ def _get_ip_address(addresses, address_type, ip_address_family):
return addy['addr']
msg = _("ERROR: No %(type)s IP version %(family)s address found")
raise exceptions.CommandError(
- msg % {"type": address_type,
- "family": ip_address_family}
+ msg % {"type": address_type, "family": ip_address_family}
)
@@ -184,9 +188,13 @@ def _prep_server_detail(compute_client, image_client, server, refresh=True):
'vm_state': 'OS-EXT-STS:vm_state',
}
- info.update({
- column_map[column]: data for column, data in info.items()
- if column in column_map})
+ info.update(
+ {
+ column_map[column]: data
+ for column, data in info.items()
+ if column in column_map
+ }
+ )
# Convert the image blob to a name
image_info = info.get('image', {})
@@ -223,14 +231,16 @@ def _prep_server_detail(compute_client, image_client, server, refresh=True):
info.update(
{
'volumes_attached': format_columns.ListDictColumn(
- info.pop('os-extended-volumes:volumes_attached'))
+ info.pop('os-extended-volumes:volumes_attached')
+ )
}
)
if 'security_groups' in info:
info.update(
{
'security_groups': format_columns.ListDictColumn(
- info.pop('security_groups'))
+ info.pop('security_groups')
+ )
}
)
if 'tags' in info:
@@ -239,8 +249,10 @@ def _prep_server_detail(compute_client, image_client, server, refresh=True):
# NOTE(dtroyer): novaclient splits these into separate entries...
# Format addresses in a useful way
info['addresses'] = (
- AddressesColumn(info['addresses']) if 'addresses' in info
- else format_columns.DictListColumn(info.get('networks')))
+ AddressesColumn(info['addresses'])
+ if 'addresses' in info
+ else format_columns.DictListColumn(info.get('networks'))
+ )
# Map 'metadata' field to 'properties'
info['properties'] = format_columns.DictColumn(info.pop('metadata'))
@@ -252,7 +264,8 @@ def _prep_server_detail(compute_client, image_client, server, refresh=True):
# Map power state num to meaningful string
if 'OS-EXT-STS:power_state' in info:
info['OS-EXT-STS:power_state'] = PowerStateColumn(
- info['OS-EXT-STS:power_state'])
+ info['OS-EXT-STS:power_state']
+ )
# Remove values that are long and not too useful
info.pop('links', None)
@@ -306,15 +319,14 @@ class AddFixedIP(command.ShowOne):
help=_(
'Tag for the attached interface. '
'(supported by --os-compute-api-version 2.49 or above)'
- )
+ ),
)
return parser
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server,
- ignore_missing=False
+ parsed_args.server, ignore_missing=False
)
if parsed_args.tag:
@@ -328,36 +340,39 @@ class AddFixedIP(command.ShowOne):
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
net_id = network_client.find_network(
- parsed_args.network,
- ignore_missing=False
+ parsed_args.network, ignore_missing=False
).id
else:
net_id = parsed_args.network
if not sdk_utils.supports_microversion(compute_client, '2.44'):
- compute_client.add_fixed_ip_to_server(
- server.id,
- net_id
- )
+ compute_client.add_fixed_ip_to_server(server.id, net_id)
return ((), ())
- kwargs = {
- 'net_id': net_id
- }
+ kwargs = {'net_id': net_id}
if parsed_args.fixed_ip_address:
kwargs['fixed_ips'] = [
- {"ip_address": parsed_args.fixed_ip_address}]
+ {"ip_address": parsed_args.fixed_ip_address}
+ ]
if parsed_args.tag:
kwargs['tag'] = parsed_args.tag
interface = compute_client.create_server_interface(server.id, **kwargs)
columns = (
- 'port_id', 'server_id', 'net_id', 'mac_addr', 'port_state',
+ 'port_id',
+ 'server_id',
+ 'net_id',
+ 'mac_addr',
+ 'port_state',
'fixed_ips',
)
column_headers = (
- 'Port ID', 'Server ID', 'Network ID', 'MAC Address', 'Port State',
+ 'Port ID',
+ 'Server ID',
+ 'Network ID',
+ 'MAC Address',
+ 'Port State',
'Fixed IPs',
)
if sdk_utils.supports_microversion(compute_client, '2.49'):
@@ -388,8 +403,10 @@ class AddFloatingIP(network_common.NetworkAndComputeCommand):
parser.add_argument(
"ip_address",
metavar="<ip-address>",
- help=_("Floating IP address to assign to the first available "
- "server port (IP only)"),
+ help=_(
+ "Floating IP address to assign to the first available "
+ "server port (IP only)"
+ ),
)
parser.add_argument(
"--fixed-ip-address",
@@ -448,8 +465,11 @@ class AddFloatingIP(network_common.NetworkAndComputeCommand):
client.update_ip(obj, **attrs)
except sdk_exceptions.NotFoundException as exp:
# 404 ExternalGatewayForFloatingIPNotFound from neutron
- LOG.info('Skipped port %s because it is not attached to '
- 'an external gateway', port.id)
+ LOG.info(
+ 'Skipped port %s because it is not attached to '
+ 'an external gateway',
+ port.id,
+ )
error = exp
continue
else:
@@ -487,7 +507,7 @@ class AddPort(command.Command):
help=_(
'Tag for the attached interface '
'(supported by --os-compute-api-version 2.49 or later)'
- )
+ ),
)
return parser
@@ -495,18 +515,18 @@ class AddPort(command.Command):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
port_id = network_client.find_port(
- parsed_args.port, ignore_missing=False).id
+ parsed_args.port, ignore_missing=False
+ ).id
else:
port_id = parsed_args.port
- kwargs = {
- 'port_id': port_id
- }
+ kwargs = {'port_id': port_id}
if parsed_args.tag:
if not sdk_utils.supports_microversion(compute_client, '2.49'):
@@ -549,18 +569,18 @@ class AddNetwork(command.Command):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
net_id = network_client.find_network(
- parsed_args.network, ignore_missing=False).id
+ parsed_args.network, ignore_missing=False
+ ).id
else:
net_id = parsed_args.network
- kwargs = {
- 'net_id': net_id
- }
+ kwargs = {'net_id': net_id}
if parsed_args.tag:
if not sdk_utils.supports_microversion(compute_client, '2.49'):
@@ -607,10 +627,12 @@ class AddServerSecurityGroup(command.Command):
class AddServerVolume(command.ShowOne):
- _description = _("""Add volume to server.
+ _description = _(
+ """Add volume to server.
Specify ``--os-compute-api-version 2.20`` or higher to add a volume to a server
-with status ``SHELVED`` or ``SHELVED_OFFLOADED``.""")
+with status ``SHELVED`` or ``SHELVED_OFFLOADED``."""
+ )
def get_parser(self, prog_name):
parser = super(AddServerVolume, self).get_parser(prog_name)
@@ -671,10 +693,7 @@ with status ``SHELVED`` or ``SHELVED_OFFLOADED``.""")
ignore_missing=False,
)
- kwargs = {
- "volumeId": volume.id,
- "device": parsed_args.device
- }
+ kwargs = {"volumeId": volume.id, "device": parsed_args.device}
if parsed_args.tag:
if not sdk_utils.supports_microversion(compute_client, '2.49'):
@@ -722,12 +741,14 @@ with status ``SHELVED`` or ``SHELVED_OFFLOADED``.""")
return (
column_headers,
- utils.get_item_properties(volume_attachment, columns,)
+ utils.get_item_properties(
+ volume_attachment,
+ columns,
+ ),
)
class NoneNICAction(argparse.Action):
-
def __init__(self, option_strings, dest, help=None):
super().__init__(
option_strings=option_strings,
@@ -747,7 +768,6 @@ class NoneNICAction(argparse.Action):
class AutoNICAction(argparse.Action):
-
def __init__(self, option_strings, dest, help=None):
super().__init__(
option_strings=option_strings,
@@ -767,7 +787,6 @@ class AutoNICAction(argparse.Action):
class NICAction(argparse.Action):
-
def __init__(
self,
option_strings,
@@ -844,7 +863,6 @@ class NICAction(argparse.Action):
class BDMLegacyAction(argparse.Action):
-
def __call__(self, parser, namespace, values, option_string=None):
# Make sure we have an empty list rather than None
if getattr(namespace, self.dest, None) is None:
@@ -889,18 +907,28 @@ class BDMLegacyAction(argparse.Action):
class BDMAction(parseractions.MultiKeyValueAction):
-
def __init__(self, option_strings, dest, **kwargs):
required_keys = []
optional_keys = [
- 'uuid', 'source_type', 'destination_type',
- 'disk_bus', 'device_type', 'device_name', 'volume_size',
- 'guest_format', 'boot_index', 'delete_on_termination', 'tag',
+ 'uuid',
+ 'source_type',
+ 'destination_type',
+ 'disk_bus',
+ 'device_type',
+ 'device_name',
+ 'volume_size',
+ 'guest_format',
+ 'boot_index',
+ 'delete_on_termination',
+ 'tag',
'volume_type',
]
super().__init__(
- option_strings, dest, required_keys=required_keys,
- optional_keys=optional_keys, **kwargs,
+ option_strings,
+ dest,
+ required_keys=required_keys,
+ optional_keys=optional_keys,
+ **kwargs,
)
# TODO(stephenfin): Remove once I549d0897ef3704b7f47000f867d6731ad15d3f2b
@@ -917,10 +945,13 @@ class BDMAction(parseractions.MultiKeyValueAction):
"Invalid keys %(invalid_keys)s specified.\n"
"Valid keys are: %(valid_keys)s"
)
- raise argparse.ArgumentTypeError(msg % {
- 'invalid_keys': ', '.join(invalid_keys),
- 'valid_keys': ', '.join(valid_keys),
- })
+ raise argparse.ArgumentTypeError(
+ msg
+ % {
+ 'invalid_keys': ', '.join(invalid_keys),
+ 'valid_keys': ', '.join(valid_keys),
+ }
+ )
missing_keys = [k for k in self.required_keys if k not in keys]
if missing_keys:
@@ -928,10 +959,13 @@ class BDMAction(parseractions.MultiKeyValueAction):
"Missing required keys %(missing_keys)s.\n"
"Required keys are: %(required_keys)s"
)
- raise argparse.ArgumentTypeError(msg % {
- 'missing_keys': ', '.join(missing_keys),
- 'required_keys': ', '.join(self.required_keys),
- })
+ raise argparse.ArgumentTypeError(
+ msg
+ % {
+ 'missing_keys': ', '.join(missing_keys),
+ 'required_keys': ', '.join(self.required_keys),
+ }
+ )
def __call__(self, parser, namespace, values, option_string=None):
if getattr(namespace, self.dest, None) is None:
@@ -1023,7 +1057,7 @@ class CreateServer(command.ShowOne):
'be deleted when the server is deleted. This option is '
'mutually exclusive with the ``--volume`` and ``--snapshot`` '
'options.'
- )
+ ),
)
# TODO(stephenfin): Remove this in the v7.0
parser.add_argument(
@@ -1168,7 +1202,7 @@ class CreateServer(command.ShowOne):
parser.add_argument(
'--nic',
metavar="<net-id=net-uuid,port-id=port-uuid,v4-fixed-ip=ip-addr,"
- "v6-fixed-ip=ip-addr,tag=tag,auto,none>",
+ "v6-fixed-ip=ip-addr,tag=tag,auto,none>",
dest='nics',
action=NICAction,
# NOTE(RuiChen): Add '\n' to the end of line to improve formatting;
@@ -1372,7 +1406,6 @@ class CreateServer(command.ShowOne):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -1386,9 +1419,11 @@ class CreateServer(command.ShowOne):
image = None
if parsed_args.image:
image = image_client.find_image(
- parsed_args.image, ignore_missing=False)
+ parsed_args.image, ignore_missing=False
+ )
if not image and parsed_args.image_properties:
+
def emit_duplicated_warning(img):
img_uuid_list = [str(image.id) for image in img]
LOG.warning(
@@ -1397,7 +1432,8 @@ class CreateServer(command.ShowOne):
{
'img_uuid_list': img_uuid_list,
'chosen_one': img_uuid_list[0],
- })
+ },
+ )
def _match_image(image_api, wanted_properties):
image_list = image_api.images()
@@ -1418,7 +1454,9 @@ class CreateServer(command.ShowOne):
'Skipped the \'%s\' attribute. '
'That cannot be compared. '
'(image: %s, value: %s)',
- key, img.id, value,
+ key,
+ img.id,
+ value,
)
pass
else:
@@ -1469,7 +1507,8 @@ class CreateServer(command.ShowOne):
).id
flavor = utils.find_resource(
- compute_client.flavors, parsed_args.flavor)
+ compute_client.flavors, parsed_args.flavor
+ )
if parsed_args.file:
if compute_client.api_version >= api_versions.APIVersion('2.57'):
@@ -1515,47 +1554,57 @@ class CreateServer(command.ShowOne):
if parsed_args.description:
if compute_client.api_version < api_versions.APIVersion("2.19"):
- msg = _("Description is not supported for "
- "--os-compute-api-version less than 2.19")
+ msg = _(
+ "Description is not supported for "
+ "--os-compute-api-version less than 2.19"
+ )
raise exceptions.CommandError(msg)
block_device_mapping_v2 = []
if volume:
- block_device_mapping_v2 = [{
- 'uuid': volume,
- 'boot_index': 0,
- 'source_type': 'volume',
- 'destination_type': 'volume'
- }]
+ block_device_mapping_v2 = [
+ {
+ 'uuid': volume,
+ 'boot_index': 0,
+ 'source_type': 'volume',
+ 'destination_type': 'volume',
+ }
+ ]
elif snapshot:
- block_device_mapping_v2 = [{
- 'uuid': snapshot,
- 'boot_index': 0,
- 'source_type': 'snapshot',
- 'destination_type': 'volume',
- 'delete_on_termination': False
- }]
+ block_device_mapping_v2 = [
+ {
+ 'uuid': snapshot,
+ 'boot_index': 0,
+ 'source_type': 'snapshot',
+ 'destination_type': 'volume',
+ 'delete_on_termination': False,
+ }
+ ]
elif parsed_args.boot_from_volume:
# Tell nova to create a root volume from the image provided.
- block_device_mapping_v2 = [{
- 'uuid': image.id,
- 'boot_index': 0,
- 'source_type': 'image',
- 'destination_type': 'volume',
- 'volume_size': parsed_args.boot_from_volume
- }]
+ block_device_mapping_v2 = [
+ {
+ 'uuid': image.id,
+ 'boot_index': 0,
+ 'source_type': 'image',
+ 'destination_type': 'volume',
+ 'volume_size': parsed_args.boot_from_volume,
+ }
+ ]
# If booting from volume we do not pass an image to compute.
image = None
if parsed_args.swap:
- block_device_mapping_v2.append({
- 'boot_index': -1,
- 'source_type': 'blank',
- 'destination_type': 'local',
- 'guest_format': 'swap',
- 'volume_size': parsed_args.swap,
- 'delete_on_termination': True,
- })
+ block_device_mapping_v2.append(
+ {
+ 'boot_index': -1,
+ 'source_type': 'blank',
+ 'destination_type': 'local',
+ 'guest_format': 'swap',
+ 'volume_size': parsed_args.swap,
+ 'delete_on_termination': True,
+ }
+ )
for mapping in parsed_args.ephemerals:
block_device_mapping_dict = {
@@ -1577,12 +1626,14 @@ class CreateServer(command.ShowOne):
# just in case
if mapping['source_type'] == 'volume':
volume_id = utils.find_resource(
- volume_client.volumes, mapping['uuid'],
+ volume_client.volumes,
+ mapping['uuid'],
).id
mapping['uuid'] = volume_id
elif mapping['source_type'] == 'snapshot':
snapshot_id = utils.find_resource(
- volume_client.volume_snapshots, mapping['uuid'],
+ volume_client.volume_snapshots,
+ mapping['uuid'],
).id
mapping['uuid'] = snapshot_id
elif mapping['source_type'] == 'image':
@@ -1598,7 +1649,8 @@ class CreateServer(command.ShowOne):
# create a volume from the image and attach it to the
# server as a non-root volume.
image_id = image_client.find_image(
- mapping['uuid'], ignore_missing=False,
+ mapping['uuid'],
+ ignore_missing=False,
).id
mapping['uuid'] = image_id
@@ -1635,7 +1687,10 @@ class CreateServer(command.ShowOne):
if 'source_type' in mapping:
if mapping['source_type'] not in (
- 'volume', 'image', 'snapshot', 'blank',
+ 'volume',
+ 'image',
+ 'snapshot',
+ 'blank',
):
msg = _(
'The source_type key of --block-device should be one '
@@ -1661,7 +1716,8 @@ class CreateServer(command.ShowOne):
if 'delete_on_termination' in mapping:
try:
value = strutils.bool_from_string(
- mapping['delete_on_termination'], strict=True)
+ mapping['delete_on_termination'], strict=True
+ )
except ValueError:
msg = _(
'The delete_on_termination key of --block-device '
@@ -1708,9 +1764,8 @@ class CreateServer(command.ShowOne):
else:
for nic in nics:
if 'tag' in nic:
- if (
- compute_client.api_version <
- api_versions.APIVersion('2.43')
+ if compute_client.api_version < api_versions.APIVersion(
+ '2.43'
):
msg = _(
'--os-compute-api-version 2.43 or greater is '
@@ -1723,13 +1778,15 @@ class CreateServer(command.ShowOne):
if nic['net-id']:
net = network_client.find_network(
- nic['net-id'], ignore_missing=False,
+ nic['net-id'],
+ ignore_missing=False,
)
nic['net-id'] = net.id
if nic['port-id']:
port = network_client.find_port(
- nic['port-id'], ignore_missing=False,
+ nic['port-id'],
+ ignore_missing=False,
)
nic['port-id'] = port.id
else:
@@ -1760,8 +1817,9 @@ class CreateServer(command.ShowOne):
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
for each_sg in parsed_args.security_group:
- sg = network_client.find_security_group(each_sg,
- ignore_missing=False)
+ sg = network_client.find_security_group(
+ each_sg, ignore_missing=False
+ )
# Use security group ID to avoid multiple security group have
# same name in neutron networking backend
security_group_names.append(sg.id)
@@ -1787,8 +1845,12 @@ class CreateServer(command.ShowOne):
# '--config-drive'
if str(parsed_args.config_drive).lower() in ("true", "1"):
config_drive = True
- elif str(parsed_args.config_drive).lower() in ("false", "0",
- "", "none"):
+ elif str(parsed_args.config_drive).lower() in (
+ "false",
+ "0",
+ "",
+ "none",
+ ):
config_drive = None
else:
config_drive = parsed_args.config_drive
@@ -1809,7 +1871,8 @@ class CreateServer(command.ShowOne):
block_device_mapping_v2=block_device_mapping_v2,
nics=nics,
scheduler_hints=hints,
- config_drive=config_drive)
+ config_drive=config_drive,
+ )
if parsed_args.description:
boot_kwargs['description'] = parsed_args.description
@@ -1842,8 +1905,9 @@ class CreateServer(command.ShowOne):
)
raise exceptions.CommandError(msg)
- boot_kwargs['hypervisor_hostname'] = (
- parsed_args.hypervisor_hostname)
+ boot_kwargs[
+ 'hypervisor_hostname'
+ ] = parsed_args.hypervisor_hostname
if parsed_args.hostname:
if compute_client.api_version < api_versions.APIVersion("2.90"):
@@ -1965,7 +2029,6 @@ class DeleteServer(command.Command):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -1974,8 +2037,10 @@ class DeleteServer(command.Command):
compute_client = self.app.client_manager.compute
for server in parsed_args.server:
server_obj = utils.find_resource(
- compute_client.servers, server,
- all_tenants=parsed_args.all_projects)
+ compute_client.servers,
+ server,
+ all_tenants=parsed_args.all_projects,
+ )
if parsed_args.force:
compute_client.servers.force_delete(server_obj.id)
@@ -2062,7 +2127,7 @@ class ListServer(command.Lister):
'SHUTOFF',
'SOFT_DELETED',
'SUSPENDED',
- 'VERIFY_RESIZE'
+ 'VERIFY_RESIZE',
),
help=_('Search by server status'),
)
@@ -2093,7 +2158,7 @@ class ListServer(command.Lister):
parser.add_argument(
'--project',
metavar='<project>',
- help=_("Search by project (admin only) (name or ID)")
+ help=_("Search by project (admin only) (name or ID)"),
)
identity_common.add_project_domain_option_to_parser(parser)
parser.add_argument(
@@ -2259,7 +2324,8 @@ class ListServer(command.Lister):
)
name_lookup_group = parser.add_mutually_exclusive_group()
name_lookup_group.add_argument(
- '-n', '--no-name-lookup',
+ '-n',
+ '--no-name-lookup',
action='store_true',
default=False,
help=_(
@@ -2511,8 +2577,8 @@ class ListServer(command.Lister):
iso8601.parse_date(search_opts['changes-before'])
except (TypeError, iso8601.ParseError):
raise exceptions.CommandError(
- _('Invalid changes-before value: %s') %
- search_opts['changes-before']
+ _('Invalid changes-before value: %s')
+ % search_opts['changes-before']
)
if search_opts['changes-since']:
@@ -2659,7 +2725,8 @@ class ListServer(command.Lister):
# partial responses from down cells will not have an image
# attribute so we use getattr
image_ids = {
- s.image['id'] for s in data
+ s.image['id']
+ for s in data
if getattr(s, 'image', None) and s.image.get('id')
}
@@ -2700,7 +2767,8 @@ class ListServer(command.Lister):
# present if there are infra failures
if parsed_args.name_lookup_one_by_one or flavor_id:
for f_id in set(
- s.flavor['id'] for s in data
+ s.flavor['id']
+ for s in data
if s.flavor and s.flavor.get('id')
):
# "Flavor Name" is not crucial, so we swallow any
@@ -2765,8 +2833,8 @@ class ListServer(command.Lister):
# it's on, providing useful information to a user in this
# situation.
if (
- sdk_utils.supports_microversion(compute_client, '2.16') and
- parsed_args.long
+ sdk_utils.supports_microversion(compute_client, '2.16')
+ and parsed_args.long
):
if any([s.host_status is not None for s in data]):
columns += ('Host Status',)
@@ -2776,7 +2844,8 @@ class ListServer(command.Lister):
column_headers,
(
utils.get_item_properties(
- s, columns,
+ s,
+ columns,
mixed_case_fields=(
'task_state',
'power_state',
@@ -2790,17 +2859,19 @@ class ListServer(command.Lister):
'security_groups_name': format_columns.ListColumn,
'hypervisor_hostname': HostColumn,
},
- ) for s in data
+ )
+ for s in data
),
)
return table
class LockServer(command.Command):
+ _description = _(
+ """Lock server(s)
- _description = _("""Lock server(s)
-
-A non-admin user will not be able to execute actions.""")
+A non-admin user will not be able to execute actions."""
+ )
def get_parser(self, prog_name):
parser = super(LockServer, self).get_parser(prog_name)
@@ -2837,8 +2908,7 @@ A non-admin user will not be able to execute actions.""")
for server in parsed_args.server:
server_id = compute_client.find_server(
- server,
- ignore_missing=False
+ server, ignore_missing=False
).id
compute_client.lock_server(server_id, **kwargs)
@@ -2853,8 +2923,10 @@ A non-admin user will not be able to execute actions.""")
# live_parser = parser.add_argument_group(title='Live migration options')
# then adding the groups doesn't seem to work
+
class MigrateServer(command.Command):
- _description = _("""Migrate server to different host.
+ _description = _(
+ """Migrate server to different host.
A migrate operation is implemented as a resize operation using the same flavor
as the old server. This means that, like resize, migrate works by creating a
@@ -2862,7 +2934,8 @@ new server using the same flavor and copying the contents of the original disk
into a new one. As with resize, the migrate operation is a two-step process for
the user: the first step is to perform the migrate, and the second step is to
either confirm (verify) success and release the old server, or to declare a
-revert to release the new server and restart the old one.""")
+revert to release the new server and restart the old one."""
+ )
def get_parser(self, prog_name):
parser = super(MigrateServer, self).get_parser(prog_name)
@@ -2939,7 +3012,6 @@ revert to release the new server and restart the old one.""")
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -2957,9 +3029,8 @@ revert to release the new server and restart the old one.""")
block_migration = parsed_args.block_migration
if block_migration is None:
- if (
- compute_client.api_version <
- api_versions.APIVersion('2.25')
+ if compute_client.api_version < api_versions.APIVersion(
+ '2.25'
):
block_migration = False
else:
@@ -2974,8 +3045,9 @@ revert to release the new server and restart the old one.""")
# and --host, we want to enforce that they are using version
# 2.30 or greater.
if (
- parsed_args.host and
- compute_client.api_version < api_versions.APIVersion('2.30')
+ parsed_args.host
+ and compute_client.api_version
+ < api_versions.APIVersion('2.30')
):
raise exceptions.CommandError(
'--os-compute-api-version 2.30 or greater is required '
@@ -3008,10 +3080,12 @@ revert to release the new server and restart the old one.""")
raise exceptions.CommandError(
"--live-migration must be specified if "
"--block-migration or --disk-overcommit is "
- "specified")
+ "specified"
+ )
if parsed_args.host:
- if (compute_client.api_version <
- api_versions.APIVersion('2.56')):
+ if compute_client.api_version < api_versions.APIVersion(
+ '2.56'
+ ):
msg = _(
'--os-compute-api-version 2.56 or greater is '
'required to use --host without --live-migration.'
@@ -3030,8 +3104,7 @@ revert to release the new server and restart the old one.""")
):
self.app.stdout.write(_('Complete\n'))
else:
- LOG.error(_('Error migrating server: %s'),
- server.id)
+ LOG.error(_('Error migrating server: %s'), server.id)
self.app.stdout.write(_('Error migrating server\n'))
raise SystemExit
@@ -3094,7 +3167,6 @@ class RebootServer(command.Command):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -3301,7 +3373,6 @@ class RebuildServer(command.ShowOne):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -3311,7 +3382,8 @@ class RebuildServer(command.ShowOne):
image_client = self.app.client_manager.image
server = utils.find_resource(
- compute_client.servers, parsed_args.server)
+ compute_client.servers, parsed_args.server
+ )
# If parsed_args.image is not set and if the instance is image backed,
# default to the currently used one. If the instance is volume backed,
@@ -3319,7 +3391,8 @@ class RebuildServer(command.ShowOne):
# to error out in this case and ask user to supply the image.
if parsed_args.image:
image = image_client.find_image(
- parsed_args.image, ignore_missing=False)
+ parsed_args.image, ignore_missing=False
+ )
else:
if not server.image:
msg = _(
@@ -3482,12 +3555,14 @@ class RebuildServer(command.ShowOne):
raise SystemExit
details = _prep_server_detail(
- compute_client, image_client, server, refresh=False)
+ compute_client, image_client, server, refresh=False
+ )
return zip(*sorted(details.items()))
class EvacuateServer(command.ShowOne):
- _description = _("""Evacuate a server to a different host.
+ _description = _(
+ """Evacuate a server to a different host.
This command is used to recreate a server after the host it was on has failed.
It can only be used if the compute service that manages the server is down.
@@ -3500,7 +3575,8 @@ the ports and any attached data volumes.
If the server uses boot for volume or has its root disk on shared storage the
root disk will be preserved and reused for the evacuated instance on the new
-host.""")
+host."""
+ )
def get_parser(self, prog_name):
parser = super(EvacuateServer, self).get_parser(prog_name)
@@ -3511,11 +3587,14 @@ host.""")
)
parser.add_argument(
- '--wait', action='store_true',
+ '--wait',
+ action='store_true',
help=_('Wait for evacuation to complete'),
)
parser.add_argument(
- '--host', metavar='<host>', default=None,
+ '--host',
+ metavar='<host>',
+ default=None,
help=_(
'Set the preferred host on which to rebuild the evacuated '
'server. The host will be validated by the scheduler. '
@@ -3524,7 +3603,9 @@ host.""")
)
shared_storage_group = parser.add_mutually_exclusive_group()
shared_storage_group.add_argument(
- '--password', metavar='<password>', default=None,
+ '--password',
+ metavar='<password>',
+ default=None,
help=_(
'Set the password on the evacuated instance. This option is '
'mutually exclusive with the --shared-storage option. '
@@ -3532,7 +3613,9 @@ host.""")
),
)
shared_storage_group.add_argument(
- '--shared-storage', action='store_true', dest='shared_storage',
+ '--shared-storage',
+ action='store_true',
+ dest='shared_storage',
help=_(
'Indicate that the instance is on shared storage. '
'This will be auto-calculated with '
@@ -3544,7 +3627,6 @@ host.""")
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -3578,7 +3660,8 @@ host.""")
kwargs['on_shared_storage'] = parsed_args.shared_storage
server = utils.find_resource(
- compute_client.servers, parsed_args.server)
+ compute_client.servers, parsed_args.server
+ )
server.evacuate(**kwargs)
@@ -3595,7 +3678,8 @@ host.""")
raise SystemExit
details = _prep_server_detail(
- compute_client, image_client, server, refresh=True)
+ compute_client, image_client, server, refresh=True
+ )
return zip(*sorted(details.items()))
@@ -3620,7 +3704,8 @@ class RemoveFixedIP(command.Command):
compute_client = self.app.client_manager.compute
server = utils.find_resource(
- compute_client.servers, parsed_args.server)
+ compute_client.servers, parsed_args.server
+ )
server.remove_fixed_ip(parsed_args.ip_address)
@@ -3681,12 +3766,14 @@ class RemovePort(command.Command):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
port_id = network_client.find_port(
- parsed_args.port, ignore_missing=False).id
+ parsed_args.port, ignore_missing=False
+ ).id
else:
port_id = parsed_args.port
@@ -3718,12 +3805,14 @@ class RemoveNetwork(command.Command):
compute_client = self.app.client_manager.sdk_connection.compute
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
if self.app.client_manager.is_network_endpoint_enabled():
network_client = self.app.client_manager.network
net_id = network_client.find_network(
- parsed_args.network, ignore_missing=False).id
+ parsed_args.network, ignore_missing=False
+ ).id
else:
net_id = parsed_args.network
@@ -3767,10 +3856,12 @@ class RemoveServerSecurityGroup(command.Command):
class RemoveServerVolume(command.Command):
- _description = _("""Remove volume from server.
+ _description = _(
+ """Remove volume from server.
Specify ``--os-compute-api-version 2.20`` or higher to remove a
-volume from a server with status ``SHELVED`` or ``SHELVED_OFFLOADED``.""")
+volume from a server with status ``SHELVED`` or ``SHELVED_OFFLOADED``."""
+ )
def get_parser(self, prog_name):
parser = super(RemoveServerVolume, self).get_parser(prog_name)
@@ -3807,10 +3898,12 @@ volume from a server with status ``SHELVED`` or ``SHELVED_OFFLOADED``.""")
class RescueServer(command.Command):
- _description = _("""Put server in rescue mode.
+ _description = _(
+ """Put server in rescue mode.
Specify ``--os-compute-api-version 2.87`` or higher to rescue a
-server booted from a volume.""")
+server booted from a volume."""
+ )
def get_parser(self, prog_name):
parser = super(RescueServer, self).get_parser(prog_name)
@@ -3822,8 +3915,10 @@ server booted from a volume.""")
parser.add_argument(
'--image',
metavar='<image>',
- help=_('Image (name or ID) to use for the rescue mode.'
- ' Defaults to the currently used one.'),
+ help=_(
+ 'Image (name or ID) to use for the rescue mode.'
+ ' Defaults to the currently used one.'
+ ),
)
parser.add_argument(
'--password',
@@ -3846,18 +3941,19 @@ server booted from a volume.""")
utils.find_resource(
compute_client.servers,
parsed_args.server,
- ).rescue(image=image,
- password=parsed_args.password)
+ ).rescue(image=image, password=parsed_args.password)
class ResizeServer(command.Command):
- _description = _("""Scale server to a new flavor.
+ _description = _(
+ """Scale server to a new flavor.
A resize operation is implemented by creating a new server and copying the
contents of the original disk into a new one. It is a two-step process for the
user: the first step is to perform the resize, and the second step is to either
confirm (verify) success and release the old server or to declare a revert to
-release the new server and restart the old one.""")
+release the new server and restart the old one."""
+ )
def get_parser(self, prog_name):
parser = super(ResizeServer, self).get_parser(prog_name)
@@ -3898,7 +3994,6 @@ release the new server and restart the old one.""")
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -3924,26 +4019,33 @@ release the new server and restart the old one.""")
):
self.app.stdout.write(_('Complete\n'))
else:
- LOG.error(_('Error resizing server: %s'),
- server.id)
+ LOG.error(_('Error resizing server: %s'), server.id)
self.app.stdout.write(_('Error resizing server\n'))
raise SystemExit
elif parsed_args.confirm:
- self.log.warning(_(
- "The --confirm option has been deprecated. Please use the "
- "'openstack server resize confirm' command instead."))
+ self.log.warning(
+ _(
+ "The --confirm option has been deprecated. Please use the "
+ "'openstack server resize confirm' command instead."
+ )
+ )
compute_client.servers.confirm_resize(server)
elif parsed_args.revert:
- self.log.warning(_(
- "The --revert option has been deprecated. Please use the "
- "'openstack server resize revert' command instead."))
+ self.log.warning(
+ _(
+ "The --revert option has been deprecated. Please use the "
+ "'openstack server resize revert' command instead."
+ )
+ )
compute_client.servers.revert_resize(server)
class ResizeConfirm(command.Command):
- _description = _("""Confirm server resize.
+ _description = _(
+ """Confirm server resize.
-Confirm (verify) success of resize operation and release the old server.""")
+Confirm (verify) success of resize operation and release the old server."""
+ )
def get_parser(self, prog_name):
parser = super(ResizeConfirm, self).get_parser(prog_name)
@@ -3955,7 +4057,6 @@ Confirm (verify) success of resize operation and release the old server.""")
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers,
@@ -3979,17 +4080,21 @@ class MigrateConfirm(ResizeConfirm):
class ConfirmMigration(ResizeConfirm):
- _description = _("""Confirm server migration.
+ _description = _(
+ """Confirm server migration.
Confirm (verify) success of the migration operation and release the old
-server.""")
+server."""
+ )
class ResizeRevert(command.Command):
- _description = _("""Revert server resize.
+ _description = _(
+ """Revert server resize.
Revert the resize operation. Release the new server and restart the old
-one.""")
+one."""
+ )
def get_parser(self, prog_name):
parser = super(ResizeRevert, self).get_parser(prog_name)
@@ -4001,7 +4106,6 @@ one.""")
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers,
@@ -4025,10 +4129,12 @@ class MigrateRevert(ResizeRevert):
class RevertMigration(ResizeRevert):
- _description = _("""Revert server migration.
+ _description = _(
+ """Revert server migration.
Revert the migration operation. Release the new server and restart the old
-one.""")
+one."""
+ )
class RestoreServer(command.Command):
@@ -4169,7 +4275,6 @@ class SetServer(command.Command):
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.compute
server = utils.find_resource(
compute_client.servers,
@@ -4282,7 +4387,6 @@ class ShelveServer(command.Command):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -4348,7 +4452,8 @@ class ShelveServer(command.Command):
callback=_show_progress,
):
LOG.error(
- _('Error offloading shelved server %s'), server_obj.id,
+ _('Error offloading shelved server %s'),
+ server_obj.id,
)
self.app.stdout.write(
_('Error offloading shelved server: %s\n') % server_obj.id
@@ -4357,10 +4462,12 @@ class ShelveServer(command.Command):
class ShowServer(command.ShowOne):
- _description = _("""Show server details.
+ _description = _(
+ """Show server details.
Specify ``--os-compute-api-version 2.47`` or higher to see the embedded flavor
-information for the server.""")
+information for the server."""
+ )
def get_parser(self, prog_name):
parser = super(ShowServer, self).get_parser(prog_name)
@@ -4393,7 +4500,8 @@ information for the server.""")
# Find by name or ID, then get the full details of the server
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False)
+ parsed_args.server, ignore_missing=False
+ )
server = compute_client.get_server(server)
if parsed_args.diagnostics:
@@ -4417,7 +4525,8 @@ information for the server.""")
self.app.client_manager.compute,
self.app.client_manager.image,
server,
- refresh=False)
+ refresh=False,
+ )
if topology:
data['topology'] = format_columns.DictColumn(topology)
@@ -4437,26 +4546,30 @@ class SshServer(command.Command):
)
# Deprecated during the Yoga cycle
parser.add_argument(
- '--login', '-l',
+ '--login',
+ '-l',
metavar='<login-name>',
help=argparse.SUPPRESS,
)
# Deprecated during the Yoga cycle
parser.add_argument(
- '--port', '-p',
+ '--port',
+ '-p',
metavar='<port>',
type=int,
help=argparse.SUPPRESS,
)
# Deprecated during the Yoga cycle
parser.add_argument(
- '--identity', '-i',
+ '--identity',
+ '-i',
metavar='<keyfile>',
help=argparse.SUPPRESS,
)
# Deprecated during the Yoga cycle
parser.add_argument(
- '--option', '-o',
+ '--option',
+ '-o',
metavar='<config-options>',
help=argparse.SUPPRESS,
)
@@ -4519,7 +4632,6 @@ class SshServer(command.Command):
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.compute
server = utils.find_resource(
@@ -4528,13 +4640,15 @@ class SshServer(command.Command):
)
# first, handle the deprecated options
- if any((
- parsed_args.port,
- parsed_args.identity,
- parsed_args.option,
- parsed_args.login,
- parsed_args.verbose,
- )):
+ if any(
+ (
+ parsed_args.port,
+ parsed_args.identity,
+ parsed_args.option,
+ parsed_args.login,
+ parsed_args.verbose,
+ )
+ ):
msg = _(
'The ssh options have been deprecated. The ssh equivalent '
'options can be used instead as arguments after "--" on '
@@ -4742,7 +4856,6 @@ class UnrescueServer(command.Command):
return parser
def take_action(self, parsed_args):
-
compute_client = self.app.client_manager.compute
utils.find_resource(
compute_client.servers,
@@ -4766,15 +4879,19 @@ class UnsetServer(command.Command):
action='append',
default=[],
dest='properties',
- help=_('Property key to remove from server '
- '(repeat option to remove multiple values)'),
+ help=_(
+ 'Property key to remove from server '
+ '(repeat option to remove multiple values)'
+ ),
)
parser.add_argument(
'--description',
dest='description',
action='store_true',
- help=_('Unset server description (supported by '
- '--os-compute-api-version 2.19 or above)'),
+ help=_(
+ 'Unset server description (supported by '
+ '--os-compute-api-version 2.19 or above)'
+ ),
)
parser.add_argument(
'--tag',
@@ -4802,8 +4919,10 @@ class UnsetServer(command.Command):
if parsed_args.description:
if compute_client.api_version < api_versions.APIVersion("2.19"):
- msg = _("Description is not supported for "
- "--os-compute-api-version less than 2.19")
+ msg = _(
+ "Description is not supported for "
+ "--os-compute-api-version less than 2.19"
+ )
raise exceptions.CommandError(msg)
compute_client.servers.update(
server,
@@ -4872,7 +4991,6 @@ class UnshelveServer(command.Command):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -4918,7 +5036,8 @@ class UnshelveServer(command.Command):
)
if server_obj.status.lower() not in (
- 'shelved', 'shelved_offloaded',
+ 'shelved',
+ 'shelved_offloaded',
):
continue
diff --git a/openstackclient/compute/v2/server_backup.py b/openstackclient/compute/v2/server_backup.py
index 53891991..c88a0b6c 100644
--- a/openstackclient/compute/v2/server_backup.py
+++ b/openstackclient/compute/v2/server_backup.py
@@ -66,7 +66,6 @@ class CreateServerBackup(command.ShowOne):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stderr.write('\rProgress: %s' % progress)
diff --git a/openstackclient/compute/v2/server_event.py b/openstackclient/compute/v2/server_event.py
index 395c2cac..7c161cee 100644
--- a/openstackclient/compute/v2/server_event.py
+++ b/openstackclient/compute/v2/server_event.py
@@ -95,7 +95,7 @@ class ListServerEvent(command.Lister):
'--long',
action='store_true',
default=False,
- help=_("List additional fields in output")
+ help=_("List additional fields in output"),
)
parser.add_argument(
'--changes-since',
@@ -196,8 +196,7 @@ class ListServerEvent(command.Lister):
try:
server_id = compute_client.find_server(
- parsed_args.server,
- ignore_missing=False
+ parsed_args.server, ignore_missing=False
).id
except sdk_exceptions.ResourceNotFound:
# If we fail to find the resource, it is possible the server is
@@ -282,11 +281,13 @@ class ShowServerEvent(command.ShowOne):
raise
server_action = compute_client.get_server_action(
- parsed_args.request_id, server_id,
+ parsed_args.request_id,
+ server_id,
)
column_headers, columns = _get_server_event_columns(
- server_action, compute_client,
+ server_action,
+ compute_client,
)
return (
diff --git a/openstackclient/compute/v2/server_group.py b/openstackclient/compute/v2/server_group.py
index eadc3ffb..d1c0bf97 100644
--- a/openstackclient/compute/v2/server_group.py
+++ b/openstackclient/compute/v2/server_group.py
@@ -48,7 +48,8 @@ def _get_server_group_columns(item, client):
hidden_columns.append('rules')
return utils.get_osc_show_columns_for_sdk_resource(
- item, column_map, hidden_columns)
+ item, column_map, hidden_columns
+ )
class CreateServerGroup(command.ShowOne):
@@ -167,8 +168,7 @@ class DeleteServerGroup(command.Command):
total = len(parsed_args.server_group)
msg = _("%(result)s of %(total)s server groups failed to delete.")
raise exceptions.CommandError(
- msg % {"result": result,
- "total": total}
+ msg % {"result": result, "total": total}
)
@@ -261,8 +261,11 @@ class ListServerGroup(command.Lister):
column_headers,
(
utils.get_item_properties(
- s, columns, formatters=_formatters,
- ) for s in data
+ s,
+ columns,
+ formatters=_formatters,
+ )
+ for s in data
),
)
diff --git a/openstackclient/compute/v2/server_image.py b/openstackclient/compute/v2/server_image.py
index 2021fae7..ec4b7b23 100644
--- a/openstackclient/compute/v2/server_image.py
+++ b/openstackclient/compute/v2/server_image.py
@@ -67,7 +67,6 @@ class CreateServerImage(command.ShowOne):
return parser
def take_action(self, parsed_args):
-
def _show_progress(progress):
if progress:
self.app.stdout.write('\rProgress: %s' % progress)
@@ -77,7 +76,8 @@ class CreateServerImage(command.ShowOne):
image_client = self.app.client_manager.image
server = compute_client.find_server(
- parsed_args.server, ignore_missing=False,
+ parsed_args.server,
+ ignore_missing=False,
)
if parsed_args.name:
@@ -100,7 +100,8 @@ class CreateServerImage(command.ShowOne):
self.app.stdout.write('\n')
else:
LOG.error(
- _('Error creating server image: %s'), parsed_args.server)
+ _('Error creating server image: %s'), parsed_args.server
+ )
raise exceptions.CommandError
image = image_client.find_image(image_id, ignore_missing=False)
diff --git a/openstackclient/compute/v2/server_migration.py b/openstackclient/compute/v2/server_migration.py
index 91575c1e..6235ae69 100644
--- a/openstackclient/compute/v2/server_migration.py
+++ b/openstackclient/compute/v2/server_migration.py
@@ -31,27 +31,26 @@ class ListMigration(command.Lister):
parser.add_argument(
'--server',
metavar='<server>',
- help=_(
- 'Filter migrations by server (name or ID)'
- )
+ help=_('Filter migrations by server (name or ID)'),
)
parser.add_argument(
'--host',
metavar='<host>',
- help=_(
- 'Filter migrations by source or destination host'
- ),
+ help=_('Filter migrations by source or destination host'),
)
parser.add_argument(
'--status',
metavar='<status>',
- help=_('Filter migrations by status')
+ help=_('Filter migrations by status'),
)
parser.add_argument(
'--type',
metavar='<type>',
choices=[
- 'evacuation', 'live-migration', 'cold-migration', 'resize',
+ 'evacuation',
+ 'live-migration',
+ 'cold-migration',
+ 'resize',
],
help=_('Filter migrations by type'),
)
@@ -121,17 +120,33 @@ class ListMigration(command.Lister):
def print_migrations(self, parsed_args, compute_client, migrations):
column_headers = [
- 'Source Node', 'Dest Node', 'Source Compute', 'Dest Compute',
- 'Dest Host', 'Status', 'Server UUID', 'Old Flavor', 'New Flavor',
- 'Created At', 'Updated At',
+ 'Source Node',
+ 'Dest Node',
+ 'Source Compute',
+ 'Dest Compute',
+ 'Dest Host',
+ 'Status',
+ 'Server UUID',
+ 'Old Flavor',
+ 'New Flavor',
+ 'Created At',
+ 'Updated At',
]
# Response fields coming back from the REST API are not always exactly
# the same as the column header names.
columns = [
- 'source_node', 'dest_node', 'source_compute', 'dest_compute',
- 'dest_host', 'status', 'server_id', 'old_flavor_id',
- 'new_flavor_id', 'created_at', 'updated_at',
+ 'source_node',
+ 'dest_node',
+ 'source_compute',
+ 'dest_compute',
+ 'dest_host',
+ 'status',
+ 'server_id',
+ 'old_flavor_id',
+ 'new_flavor_id',
+ 'created_at',
+ 'updated_at',
]
# Insert migrations UUID after ID
@@ -260,9 +275,7 @@ def _get_migration_by_uuid(compute_client, server_id, migration_uuid):
return migration
break
else:
- msg = _(
- 'In-progress live migration %s is not found for server %s.'
- )
+ msg = _('In-progress live migration %s is not found for server %s.')
raise exceptions.CommandError(msg % (migration_uuid, server_id))
@@ -302,9 +315,7 @@ class ShowMigration(command.ShowOne):
try:
uuid.UUID(parsed_args.migration)
except ValueError:
- msg = _(
- 'The <migration> argument must be an ID or UUID'
- )
+ msg = _('The <migration> argument must be an ID or UUID')
raise exceptions.CommandError(msg)
if not sdk_utils.supports_microversion(compute_client, '2.59'):
@@ -324,7 +335,9 @@ class ShowMigration(command.ShowOne):
# migrations - the responses are identical
if not parsed_args.migration.isdigit():
server_migration = _get_migration_by_uuid(
- compute_client, server.id, parsed_args.migration,
+ compute_client,
+ server.id,
+ parsed_args.migration,
)
else:
server_migration = compute_client.get_server_migration(
@@ -417,9 +430,7 @@ class AbortMigration(command.Command):
try:
uuid.UUID(parsed_args.migration)
except ValueError:
- msg = _(
- 'The <migration> argument must be an ID or UUID'
- )
+ msg = _('The <migration> argument must be an ID or UUID')
raise exceptions.CommandError(msg)
if not sdk_utils.supports_microversion(compute_client, '2.59'):
@@ -440,7 +451,9 @@ class AbortMigration(command.Command):
migration_id = parsed_args.migration
if not parsed_args.migration.isdigit():
migration_id = _get_migration_by_uuid(
- compute_client, server.id, parsed_args.migration,
+ compute_client,
+ server.id,
+ parsed_args.migration,
).id
compute_client.abort_server_migration(
@@ -464,9 +477,7 @@ class ForceCompleteMigration(command.Command):
help=_('Server (name or ID)'),
)
parser.add_argument(
- 'migration',
- metavar='<migration>',
- help=_('Migration (ID)')
+ 'migration', metavar='<migration>', help=_('Migration (ID)')
)
return parser
@@ -484,9 +495,7 @@ class ForceCompleteMigration(command.Command):
try:
uuid.UUID(parsed_args.migration)
except ValueError:
- msg = _(
- 'The <migration> argument must be an ID or UUID'
- )
+ msg = _('The <migration> argument must be an ID or UUID')
raise exceptions.CommandError(msg)
if not sdk_utils.supports_microversion(compute_client, '2.59'):
@@ -507,9 +516,9 @@ class ForceCompleteMigration(command.Command):
migration_id = parsed_args.migration
if not parsed_args.migration.isdigit():
migration_id = _get_migration_by_uuid(
- compute_client, server.id, parsed_args.migration,
+ compute_client,
+ server.id,
+ parsed_args.migration,
).id
- compute_client.force_complete_server_migration(
- migration_id, server.id
- )
+ compute_client.force_complete_server_migration(migration_id, server.id)
diff --git a/openstackclient/compute/v2/service.py b/openstackclient/compute/v2/service.py
index fad717c9..1cf59ab0 100644
--- a/openstackclient/compute/v2/service.py
+++ b/openstackclient/compute/v2/service.py
@@ -37,15 +37,17 @@ class DeleteService(command.Command):
"service",
metavar="<service>",
nargs='+',
- help=_("Compute service(s) to delete (ID only). If using "
- "``--os-compute-api-version`` 2.53 or greater, the ID is "
- "a UUID which can be retrieved by listing compute services "
- "using the same 2.53+ microversion. "
- "If deleting a compute service, be sure to stop the actual "
- "compute process on the physical host before deleting the "
- "service with this command. Failing to do so can lead to "
- "the running service re-creating orphaned compute_nodes "
- "table records in the database.")
+ help=_(
+ "Compute service(s) to delete (ID only). If using "
+ "``--os-compute-api-version`` 2.53 or greater, the ID is "
+ "a UUID which can be retrieved by listing compute services "
+ "using the same 2.53+ microversion. "
+ "If deleting a compute service, be sure to stop the actual "
+ "compute process on the physical host before deleting the "
+ "service with this command. Failing to do so can lead to "
+ "the running service re-creating orphaned compute_nodes "
+ "table records in the database."
+ ),
)
return parser
@@ -54,47 +56,54 @@ class DeleteService(command.Command):
result = 0
for s in parsed_args.service:
try:
- compute_client.delete_service(
- s,
- ignore_missing=False
- )
+ compute_client.delete_service(s, ignore_missing=False)
except Exception as e:
result += 1
- LOG.error(_("Failed to delete compute service with "
- "ID '%(service)s': %(e)s"), {'service': s, 'e': e})
+ LOG.error(
+ _(
+ "Failed to delete compute service with "
+ "ID '%(service)s': %(e)s"
+ ),
+ {'service': s, 'e': e},
+ )
if result > 0:
total = len(parsed_args.service)
- msg = (_("%(result)s of %(total)s compute services failed "
- "to delete.") % {'result': result, 'total': total})
+ msg = _(
+ "%(result)s of %(total)s compute services failed " "to delete."
+ ) % {'result': result, 'total': total}
raise exceptions.CommandError(msg)
class ListService(command.Lister):
- _description = _("""List compute services.
+ _description = _(
+ """List compute services.
Using ``--os-compute-api-version`` 2.53 or greater will return the ID as a UUID
value which can be used to uniquely identify the service in a multi-cell
-deployment.""")
+deployment."""
+ )
def get_parser(self, prog_name):
parser = super(ListService, self).get_parser(prog_name)
parser.add_argument(
"--host",
metavar="<host>",
- help=_("List services on specified host (name only)")
+ help=_("List services on specified host (name only)"),
)
parser.add_argument(
"--service",
metavar="<service>",
- help=_("List only specified service binaries (name only). For "
- "example, ``nova-compute``, ``nova-conductor``, etc.")
+ help=_(
+ "List only specified service binaries (name only). For "
+ "example, ``nova-compute``, ``nova-conductor``, etc."
+ ),
)
parser.add_argument(
"--long",
action="store_true",
default=False,
- help=_("List additional fields in output")
+ help=_("List additional fields in output"),
)
return parser
@@ -126,12 +135,11 @@ deployment.""")
column_headers += ("Forced Down",)
data = compute_client.services(
- host=parsed_args.host,
- binary=parsed_args.service
+ host=parsed_args.host, binary=parsed_args.service
)
return (
column_headers,
- (utils.get_item_properties(s, columns) for s in data)
+ (utils.get_item_properties(s, columns) for s in data),
)
@@ -140,47 +148,47 @@ class SetService(command.Command):
def get_parser(self, prog_name):
parser = super(SetService, self).get_parser(prog_name)
- parser.add_argument(
- "host",
- metavar="<host>",
- help=_("Name of host")
- )
+ parser.add_argument("host", metavar="<host>", help=_("Name of host"))
parser.add_argument(
"service",
metavar="<service>",
- help=_("Name of service (Binary name), for example "
- "``nova-compute``")
+ help=_(
+ "Name of service (Binary name), for example "
+ "``nova-compute``"
+ ),
)
enabled_group = parser.add_mutually_exclusive_group()
enabled_group.add_argument(
- "--enable",
- action="store_true",
- help=_("Enable service")
+ "--enable", action="store_true", help=_("Enable service")
)
enabled_group.add_argument(
- "--disable",
- action="store_true",
- help=_("Disable service")
+ "--disable", action="store_true", help=_("Disable service")
)
parser.add_argument(
"--disable-reason",
default=None,
metavar="<reason>",
- help=_("Reason for disabling the service (in quotes). "
- "Should be used with --disable option.")
+ help=_(
+ "Reason for disabling the service (in quotes). "
+ "Should be used with --disable option."
+ ),
)
up_down_group = parser.add_mutually_exclusive_group()
up_down_group.add_argument(
'--up',
action='store_true',
- help=_('Force up service. Requires ``--os-compute-api-version`` '
- '2.11 or greater.'),
+ help=_(
+ 'Force up service. Requires ``--os-compute-api-version`` '
+ '2.11 or greater.'
+ ),
)
up_down_group.add_argument(
'--down',
action='store_true',
- help=_('Force down service. Requires ``--os-compute-api-version`` '
- '2.11 or greater.'),
+ help=_(
+ 'Force down service. Requires ``--os-compute-api-version`` '
+ '2.11 or greater.'
+ ),
)
return parser
@@ -196,45 +204,49 @@ class SetService(command.Command):
services = list(compute_client.services(host=host, binary=binary))
# Did we find anything?
if not len(services):
- msg = _('Compute service for host "%(host)s" and binary '
- '"%(binary)s" not found.') % {
- 'host': host, 'binary': binary}
+ msg = _(
+ 'Compute service for host "%(host)s" and binary '
+ '"%(binary)s" not found.'
+ ) % {'host': host, 'binary': binary}
raise exceptions.CommandError(msg)
# Did we find more than one result? This should not happen but let's
# be safe.
if len(services) > 1:
# TODO(mriedem): If we have an --id option for 2.53+ then we can
# say to use that option to uniquely identify the service.
- msg = _('Multiple compute services found for host "%(host)s" and '
- 'binary "%(binary)s". Unable to proceed.') % {
- 'host': host, 'binary': binary}
+ msg = _(
+ 'Multiple compute services found for host "%(host)s" and '
+ 'binary "%(binary)s". Unable to proceed.'
+ ) % {'host': host, 'binary': binary}
raise exceptions.CommandError(msg)
return services[0]
def take_action(self, parsed_args):
compute_client = self.app.client_manager.sdk_connection.compute
- if (parsed_args.enable or not parsed_args.disable) and \
- parsed_args.disable_reason:
- msg = _("Cannot specify option --disable-reason without "
- "--disable specified.")
+ if (
+ parsed_args.enable or not parsed_args.disable
+ ) and parsed_args.disable_reason:
+ msg = _(
+ "Cannot specify option --disable-reason without "
+ "--disable specified."
+ )
raise exceptions.CommandError(msg)
# Starting with microversion 2.53, there is a single
# PUT /os-services/{service_id} API for updating nova-compute
# services. If 2.53+ is used we need to find the nova-compute
# service using the --host and --service (binary) values.
- requires_service_id = (
- sdk_utils.supports_microversion(compute_client, '2.53'))
+ requires_service_id = sdk_utils.supports_microversion(
+ compute_client, '2.53'
+ )
service_id = None
if requires_service_id:
# TODO(mriedem): Add an --id option so users can pass the service
# id (as a uuid) directly rather than make us look it up using
# host/binary.
service_id = SetService._find_service_by_host_and_binary(
- compute_client,
- parsed_args.host,
- parsed_args.service
+ compute_client, parsed_args.host, parsed_args.service
).id
result = 0
@@ -248,16 +260,14 @@ class SetService(command.Command):
if enabled is not None:
if enabled:
compute_client.enable_service(
- service_id,
- parsed_args.host,
- parsed_args.service
+ service_id, parsed_args.host, parsed_args.service
)
else:
compute_client.disable_service(
service_id,
parsed_args.host,
parsed_args.service,
- parsed_args.disable_reason
+ parsed_args.disable_reason,
)
except Exception:
status = "enabled" if enabled else "disabled"
@@ -271,15 +281,16 @@ class SetService(command.Command):
force_down = False
if force_down is not None:
if not sdk_utils.supports_microversion(compute_client, '2.11'):
- msg = _('--os-compute-api-version 2.11 or later is '
- 'required')
+ msg = _(
+ '--os-compute-api-version 2.11 or later is ' 'required'
+ )
raise exceptions.CommandError(msg)
try:
compute_client.update_service_forced_down(
service_id,
parsed_args.host,
parsed_args.service,
- force_down
+ force_down,
)
except Exception:
state = "down" if force_down else "up"
@@ -287,7 +298,8 @@ class SetService(command.Command):
result += 1
if result > 0:
- msg = _("Compute service %(service)s of host %(host)s failed to "
- "set.") % {"service": parsed_args.service,
- "host": parsed_args.host}
+ msg = _(
+ "Compute service %(service)s of host %(host)s failed to "
+ "set."
+ ) % {"service": parsed_args.service, "host": parsed_args.host}
raise exceptions.CommandError(msg)
diff --git a/openstackclient/compute/v2/usage.py b/openstackclient/compute/v2/usage.py
index 86f538a7..3b8bda2d 100644
--- a/openstackclient/compute/v2/usage.py
+++ b/openstackclient/compute/v2/usage.py
@@ -54,13 +54,11 @@ class ProjectColumn(cliff_columns.FormattableColumn):
class CountColumn(cliff_columns.FormattableColumn):
-
def human_readable(self):
return len(self._value) if self._value is not None else None
class FloatColumn(cliff_columns.FormattableColumn):
-
def human_readable(self):
return float("%.2f" % self._value)
@@ -68,7 +66,8 @@ class FloatColumn(cliff_columns.FormattableColumn):
def _formatters(project_cache):
return {
'project_id': functools.partial(
- ProjectColumn, project_cache=project_cache),
+ ProjectColumn, project_cache=project_cache
+ ),
'server_usages': CountColumn,
'total_memory_mb_usage': FloatColumn,
'total_vcpus_usage': FloatColumn,
@@ -115,19 +114,20 @@ class ListUsage(command.Lister):
"--start",
metavar="<start>",
default=None,
- help=_("Usage range start date, ex 2012-01-20"
- " (default: 4 weeks ago)")
+ help=_(
+ "Usage range start date, ex 2012-01-20"
+ " (default: 4 weeks ago)"
+ ),
)
parser.add_argument(
"--end",
metavar="<end>",
default=None,
- help=_("Usage range end date, ex 2012-01-20 (default: tomorrow)")
+ help=_("Usage range end date, ex 2012-01-20 (default: tomorrow)"),
)
return parser
def take_action(self, parsed_args):
-
def _format_project(project):
if not project:
return ""
@@ -142,14 +142,14 @@ class ListUsage(command.Lister):
"server_usages",
"total_memory_mb_usage",
"total_vcpus_usage",
- "total_local_gb_usage"
+ "total_local_gb_usage",
)
column_headers = (
"Project",
"Servers",
"RAM MB-Hours",
"CPU Hours",
- "Disk GB-Hours"
+ "Disk GB-Hours",
)
date_cli_format = "%Y-%m-%d"
@@ -158,7 +158,8 @@ class ListUsage(command.Lister):
if parsed_args.start:
start = datetime.datetime.strptime(
- parsed_args.start, date_cli_format)
+ parsed_args.start, date_cli_format
+ )
else:
start = now - datetime.timedelta(weeks=4)
@@ -167,10 +168,13 @@ class ListUsage(command.Lister):
else:
end = now + datetime.timedelta(days=1)
- usage_list = list(compute_client.usages(
- start=start.strftime(date_api_format),
- end=end.strftime(date_api_format),
- detailed=True))
+ usage_list = list(
+ compute_client.usages(
+ start=start.strftime(date_api_format),
+ end=end.strftime(date_api_format),
+ detailed=True,
+ )
+ )
# Cache the project list
project_cache = {}
@@ -182,18 +186,23 @@ class ListUsage(command.Lister):
pass
if parsed_args.formatter == 'table' and len(usage_list) > 0:
- self.app.stdout.write(_("Usage from %(start)s to %(end)s: \n") % {
- "start": start.strftime(date_cli_format),
- "end": end.strftime(date_cli_format),
- })
+ self.app.stdout.write(
+ _("Usage from %(start)s to %(end)s: \n")
+ % {
+ "start": start.strftime(date_cli_format),
+ "end": end.strftime(date_cli_format),
+ }
+ )
return (
column_headers,
(
utils.get_item_properties(
- s, columns,
+ s,
+ columns,
formatters=_formatters(project_cache),
- ) for s in usage_list
+ )
+ for s in usage_list
),
)
@@ -207,20 +216,22 @@ class ShowUsage(command.ShowOne):
"--project",
metavar="<project>",
default=None,
- help=_("Name or ID of project to show usage for")
+ help=_("Name or ID of project to show usage for"),
)
parser.add_argument(
"--start",
metavar="<start>",
default=None,
- help=_("Usage range start date, ex 2012-01-20"
- " (default: 4 weeks ago)")
+ help=_(
+ "Usage range start date, ex 2012-01-20"
+ " (default: 4 weeks ago)"
+ ),
)
parser.add_argument(
"--end",
metavar="<end>",
default=None,
- help=_("Usage range end date, ex 2012-01-20 (default: tomorrow)")
+ help=_("Usage range end date, ex 2012-01-20 (default: tomorrow)"),
)
return parser
@@ -233,7 +244,8 @@ class ShowUsage(command.ShowOne):
if parsed_args.start:
start = datetime.datetime.strptime(
- parsed_args.start, date_cli_format)
+ parsed_args.start, date_cli_format
+ )
else:
start = now - datetime.timedelta(weeks=4)
@@ -252,33 +264,37 @@ class ShowUsage(command.ShowOne):
project = self.app.client_manager.auth_ref.project_id
usage = compute_client.get_usage(
- project=project, start=start.strftime(date_api_format),
- end=end.strftime(date_api_format))
+ project=project,
+ start=start.strftime(date_api_format),
+ end=end.strftime(date_api_format),
+ )
if parsed_args.formatter == 'table':
- self.app.stdout.write(_(
- "Usage from %(start)s to %(end)s on project %(project)s: \n"
- ) % {
- "start": start.strftime(date_cli_format),
- "end": end.strftime(date_cli_format),
- "project": project,
- })
+ self.app.stdout.write(
+ _("Usage from %(start)s to %(end)s on project %(project)s: \n")
+ % {
+ "start": start.strftime(date_cli_format),
+ "end": end.strftime(date_cli_format),
+ "project": project,
+ }
+ )
columns = (
"project_id",
"server_usages",
"total_memory_mb_usage",
"total_vcpus_usage",
- "total_local_gb_usage"
+ "total_local_gb_usage",
)
column_headers = (
"Project",
"Servers",
"RAM MB-Hours",
"CPU Hours",
- "Disk GB-Hours"
+ "Disk GB-Hours",
)
data = utils.get_item_properties(
- usage, columns, formatters=_formatters(None))
+ usage, columns, formatters=_formatters(None)
+ )
return column_headers, data