Fix i18n messages in novaclient, part I

This change make all the text visible by the user i18n. The
messages changes are in prints, logs, exceptions, helps, etc
Pep8 errors about "Multiple positional placeholders" also fixed

Change-Id: I731afea790baddbc34d059b93a35e3d275fc1df8
This commit is contained in:
Sergio Cazzolato 2013-12-12 23:17:28 -05:00
parent eb0b6d167d
commit 6b070c82d4
17 changed files with 132 additions and 108 deletions

View File

@ -15,11 +15,12 @@
# under the License. # under the License.
import logging import logging
import pkg_resources
import pkg_resources
import six import six
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -39,7 +40,7 @@ def discover_auth_systems():
try: try:
auth_plugin = ep.load() auth_plugin = ep.load()
except (ImportError, pkg_resources.UnknownExtra, AttributeError) as e: except (ImportError, pkg_resources.UnknownExtra, AttributeError) as e:
logger.debug("ERROR: Cannot load auth plugin %s" % ep.name) logger.debug(_("ERROR: Cannot load auth plugin %s") % ep.name)
logger.debug(e, exc_info=1) logger.debug(e, exc_info=1)
else: else:
_discovered_plugins[ep.name] = auth_plugin _discovered_plugins[ep.name] = auth_plugin

View File

@ -31,6 +31,7 @@ except ImportError:
import simplejson as json import simplejson as json
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
from novaclient.openstack.common.py3kcompat import urlutils from novaclient.openstack.common.py3kcompat import urlutils
from novaclient import service_catalog from novaclient import service_catalog
from novaclient import utils from novaclient import utils
@ -160,11 +161,10 @@ class HTTPClient(object):
def http_log_resp(self, resp): def http_log_resp(self, resp):
if not self.http_log_debug: if not self.http_log_debug:
return return
self._logger.debug( self._logger.debug(_("RESP: [%(status)s] %(headers)s\nRESP BODY: "
"RESP: [%s] %s\nRESP BODY: %s\n", "%(text)s\n"), {'status': resp.status_code,
resp.status_code, 'headers': resp.headers,
resp.headers, 'text': resp.text})
resp.text)
def request(self, url, method, **kwargs): def request(self, url, method, **kwargs):
kwargs.setdefault('headers', kwargs.get('headers', {})) kwargs.setdefault('headers', kwargs.get('headers', {}))
@ -288,13 +288,14 @@ class HTTPClient(object):
self.management_url = management_url.rstrip('/') self.management_url = management_url.rstrip('/')
return None return None
except exceptions.AmbiguousEndpoints: except exceptions.AmbiguousEndpoints:
print("Found more than one valid endpoint. Use a more " print(_("Found more than one valid endpoint. Use a more "
"restrictive filter") "restrictive filter"))
raise raise
except KeyError: except KeyError:
raise exceptions.AuthorizationFailure() raise exceptions.AuthorizationFailure()
except exceptions.EndpointNotFound: except exceptions.EndpointNotFound:
print("Could not find any suitable endpoint. Correct region?") print(_("Could not find any suitable endpoint. Correct "
"region?"))
raise raise
elif resp.status_code == 305: elif resp.status_code == 305:
@ -317,7 +318,7 @@ class HTTPClient(object):
# GET ...:5001/v2.0/tokens/#####/endpoints # GET ...:5001/v2.0/tokens/#####/endpoints
url = '/'.join([url, 'tokens', '%s?belongsTo=%s' url = '/'.join([url, 'tokens', '%s?belongsTo=%s'
% (self.proxy_token, self.proxy_tenant_id)]) % (self.proxy_token, self.proxy_tenant_id)])
self._logger.debug("Using Endpoint URL: %s" % url) self._logger.debug(_("Using Endpoint URL: %s") % url)
resp, body = self._time_request( resp, body = self._time_request(
url, "GET", headers={'X-Auth-Token': self.auth_token}) url, "GET", headers={'X-Auth-Token': self.auth_token})
return self._extract_service_catalog(url, resp, body, return self._extract_service_catalog(url, resp, body,
@ -463,8 +464,9 @@ def get_client_class(version):
try: try:
client_path = version_map[str(version)] client_path = version_map[str(version)]
except (KeyError, ValueError): except (KeyError, ValueError):
msg = "Invalid client version '%s'. must be one of: %s" % ( msg = _("Invalid client version '%(version)s'. must be one of: "
(version, ', '.join(version_map.keys()))) "%(keys)s") % {'version': version,
'keys': ''.join(version_map.keys())}
raise exceptions.UnsupportedVersion(msg) raise exceptions.UnsupportedVersion(msg)
return utils.import_class(client_path) return utils.import_class(client_path)

View File

@ -102,7 +102,7 @@ def safe_decode(text, incoming=None, errors='strict'):
:raises TypeError: If text is not an instance of str :raises TypeError: If text is not an instance of str
""" """
if not isinstance(text, six.string_types): if not isinstance(text, six.string_types):
raise TypeError("%s can't be decoded" % type(text)) raise TypeError(_("%s can't be decoded") % type(text))
if isinstance(text, six.text_type): if isinstance(text, six.text_type):
return text return text
@ -145,7 +145,7 @@ def safe_encode(text, incoming=None,
:raises TypeError: If text is not an instance of str :raises TypeError: If text is not an instance of str
""" """
if not isinstance(text, six.string_types): if not isinstance(text, six.string_types):
raise TypeError("%s can't be encoded" % type(text)) raise TypeError(_("%s can't be encoded") % type(text))
if not incoming: if not incoming:
incoming = (sys.stdin.encoding or incoming = (sys.stdin.encoding or

View File

@ -46,6 +46,7 @@ from novaclient import client
from novaclient import exceptions as exc from novaclient import exceptions as exc
import novaclient.extension import novaclient.extension
from novaclient.openstack.common import cliutils from novaclient.openstack.common import cliutils
from novaclient.openstack.common.gettextutils import _
from novaclient.openstack.common import strutils from novaclient.openstack.common import strutils
from novaclient import utils from novaclient import utils
from novaclient.v1_1 import shell as shell_v1_1 from novaclient.v1_1 import shell as shell_v1_1
@ -70,10 +71,10 @@ def positive_non_zero_float(text):
try: try:
value = float(text) value = float(text)
except ValueError: except ValueError:
msg = "%s must be a float" % text msg = _("%s must be a float") % text
raise argparse.ArgumentTypeError(msg) raise argparse.ArgumentTypeError(msg)
if value <= 0: if value <= 0:
msg = "%s must be greater than 0" % text msg = _("%s must be greater than 0") % text
raise argparse.ArgumentTypeError(msg) raise argparse.ArgumentTypeError(msg)
return value return value
@ -137,7 +138,8 @@ class SecretsHelper(object):
# Nothing changed.... # Nothing changed....
return return
if not all([management_url, auth_token, tenant_id]): if not all([management_url, auth_token, tenant_id]):
raise ValueError("Unable to save empty management url/auth token") raise ValueError(_("Unable to save empty management url/auth "
"token"))
value = "|".join([str(auth_token), value = "|".join([str(auth_token),
str(management_url), str(management_url),
str(tenant_id)]) str(tenant_id)])
@ -220,8 +222,8 @@ class NovaClientArgumentParser(argparse.ArgumentParser):
#FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value #FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value
choose_from = ' (choose from' choose_from = ' (choose from'
progparts = self.prog.partition(' ') progparts = self.prog.partition(' ')
self.exit(2, "error: %(errmsg)s\nTry '%(mainp)s help %(subp)s'" self.exit(2, _("error: %(errmsg)s\nTry '%(mainp)s help %(subp)s'"
" for more information.\n" % " for more information.\n") %
{'errmsg': message.split(choose_from)[0], {'errmsg': message.split(choose_from)[0],
'mainp': progparts[0], 'mainp': progparts[0],
'subp': progparts[2]}) 'subp': progparts[2]})
@ -252,25 +254,25 @@ class OpenStackComputeShell(object):
parser.add_argument('--debug', parser.add_argument('--debug',
default=False, default=False,
action='store_true', action='store_true',
help="Print debugging output") help=_("Print debugging output"))
parser.add_argument('--os-cache', parser.add_argument('--os-cache',
default=strutils.bool_from_string( default=strutils.bool_from_string(
utils.env('OS_CACHE', default=False), True), utils.env('OS_CACHE', default=False), True),
action='store_true', action='store_true',
help="Use the auth token cache. Defaults to False if env[OS_CACHE]" help=_("Use the auth token cache. Defaults to False if "
" is not set.") "env[OS_CACHE] is not set."))
parser.add_argument('--timings', parser.add_argument('--timings',
default=False, default=False,
action='store_true', action='store_true',
help="Print call timing info") help=_("Print call timing info"))
parser.add_argument('--timeout', parser.add_argument('--timeout',
default=600, default=600,
metavar='<seconds>', metavar='<seconds>',
type=positive_non_zero_float, type=positive_non_zero_float,
help="Set HTTP call timeout (in seconds)") help=_("Set HTTP call timeout (in seconds)"))
parser.add_argument('--os-auth-token', parser.add_argument('--os-auth-token',
default=utils.env('OS_AUTH_TOKEN'), default=utils.env('OS_AUTH_TOKEN'),
@ -279,40 +281,40 @@ class OpenStackComputeShell(object):
parser.add_argument('--os-username', parser.add_argument('--os-username',
metavar='<auth-user-name>', metavar='<auth-user-name>',
default=utils.env('OS_USERNAME', 'NOVA_USERNAME'), default=utils.env('OS_USERNAME', 'NOVA_USERNAME'),
help='Defaults to env[OS_USERNAME].') help=_('Defaults to env[OS_USERNAME].'))
parser.add_argument('--os_username', parser.add_argument('--os_username',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--os-password', parser.add_argument('--os-password',
metavar='<auth-password>', metavar='<auth-password>',
default=utils.env('OS_PASSWORD', 'NOVA_PASSWORD'), default=utils.env('OS_PASSWORD', 'NOVA_PASSWORD'),
help='Defaults to env[OS_PASSWORD].') help=_('Defaults to env[OS_PASSWORD].'))
parser.add_argument('--os_password', parser.add_argument('--os_password',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--os-tenant-name', parser.add_argument('--os-tenant-name',
metavar='<auth-tenant-name>', metavar='<auth-tenant-name>',
default=utils.env('OS_TENANT_NAME', 'NOVA_PROJECT_ID'), default=utils.env('OS_TENANT_NAME', 'NOVA_PROJECT_ID'),
help='Defaults to env[OS_TENANT_NAME].') help=_('Defaults to env[OS_TENANT_NAME].'))
parser.add_argument('--os_tenant_name', parser.add_argument('--os_tenant_name',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--os-tenant-id', parser.add_argument('--os-tenant-id',
metavar='<auth-tenant-id>', metavar='<auth-tenant-id>',
default=utils.env('OS_TENANT_ID'), default=utils.env('OS_TENANT_ID'),
help='Defaults to env[OS_TENANT_ID].') help=_('Defaults to env[OS_TENANT_ID].'))
parser.add_argument('--os-auth-url', parser.add_argument('--os-auth-url',
metavar='<auth-url>', metavar='<auth-url>',
default=utils.env('OS_AUTH_URL', 'NOVA_URL'), default=utils.env('OS_AUTH_URL', 'NOVA_URL'),
help='Defaults to env[OS_AUTH_URL].') help=_('Defaults to env[OS_AUTH_URL].'))
parser.add_argument('--os_auth_url', parser.add_argument('--os_auth_url',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--os-region-name', parser.add_argument('--os-region-name',
metavar='<region-name>', metavar='<region-name>',
default=utils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'), default=utils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'),
help='Defaults to env[OS_REGION_NAME].') help=_('Defaults to env[OS_REGION_NAME].'))
parser.add_argument('--os_region_name', parser.add_argument('--os_region_name',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
@ -325,21 +327,21 @@ class OpenStackComputeShell(object):
parser.add_argument('--service-type', parser.add_argument('--service-type',
metavar='<service-type>', metavar='<service-type>',
help='Defaults to compute for most actions') help=_('Defaults to compute for most actions'))
parser.add_argument('--service_type', parser.add_argument('--service_type',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--service-name', parser.add_argument('--service-name',
metavar='<service-name>', metavar='<service-name>',
default=utils.env('NOVA_SERVICE_NAME'), default=utils.env('NOVA_SERVICE_NAME'),
help='Defaults to env[NOVA_SERVICE_NAME]') help=_('Defaults to env[NOVA_SERVICE_NAME]'))
parser.add_argument('--service_name', parser.add_argument('--service_name',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
parser.add_argument('--volume-service-name', parser.add_argument('--volume-service-name',
metavar='<volume-service-name>', metavar='<volume-service-name>',
default=utils.env('NOVA_VOLUME_SERVICE_NAME'), default=utils.env('NOVA_VOLUME_SERVICE_NAME'),
help='Defaults to env[NOVA_VOLUME_SERVICE_NAME]') help=_('Defaults to env[NOVA_VOLUME_SERVICE_NAME]'))
parser.add_argument('--volume_service_name', parser.add_argument('--volume_service_name',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
@ -347,7 +349,7 @@ class OpenStackComputeShell(object):
metavar='<endpoint-type>', metavar='<endpoint-type>',
default=utils.env('NOVA_ENDPOINT_TYPE', default=utils.env('NOVA_ENDPOINT_TYPE',
default=DEFAULT_NOVA_ENDPOINT_TYPE), default=DEFAULT_NOVA_ENDPOINT_TYPE),
help='Defaults to env[NOVA_ENDPOINT_TYPE] or ' help=_('Defaults to env[NOVA_ENDPOINT_TYPE] or ')
+ DEFAULT_NOVA_ENDPOINT_TYPE + '.') + DEFAULT_NOVA_ENDPOINT_TYPE + '.')
# NOTE(dtroyer): We can't add --endpoint_type here due to argparse # NOTE(dtroyer): We can't add --endpoint_type here due to argparse
# thinking usage-list --end is ambiguous; but it # thinking usage-list --end is ambiguous; but it
@ -360,8 +362,8 @@ class OpenStackComputeShell(object):
metavar='<compute-api-ver>', metavar='<compute-api-ver>',
default=utils.env('OS_COMPUTE_API_VERSION', default=utils.env('OS_COMPUTE_API_VERSION',
default=DEFAULT_OS_COMPUTE_API_VERSION), default=DEFAULT_OS_COMPUTE_API_VERSION),
help='Accepts 1.1 or 3, ' help=_('Accepts 1.1 or 3, '
'defaults to env[OS_COMPUTE_API_VERSION].') 'defaults to env[OS_COMPUTE_API_VERSION].'))
parser.add_argument('--os_compute_api_version', parser.add_argument('--os_compute_api_version',
help=argparse.SUPPRESS) help=argparse.SUPPRESS)
@ -375,10 +377,10 @@ class OpenStackComputeShell(object):
parser.add_argument('--insecure', parser.add_argument('--insecure',
default=utils.env('NOVACLIENT_INSECURE', default=False), default=utils.env('NOVACLIENT_INSECURE', default=False),
action='store_true', action='store_true',
help="Explicitly allow novaclient to perform \"insecure\" " help=_("Explicitly allow novaclient to perform \"insecure\" "
"SSL (https) requests. The server's certificate will " "SSL (https) requests. The server's certificate will "
"not be verified against any certificate authorities. " "not be verified against any certificate authorities. "
"This option should be used with caution.") "This option should be used with caution."))
parser.add_argument('--bypass-url', parser.add_argument('--bypass-url',
metavar='<bypass-url>', metavar='<bypass-url>',
@ -605,37 +607,37 @@ class OpenStackComputeShell(object):
if not auth_plugin or not auth_plugin.opts: if not auth_plugin or not auth_plugin.opts:
if not os_username: if not os_username:
raise exc.CommandError("You must provide a username " raise exc.CommandError(_("You must provide a username "
"via either --os-username or env[OS_USERNAME]") "via either --os-username or env[OS_USERNAME]"))
if not os_tenant_name and not os_tenant_id: if not os_tenant_name and not os_tenant_id:
raise exc.CommandError("You must provide a tenant name " raise exc.CommandError(_("You must provide a tenant name "
"or tenant id via --os-tenant-name, " "or tenant id via --os-tenant-name, "
"--os-tenant-id, env[OS_TENANT_NAME] " "--os-tenant-id, env[OS_TENANT_NAME] "
"or env[OS_TENANT_ID]") "or env[OS_TENANT_ID]"))
if not os_auth_url: if not os_auth_url:
if os_auth_system and os_auth_system != 'keystone': if os_auth_system and os_auth_system != 'keystone':
os_auth_url = auth_plugin.get_auth_url() os_auth_url = auth_plugin.get_auth_url()
if not os_auth_url: if not os_auth_url:
raise exc.CommandError("You must provide an auth url " raise exc.CommandError(_("You must provide an auth url "
"via either --os-auth-url or env[OS_AUTH_URL] " "via either --os-auth-url or env[OS_AUTH_URL] "
"or specify an auth_system which defines a " "or specify an auth_system which defines a "
"default url with --os-auth-system " "default url with --os-auth-system "
"or env[OS_AUTH_SYSTEM]") "or env[OS_AUTH_SYSTEM]"))
if (options.os_compute_api_version and if (options.os_compute_api_version and
options.os_compute_api_version != '1.0'): options.os_compute_api_version != '1.0'):
if not os_tenant_name and not os_tenant_id: if not os_tenant_name and not os_tenant_id:
raise exc.CommandError("You must provide a tenant name " raise exc.CommandError(_("You must provide a tenant name "
"or tenant id via --os-tenant-name, " "or tenant id via --os-tenant-name, "
"--os-tenant-id, env[OS_TENANT_NAME] " "--os-tenant-id, env[OS_TENANT_NAME] "
"or env[OS_TENANT_ID]") "or env[OS_TENANT_ID]"))
if not os_auth_url: if not os_auth_url:
raise exc.CommandError("You must provide an auth url " raise exc.CommandError(_("You must provide an auth url "
"via either --os-auth-url or env[OS_AUTH_URL]") "via either --os-auth-url or env[OS_AUTH_URL]"))
self.cs = client.Client(options.os_compute_api_version, os_username, self.cs = client.Client(options.os_compute_api_version, os_username,
os_password, os_tenant_name, tenant_id=os_tenant_id, os_password, os_tenant_name, tenant_id=os_tenant_id,
@ -682,9 +684,9 @@ class OpenStackComputeShell(object):
if not cliutils.isunauthenticated(args.func): if not cliutils.isunauthenticated(args.func):
self.cs.authenticate() self.cs.authenticate()
except exc.Unauthorized: except exc.Unauthorized:
raise exc.CommandError("Invalid OpenStack Nova credentials.") raise exc.CommandError(_("Invalid OpenStack Nova credentials."))
except exc.AuthorizationFailure: except exc.AuthorizationFailure:
raise exc.CommandError("Unable to authorize user") raise exc.CommandError(_("Unable to authorize user"))
args.func(self.cs, args) args.func(self.cs, args)
@ -734,7 +736,7 @@ class OpenStackComputeShell(object):
if args.command in self.subcommands: if args.command in self.subcommands:
self.subcommands[args.command].print_help() self.subcommands[args.command].print_help()
else: else:
raise exc.CommandError("'%s' is not a valid subcommand" % raise exc.CommandError(_("'%s' is not a valid subcommand") %
args.command) args.command)
else: else:
self.parser.print_help() self.parser.print_help()

View File

@ -22,6 +22,7 @@ import six
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common import cliutils from novaclient.openstack.common import cliutils
from novaclient.openstack.common.gettextutils import _
from novaclient.openstack.common import jsonutils from novaclient.openstack.common import jsonutils
from novaclient.openstack.common import strutils from novaclient.openstack.common import strutils
@ -56,8 +57,8 @@ def get_resource_manager_extra_kwargs(f, args, allow_conflicts=False):
conflicting_keys = set(hook_kwargs.keys()) & set(extra_kwargs.keys()) conflicting_keys = set(hook_kwargs.keys()) & set(extra_kwargs.keys())
if conflicting_keys and not allow_conflicts: if conflicting_keys and not allow_conflicts:
raise Exception("Hook '%(hook_name)s' is attempting to redefine" raise Exception(_("Hook '%(hook_name)s' is attempting to redefine"
" attributes '%(conflicting_keys)s'" % " attributes '%(conflicting_keys)s'") %
{'hook_name': hook_name, {'hook_name': hook_name,
'conflicting_keys': conflicting_keys}) 'conflicting_keys': conflicting_keys})
@ -234,13 +235,15 @@ def find_resource(manager, name_or_id, **find_args):
kwargs.update(find_args) kwargs.update(find_args)
return manager.find(**kwargs) return manager.find(**kwargs)
except exceptions.NotFound: except exceptions.NotFound:
msg = "No %s with a name or ID of '%s' exists." % \ msg = _("No %(class)s with a name or ID of '%(name)s' exists.") % \
(manager.resource_class.__name__.lower(), name_or_id) {'class': manager.resource_class.__name__.lower(),
'name': name_or_id}
raise exceptions.CommandError(msg) raise exceptions.CommandError(msg)
except exceptions.NoUniqueMatch: except exceptions.NoUniqueMatch:
msg = ("Multiple %s matches found for '%s', use an ID to be more" msg = (_("Multiple %(class)s matches found for '%(name)s', use an ID "
" specific." % (manager.resource_class.__name__.lower(), "to be more specific.") %
name_or_id)) {'class': manager.resource_class.__name__.lower(),
'name': name_or_id})
raise exceptions.CommandError(msg) raise exceptions.CommandError(msg)

View File

@ -17,6 +17,7 @@
Baremetal interface (v2 extension). Baremetal interface (v2 extension).
""" """
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -151,35 +152,36 @@ class BareMetalNodeManager(base.ManagerWithFind):
@utils.arg('service_host', @utils.arg('service_host',
metavar='<service_host>', metavar='<service_host>',
help='Name of nova compute host which will control this baremetal node') help=_('Name of nova compute host which will control this baremetal '
'node'))
@utils.arg('cpus', @utils.arg('cpus',
metavar='<cpus>', metavar='<cpus>',
type=int, type=int,
help='Number of CPUs in the node') help=_('Number of CPUs in the node'))
@utils.arg('memory_mb', @utils.arg('memory_mb',
metavar='<memory_mb>', metavar='<memory_mb>',
type=int, type=int,
help='Megabytes of RAM in the node') help=_('Megabytes of RAM in the node'))
@utils.arg('local_gb', @utils.arg('local_gb',
metavar='<local_gb>', metavar='<local_gb>',
type=int, type=int,
help='Gigabytes of local storage in the node') help=_('Gigabytes of local storage in the node'))
@utils.arg('prov_mac_address', @utils.arg('prov_mac_address',
metavar='<prov_mac_address>', metavar='<prov_mac_address>',
help='MAC address to provision the node') help=_('MAC address to provision the node'))
@utils.arg('--pm_address', default=None, @utils.arg('--pm_address', default=None,
metavar='<pm_address>', metavar='<pm_address>',
help='Power management IP for the node') help=_('Power management IP for the node'))
@utils.arg('--pm_user', default=None, @utils.arg('--pm_user', default=None,
metavar='<pm_user>', metavar='<pm_user>',
help='Username for the node\'s power management') help=_('Username for the node\'s power management'))
@utils.arg('--pm_password', default=None, @utils.arg('--pm_password', default=None,
metavar='<pm_password>', metavar='<pm_password>',
help='Password for the node\'s power management') help=_('Password for the node\'s power management'))
@utils.arg('--terminal_port', default=None, @utils.arg('--terminal_port', default=None,
metavar='<terminal_port>', metavar='<terminal_port>',
type=int, type=int,
help='ShellInABox port?') help=_('ShellInABox port?'))
def do_baremetal_node_create(cs, args): def do_baremetal_node_create(cs, args):
"""Create a baremetal node.""" """Create a baremetal node."""
node = cs.baremetal.create(args.service_host, args.cpus, node = cs.baremetal.create(args.service_host, args.cpus,
@ -270,18 +272,18 @@ def do_baremetal_node_show(cs, args):
@utils.arg('node', @utils.arg('node',
metavar='<node>', metavar='<node>',
help="ID of node") help=_("ID of node"))
@utils.arg('address', @utils.arg('address',
metavar='<address>', metavar='<address>',
help="MAC address of interface") help=_("MAC address of interface"))
@utils.arg('--datapath_id', @utils.arg('--datapath_id',
default=0, default=0,
metavar='<datapath_id>', metavar='<datapath_id>',
help="OpenFlow Datapath ID of interface") help=_("OpenFlow Datapath ID of interface"))
@utils.arg('--port_no', @utils.arg('--port_no',
default=0, default=0,
metavar='<port_no>', metavar='<port_no>',
help="OpenFlow port number of interface") help=_("OpenFlow port number of interface"))
def do_baremetal_interface_add(cs, args): def do_baremetal_interface_add(cs, args):
"""Add a network interface to a baremetal node.""" """Add a network interface to a baremetal node."""
bmif = cs.baremetal.add_interface(args.node, args.address, bmif = cs.baremetal.add_interface(args.node, args.address,
@ -289,8 +291,8 @@ def do_baremetal_interface_add(cs, args):
_print_baremetal_resource(bmif) _print_baremetal_resource(bmif)
@utils.arg('node', metavar='<node>', help="ID of node") @utils.arg('node', metavar='<node>', help=_("ID of node"))
@utils.arg('address', metavar='<address>', help="MAC address of interface") @utils.arg('address', metavar='<address>', help=_("MAC address of interface"))
def do_baremetal_interface_remove(cs, args): def do_baremetal_interface_remove(cs, args):
"""Remove a network interface from a baremetal node.""" """Remove a network interface from a baremetal node."""
cs.baremetal.remove_interface(args.node, args.address) cs.baremetal.remove_interface(args.node, args.address)

View File

@ -14,6 +14,7 @@
# under the License. # under the License.
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -47,7 +48,7 @@ class CellsManager(base.Manager):
@utils.arg('cell', @utils.arg('cell',
metavar='<cell-name>', metavar='<cell-name>',
help='Name of the cell.') help=_('Name of the cell.'))
def do_cell_show(cs, args): def do_cell_show(cs, args):
"""Show details of a given cell.""" """Show details of a given cell."""
cell = cs.cells.get(args.cell) cell = cs.cells.get(args.cell)
@ -56,14 +57,15 @@ def do_cell_show(cs, args):
@utils.arg('--cell', @utils.arg('--cell',
metavar='<cell-name>', metavar='<cell-name>',
help="Name of the cell to get the capacities.", help=_("Name of the cell to get the capacities."),
default=None) default=None)
def do_cell_capacities(cs, args): def do_cell_capacities(cs, args):
"""Get cell capacities for all cells or a given cell.""" """Get cell capacities for all cells or a given cell."""
cell = cs.cells.capacities(args.cell) cell = cs.cells.capacities(args.cell)
print("Ram Available: %s MB" % cell.capacities['ram_free']['total_mb']) print(_("Ram Available: %s MB") % cell.capacities['ram_free']['total_mb'])
utils.print_dict(cell.capacities['ram_free']['units_by_mb'], utils.print_dict(cell.capacities['ram_free']['units_by_mb'],
dict_property='Ram(MB)', dict_value="Units") dict_property='Ram(MB)', dict_value="Units")
print("\nDisk Available: %s MB" % cell.capacities['disk_free']['total_mb']) print(_("\nDisk Available: %s MB") %
cell.capacities['disk_free']['total_mb'])
utils.print_dict(cell.capacities['disk_free']['units_by_mb'], utils.print_dict(cell.capacities['disk_free']['units_by_mb'],
dict_property='Disk(MB)', dict_value="Units") dict_property='Disk(MB)', dict_value="Units")

View File

@ -14,6 +14,7 @@
# under the License. # under the License.
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -29,7 +30,7 @@ def _server_evacuate(cs, server, args):
args.on_shared_storage) args.on_shared_storage)
except Exception as e: except Exception as e:
success = False success = False
error_message = "Error while evacuating instance: %s" % e error_message = _("Error while evacuating instance: %s") % e
return EvacuateHostResponse(base.Manager, return EvacuateHostResponse(base.Manager,
{"server_uuid": server['uuid'], {"server_uuid": server['uuid'],
"evacuate_accepted": success, "evacuate_accepted": success,
@ -40,12 +41,13 @@ def _server_evacuate(cs, server, args):
@utils.arg('--target_host', @utils.arg('--target_host',
metavar='<target_host>', metavar='<target_host>',
default=None, default=None,
help='Name of target host.') help=_('Name of target host.'))
@utils.arg('--on-shared-storage', @utils.arg('--on-shared-storage',
dest='on_shared_storage', dest='on_shared_storage',
action="store_true", action="store_true",
default=False, default=False,
help='Specifies whether all instances files are on shared storage') help=_('Specifies whether all instances files are on shared '
' storage'))
def do_host_evacuate(cs, args): def do_host_evacuate(cs, args):
"""Evacuate all instances from failed host to specified one.""" """Evacuate all instances from failed host to specified one."""
hypervisors = cs.hypervisors.search(args.host, servers=True) hypervisors = cs.hypervisors.search(args.host, servers=True)

View File

@ -14,6 +14,7 @@
# under the License. # under the License.
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -28,7 +29,7 @@ def _server_migrate(cs, server):
cs.servers.migrate(server['uuid']) cs.servers.migrate(server['uuid'])
except Exception as e: except Exception as e:
success = False success = False
error_message = "Error while migrating instance: %s" % e error_message = _("Error while migrating instance: %s") % e
return HostServersMigrateResponse(base.Manager, return HostServersMigrateResponse(base.Manager,
{"server_uuid": server['uuid'], {"server_uuid": server['uuid'],
"migration_accepted": success, "migration_accepted": success,

View File

@ -16,6 +16,7 @@
import pprint import pprint
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -41,10 +42,10 @@ class InstanceActionManager(base.ManagerWithFind):
@utils.arg('server', @utils.arg('server',
metavar='<server>', metavar='<server>',
help='Name or UUID of the server to show an action for.') help=_('Name or UUID of the server to show an action for.'))
@utils.arg('request_id', @utils.arg('request_id',
metavar='<request_id>', metavar='<request_id>',
help='Request ID of the action to get.') help=_('Request ID of the action to get.'))
def do_instance_action(cs, args): def do_instance_action(cs, args):
"""Show an action.""" """Show an action."""
server = utils.find_resource(cs.servers, args.server) server = utils.find_resource(cs.servers, args.server)
@ -57,7 +58,7 @@ def do_instance_action(cs, args):
@utils.arg('server', @utils.arg('server',
metavar='<server>', metavar='<server>',
help='Name or UUID of the server to list actions for.') help=_('Name or UUID of the server to list actions for.'))
def do_instance_action_list(cs, args): def do_instance_action_list(cs, args):
"""List actions on a server.""" """List actions on a server."""
server = utils.find_resource(cs.servers, args.server) server = utils.find_resource(cs.servers, args.server)

View File

@ -13,23 +13,25 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
from novaclient.v1_1 import shell from novaclient.v1_1 import shell
@utils.arg('host', @utils.arg('host',
metavar='<host>', metavar='<host>',
help='Name of host.') help=_('Name of host.'))
@utils.arg('action', @utils.arg('action',
metavar='<action>', metavar='<action>',
choices=['set', 'delete'], choices=['set', 'delete'],
help="Actions: 'set' or 'delete'") help=_("Actions: 'set' or 'delete'"))
@utils.arg('metadata', @utils.arg('metadata',
metavar='<key=value>', metavar='<key=value>',
nargs='+', nargs='+',
action='append', action='append',
default=[], default=[],
help='Metadata to set or delete (only key is necessary on delete)') help=_('Metadata to set or delete (only key is necessary on '
'delete)'))
def do_host_meta(cs, args): def do_host_meta(cs, args):
"""Set or Delete metadata on all instances of a host.""" """Set or Delete metadata on all instances of a host."""
hypervisors = cs.hypervisors.search(args.host, servers=True) hypervisors = cs.hypervisors.search(args.host, servers=True)

View File

@ -15,6 +15,7 @@ migration interface
""" """
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient.openstack.common.py3kcompat import urlutils from novaclient.openstack.common.py3kcompat import urlutils
from novaclient import utils from novaclient import utils
@ -54,15 +55,15 @@ class MigrationManager(base.ManagerWithFind):
@utils.arg('--host', @utils.arg('--host',
dest='host', dest='host',
metavar='<host>', metavar='<host>',
help='Fetch migrations for the given host.') help=_('Fetch migrations for the given host.'))
@utils.arg('--status', @utils.arg('--status',
dest='status', dest='status',
metavar='<status>', metavar='<status>',
help='Fetch migrations for the given status.') help=_('Fetch migrations for the given status.'))
@utils.arg('--cell_name', @utils.arg('--cell_name',
dest='cell_name', dest='cell_name',
metavar='<cell_name>', metavar='<cell_name>',
help='Fetch migrations for the given cell_name.') help=_('Fetch migrations for the given cell_name.'))
def do_migration_list(cs, args): def do_migration_list(cs, args):
"""Print a list of migrations.""" """Print a list of migrations."""
_print_migrations(cs.migrations.list(args.host, args.status, _print_migrations(cs.migrations.list(args.host, args.status,

View File

@ -13,6 +13,7 @@
# limitations under the License. # limitations under the License.
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
from novaclient import utils from novaclient import utils
@ -57,10 +58,10 @@ def do_net_list(cs, args):
@utils.arg('label', metavar='<network_label>', @utils.arg('label', metavar='<network_label>',
help='Network label (ex. my_new_network)') help=_('Network label (ex. my_new_network)'))
@utils.arg('cidr', metavar='<cidr>', @utils.arg('cidr', metavar='<cidr>',
help='IP block to allocate from (ex. 172.16.0.0/24 or ' help=_('IP block to allocate from (ex. 172.16.0.0/24 or '
'2001:DB8::/64)') '2001:DB8::/64)'))
def do_net_create(cs, args): def do_net_create(cs, args):
""" """
Create a network Create a network

View File

@ -16,6 +16,7 @@
"""Flavor access interface.""" """Flavor access interface."""
from novaclient import base from novaclient import base
from novaclient.openstack.common.gettextutils import _
class FlavorAccess(base.Resource): class FlavorAccess(base.Resource):
@ -35,7 +36,7 @@ class FlavorAccessManager(base.ManagerWithFind):
elif kwargs.get('tenant', None): elif kwargs.get('tenant', None):
return self._list_by_tenant(kwargs['tenant']) return self._list_by_tenant(kwargs['tenant'])
else: else:
raise NotImplementedError('Unknown list options.') raise NotImplementedError(_('Unknown list options.'))
def _list_by_flavor(self, flavor): def _list_by_flavor(self, flavor):
return self._list('/flavors/%s/os-flavor-access' % base.getid(flavor), return self._list('/flavors/%s/os-flavor-access' % base.getid(flavor),
@ -45,7 +46,7 @@ class FlavorAccessManager(base.ManagerWithFind):
"""Print flavor list shared with the given tenant.""" """Print flavor list shared with the given tenant."""
# TODO(uni): need to figure out a proper URI for list_by_tenant # TODO(uni): need to figure out a proper URI for list_by_tenant
# since current API already provided current tenant_id information # since current API already provided current tenant_id information
raise NotImplementedError('Sorry, query by tenant not supported.') raise NotImplementedError(_('Sorry, query by tenant not supported.'))
def add_tenant_access(self, flavor, tenant): def add_tenant_access(self, flavor, tenant):
"""Add a tenant to the given flavor access list.""" """Add a tenant to the given flavor access list."""

View File

@ -17,6 +17,7 @@ Flavor interface.
""" """
from novaclient import base from novaclient import base
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
from novaclient.openstack.common.py3kcompat import urlutils from novaclient.openstack.common.py3kcompat import urlutils
from novaclient.openstack.common import strutils from novaclient.openstack.common import strutils
@ -168,15 +169,15 @@ class FlavorManager(base.ManagerWithFind):
try: try:
ram = int(ram) ram = int(ram)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("Ram must be an integer.") raise exceptions.CommandError(_("Ram must be an integer."))
try: try:
vcpus = int(vcpus) vcpus = int(vcpus)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("VCPUs must be an integer.") raise exceptions.CommandError(_("VCPUs must be an integer."))
try: try:
disk = int(disk) disk = int(disk)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("Disk must be an integer.") raise exceptions.CommandError(_("Disk must be an integer."))
if flavorid == "auto": if flavorid == "auto":
flavorid = None flavorid = None
@ -184,20 +185,20 @@ class FlavorManager(base.ManagerWithFind):
try: try:
swap = int(swap) swap = int(swap)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("Swap must be an integer.") raise exceptions.CommandError(_("Swap must be an integer."))
try: try:
ephemeral = int(ephemeral) ephemeral = int(ephemeral)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("Ephemeral must be an integer.") raise exceptions.CommandError(_("Ephemeral must be an integer."))
try: try:
rxtx_factor = float(rxtx_factor) rxtx_factor = float(rxtx_factor)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("rxtx_factor must be a float.") raise exceptions.CommandError(_("rxtx_factor must be a float."))
try: try:
is_public = strutils.bool_from_string(is_public, True) is_public = strutils.bool_from_string(is_public, True)
except Exception: except Exception:
raise exceptions.CommandError("is_public must be a boolean.") raise exceptions.CommandError(_("is_public must be a boolean."))
body = self._build_body(name, ram, vcpus, disk, flavorid, swap, body = self._build_body(name, ram, vcpus, disk, flavorid, swap,
ephemeral, rxtx_factor, is_public) ephemeral, rxtx_factor, is_public)

View File

@ -19,6 +19,7 @@ Network interface.
from novaclient import base from novaclient import base
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
class Network(base.Resource): class Network(base.Resource):
@ -110,7 +111,7 @@ class NetworkManager(base.ManagerWithFind):
body = {"disassociate_host": None} body = {"disassociate_host": None}
else: else:
raise exceptions.CommandError( raise exceptions.CommandError(
"Must disassociate either host or project or both") _("Must disassociate either host or project or both"))
self.api.client.post("/os-networks/%s/action" % self.api.client.post("/os-networks/%s/action" %
base.getid(network), body=body) base.getid(network), body=body)

View File

@ -19,6 +19,7 @@ Security group rules interface (1.1 extension).
from novaclient import base from novaclient import base
from novaclient import exceptions from novaclient import exceptions
from novaclient.openstack.common.gettextutils import _
class SecurityGroupRule(base.Resource): class SecurityGroupRule(base.Resource):
@ -48,14 +49,14 @@ class SecurityGroupRuleManager(base.Manager):
try: try:
from_port = int(from_port) from_port = int(from_port)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("From port must be an integer.") raise exceptions.CommandError(_("From port must be an integer."))
try: try:
to_port = int(to_port) to_port = int(to_port)
except (TypeError, ValueError): except (TypeError, ValueError):
raise exceptions.CommandError("To port must be an integer.") raise exceptions.CommandError(_("To port must be an integer."))
if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']: if ip_protocol.upper() not in ['TCP', 'UDP', 'ICMP']:
raise exceptions.CommandError("Ip protocol must be 'tcp', 'udp', " raise exceptions.CommandError(_("Ip protocol must be 'tcp', 'udp'"
"or 'icmp'.") ", or 'icmp'."))
body = {"security_group_rule": { body = {"security_group_rule": {
"ip_protocol": ip_protocol, "ip_protocol": ip_protocol,