Improve Rally Logging (part 2)

- Remove translations

  Nobody is using translations for Rally and I don't think that
  anybody is going to use it. Target auditory for Rally are
  developers/operators which usually know well english.
  For me this looks like waste of resources, performance
  degradation (cause we are calling _()), complexity
  (+1 thing that you need to know)

- Pass to log already formatted strings

  It's very bad because in case of wrong formatting, it
  doesn't fail instead just writes errors to the logs,
  as well information about trace is lost, so it's super
  hard to fix it

  Log wrapper doesn't allow to use LOG anymore for
  formatting strings

  All places are fixed

- Improve logging of exceptions

LOG.exception() already logs exception, which means it's bad idea to
pass str(e) to it. Instead we should provide clear description of what
happend. Improved few places to write warnings or exceptions in case
of different level of logs. In few places just use LOG.exception

- Part of log messages were improved and simplified

Depends-On: If23d874e8b73de12ba2b8c4e028a55543af6381b
Change-Id: Ibc1e1f4f554649d14b8fe4801557b83922ecefe3
This commit is contained in:
Boris Pavlovic 2017-09-25 14:15:08 -07:00
parent 07a24aeb69
commit 01289aa081
14 changed files with 252 additions and 266 deletions

View File

@ -84,7 +84,7 @@ implement the Context API: the *setup()* method that creates a flavor and the
ram=self.config.get("ram", 1), ram=self.config.get("ram", 1),
vcpus=self.config.get("vcpus", 1), vcpus=self.config.get("vcpus", 1),
disk=self.config.get("disk", 1)).to_dict() disk=self.config.get("disk", 1)).to_dict()
LOG.debug("Flavor with id '%s'", self.context["flavor"]["id"]) LOG.debug("Flavor with id '%s'" % self.context["flavor"]["id"])
except Exception as e: except Exception as e:
msg = "Can't create flavor: %s" % e.message msg = "Can't create flavor: %s" % e.message
if logging.is_debug(): if logging.is_debug():
@ -97,7 +97,7 @@ implement the Context API: the *setup()* method that creates a flavor and the
try: try:
nova = osclients.Clients(self.context["admin"]["credential"]).nova() nova = osclients.Clients(self.context["admin"]["credential"]).nova()
nova.flavors.delete(self.context["flavor"]["id"]) nova.flavors.delete(self.context["flavor"]["id"])
LOG.debug("Flavor '%s' deleted", self.context["flavor"]["id"]) LOG.debug("Flavor '%s' deleted" % self.context["flavor"]["id"])
except Exception as e: except Exception as e:
msg = "Can't delete flavor: %s" % e.message msg = "Can't delete flavor: %s" % e.message
if logging.is_debug(): if logging.is_debug():

View File

@ -32,7 +32,6 @@ Inherit a class for your plugin from the base *SLA* class and implement its API
.. code-block:: python .. code-block:: python
from rally.task import sla from rally.task import sla
from rally.common.i18n import _
@sla.configure(name="max_duration_range") @sla.configure(name="max_duration_range")
class MaxDurationRange(sla.SLA): class MaxDurationRange(sla.SLA):
@ -62,8 +61,8 @@ Inherit a class for your plugin from the base *SLA* class and implement its API
return self.success return self.success
def details(self): def details(self):
return (_("%s - Maximum allowed duration range: %.2f%% <= %.2f%%") % return ("%s - Maximum allowed duration range: %.2f%% <= %.2f%%"
(self.status(), self._max - self._min, self.criterion_value)) % (self.status(), self._max - self._min, self.criterion_value))
Usage Usage

View File

@ -28,10 +28,9 @@ from oslo_config import cfg
import requests import requests
from requests.packages import urllib3 from requests.packages import urllib3
from rally.common import opts
from rally.common.i18n import _, _LI, _LE
from rally.common import logging from rally.common import logging
from rally.common import objects from rally.common import objects
from rally.common import opts
from rally.common.plugin import discover from rally.common.plugin import discover
from rally.common import utils from rally.common import utils
from rally.common import version as rally_version from rally.common import version as rally_version
@ -80,9 +79,9 @@ class _Deployment(APIGroup):
try: try:
deployment = objects.Deployment(name=name, config=config) deployment = objects.Deployment(name=name, config=config)
except exceptions.DeploymentNameExists as e: except exceptions.DeploymentNameExists:
if logging.is_debug(): if logging.is_debug():
LOG.exception(e) LOG.exception("Deployment with such name exists")
raise raise
deployer = deploy_engine.Engine.get_engine( deployer = deploy_engine.Engine.get_engine(
@ -90,7 +89,7 @@ class _Deployment(APIGroup):
try: try:
deployer.validate() deployer.validate()
except jsonschema.ValidationError: except jsonschema.ValidationError:
LOG.error(_LE("Deployment %s: Schema validation error.") % LOG.error("Deployment %s: Schema validation error." %
deployment["uuid"]) deployment["uuid"])
deployment.update_status(consts.DeployStatus.DEPLOY_FAILED) deployment.update_status(consts.DeployStatus.DEPLOY_FAILED)
raise raise
@ -102,8 +101,8 @@ class _Deployment(APIGroup):
for name, cred in deployer._get_creds(config).items()) for name, cred in deployer._get_creds(config).items())
LOG.warning( LOG.warning(
"The used config schema is deprecated since Rally 0.10.0. " "The used config schema is deprecated since Rally 0.10.0. "
"The new one is much simpler, try it now:\n%s", "The new one is much simpler, try it now:\n%s"
json.dumps(new_conf, indent=4) % json.dumps(new_conf, indent=4)
) )
with deployer: with deployer:
@ -130,7 +129,7 @@ class _Deployment(APIGroup):
with deployer: with deployer:
deployer.make_cleanup() deployer.make_cleanup()
except exceptions.PluginNotFound: except exceptions.PluginNotFound:
LOG.info(_("Deployment %s will be deleted despite exception") LOG.info("Deployment %s will be deleted despite exception"
% deployment["uuid"]) % deployment["uuid"])
for verifier in self.api.verifier.list(): for verifier in self.api.verifier.list():
@ -158,7 +157,7 @@ class _Deployment(APIGroup):
try: try:
deployer.validate(config) deployer.validate(config)
except jsonschema.ValidationError: except jsonschema.ValidationError:
LOG.error(_LE("Config schema validation error.")) LOG.error("Config schema validation error.")
raise raise
with deployer: with deployer:
@ -320,8 +319,8 @@ class _Task(APIGroup):
real_missing = [mis for mis in missing real_missing = [mis for mis in missing
if is_really_missing(mis, task_template)] if is_really_missing(mis, task_template)]
if real_missing: if real_missing:
multi_msg = _("Please specify next template task arguments: %s") multi_msg = "Please specify next template task arguments: %s"
single_msg = _("Please specify template task argument: %s") single_msg = "Please specify template task argument: %s"
raise TypeError((len(real_missing) > 1 and multi_msg or single_msg) raise TypeError((len(real_missing) > 1 and multi_msg or single_msg)
% ", ".join(real_missing)) % ", ".join(real_missing))
@ -414,8 +413,8 @@ class _Task(APIGroup):
"deprecated since Rally 0.10. To use pre-created " "deprecated since Rally 0.10. To use pre-created "
"task, transmit task UUID instead.") "task, transmit task UUID instead.")
if task.is_temporary: if task.is_temporary:
raise ValueError(_( raise ValueError(
"Unable to run a temporary task. Please check your code.")) "Unable to run a temporary task. Please check your code.")
task = objects.Task.get(task["uuid"]) task = objects.Task.get(task["uuid"])
elif task is not None: elif task is not None:
task = objects.Task.get(task) task = objects.Task.get(task)
@ -467,8 +466,9 @@ class _Task(APIGroup):
if not async: if not async:
current_status = objects.Task.get_status(task_uuid) current_status = objects.Task.get_status(task_uuid)
if current_status in objects.Task.NOT_IMPLEMENTED_STAGES_FOR_ABORT: if current_status in objects.Task.NOT_IMPLEMENTED_STAGES_FOR_ABORT:
LOG.info(_LI("Task status is '%s'. Should wait until it became" LOG.info(
" 'running'") % current_status) "Task status is '%s' waiting until it became 'running'"
% current_status)
while (current_status in while (current_status in
objects.Task.NOT_IMPLEMENTED_STAGES_FOR_ABORT): objects.Task.NOT_IMPLEMENTED_STAGES_FOR_ABORT):
time.sleep(1) time.sleep(1)
@ -477,7 +477,7 @@ class _Task(APIGroup):
objects.Task.get(task_uuid).abort(soft=soft) objects.Task.get(task_uuid).abort(soft=soft)
if not async: if not async:
LOG.info(_LI("Waiting until the task stops.")) LOG.info("Waiting until the task stops.")
finished_stages = [consts.TaskStatus.ABORTED, finished_stages = [consts.TaskStatus.ABORTED,
consts.TaskStatus.FINISHED, consts.TaskStatus.FINISHED,
consts.TaskStatus.CRASHED] consts.TaskStatus.CRASHED]
@ -564,8 +564,8 @@ class _Task(APIGroup):
reporter_cls = texporter.TaskExporter.get(output_type) reporter_cls = texporter.TaskExporter.get(output_type)
reporter_cls.validate(output_dest) reporter_cls.validate(output_dest)
LOG.info("Building '%s' report for the following task(s): " LOG.info("Building '%s' report for the following task(s): '%s'."
"'%s'.", output_type, "', '".join(tasks_uuids)) % (output_type, "', '".join(tasks_uuids)))
result = texporter.TaskExporter.make(reporter_cls, result = texporter.TaskExporter.make(reporter_cls,
tasks_results, tasks_results,
output_dest, output_dest,
@ -606,7 +606,7 @@ class _Verifier(APIGroup):
# check that the specified verifier type exists # check that the specified verifier type exists
vmanager.VerifierManager.get(vtype, platform=namespace) vmanager.VerifierManager.get(vtype, platform=namespace)
LOG.info("Creating verifier '%s'.", name) LOG.info("Creating verifier '%s'." % name)
try: try:
verifier = self._get(name) verifier = self._get(name)
@ -641,7 +641,7 @@ class _Verifier(APIGroup):
raise raise
verifier.update_status(consts.VerifierStatus.INSTALLED) verifier.update_status(consts.VerifierStatus.INSTALLED)
LOG.info("Verifier %s has been successfully created!", verifier) LOG.info("Verifier %s has been successfully created!" % verifier)
return verifier.uuid return verifier.uuid
@ -684,8 +684,8 @@ class _Verifier(APIGroup):
d_msg = ((" for deployment '%s'" % deployment_id) d_msg = ((" for deployment '%s'" % deployment_id)
if deployment_id else "") if deployment_id else "")
if force: if force:
LOG.info("Deleting all verifications created by verifier " LOG.info("Deleting all verifications created by verifier %s%s."
"%s%s.", verifier, d_msg) % (verifier, d_msg))
for verification in verifications: for verification in verifications:
self.api.verification.delete( self.api.verification.delete(
verification_uuid=verification["uuid"]) verification_uuid=verification["uuid"])
@ -698,13 +698,13 @@ class _Verifier(APIGroup):
.format(verifier, d_msg)) .format(verifier, d_msg))
if deployment_id: if deployment_id:
LOG.info("Deleting deployment-specific data for verifier %s.", LOG.info("Deleting deployment-specific data for verifier %s."
verifier) % verifier)
verifier.set_deployment(deployment_id) verifier.set_deployment(deployment_id)
verifier.manager.uninstall() verifier.manager.uninstall()
LOG.info("Deployment-specific data has been successfully deleted!") LOG.info("Deployment-specific data has been successfully deleted!")
else: else:
LOG.info("Deleting verifier %s.", verifier) LOG.info("Deleting verifier %s." % verifier)
verifier.manager.uninstall(full=True) verifier.manager.uninstall(full=True)
objects.Verifier.delete(verifier_id) objects.Verifier.delete(verifier_id)
LOG.info("Verifier has been successfully deleted!") LOG.info("Verifier has been successfully deleted!")
@ -725,7 +725,7 @@ class _Verifier(APIGroup):
"specified: 'system_wide', 'version', 'update_venv'.") "specified: 'system_wide', 'version', 'update_venv'.")
verifier = self._get(verifier_id) verifier = self._get(verifier_id)
LOG.info("Updating verifier %s.", verifier) LOG.info("Updating verifier %s." % verifier)
if verifier.status != consts.VerifierStatus.INSTALLED: if verifier.status != consts.VerifierStatus.INSTALLED:
raise exceptions.RallyException( raise exceptions.RallyException(
@ -769,7 +769,8 @@ class _Verifier(APIGroup):
if system_wide == verifier.system_wide: if system_wide == verifier.system_wide:
LOG.info( LOG.info(
"Verifier %s is already switched to system_wide=%s. " "Verifier %s is already switched to system_wide=%s. "
"Nothing will be changed.", verifier, verifier.system_wide) "Nothing will be changed."
% (verifier, verifier.system_wide))
else: else:
properties["system_wide"] = system_wide properties["system_wide"] = system_wide
if not system_wide: if not system_wide:
@ -793,7 +794,7 @@ class _Verifier(APIGroup):
properties["status"] = original_status # change verifier status back properties["status"] = original_status # change verifier status back
verifier.update_properties(**properties) verifier.update_properties(**properties)
LOG.info("Verifier %s has been successfully updated!", verifier) LOG.info("Verifier %s has been successfully updated!" % verifier)
return verifier.uuid return verifier.uuid
@ -809,9 +810,10 @@ class _Verifier(APIGroup):
if not isinstance(verifier, objects.Verifier): if not isinstance(verifier, objects.Verifier):
verifier = self._get(verifier) verifier = self._get(verifier)
verifier.set_deployment(deployment_id) verifier.set_deployment(deployment_id)
LOG.info( LOG.info("Configuring verifier %s for deployment '%s' (UUID=%s)."
"Configuring verifier %s for deployment '%s' (UUID=%s).", % (verifier,
verifier, verifier.deployment["name"], verifier.deployment["uuid"]) verifier.deployment["name"],
verifier.deployment["uuid"]))
if verifier.status != consts.VerifierStatus.INSTALLED: if verifier.status != consts.VerifierStatus.INSTALLED:
raise exceptions.RallyException( raise exceptions.RallyException(
@ -834,7 +836,7 @@ class _Verifier(APIGroup):
# Just add extra options to the config file. # Just add extra options to the config file.
if logging.is_debug(): if logging.is_debug():
LOG.debug("Adding the following extra options: %s " LOG.debug("Adding the following extra options: %s "
"to verifier configuration.", extra_options) "to verifier configuration." % extra_options)
else: else:
LOG.info( LOG.info(
"Adding extra options to verifier configuration.") "Adding extra options to verifier configuration.")
@ -870,12 +872,14 @@ class _Verifier(APIGroup):
verifier.set_deployment(deployment_id) verifier.set_deployment(deployment_id)
LOG.info("Overriding configuration of verifier %s for deployment '%s' " LOG.info("Overriding configuration of verifier %s for deployment '%s' "
"(UUID=%s).", verifier, verifier.deployment["name"], "(UUID=%s)."
verifier.deployment["uuid"]) % (verifier,
verifier.deployment["name"], verifier.deployment["uuid"]))
verifier.manager.override_configuration(new_configuration) verifier.manager.override_configuration(new_configuration)
LOG.info("Configuration of verifier %s has been successfully " LOG.info("Configuration of verifier %s has been successfully "
"overridden for deployment '%s' (UUID=%s)!", verifier, "overridden for deployment '%s' (UUID=%s)!"
verifier.deployment["name"], verifier.deployment["uuid"]) % (verifier,
verifier.deployment["name"], verifier.deployment["uuid"]))
def list_tests(self, verifier_id, pattern=""): def list_tests(self, verifier_id, pattern=""):
"""List all verifier tests. """List all verifier tests.
@ -915,7 +919,7 @@ class _Verifier(APIGroup):
verifier, verifier.status, consts.VerifierStatus.INSTALLED) verifier, verifier.status, consts.VerifierStatus.INSTALLED)
) )
LOG.info("Adding extension for verifier %s.", verifier) LOG.info("Adding extension for verifier %s." % verifier)
# store original status to rollback it after failure # store original status to rollback it after failure
original_status = verifier.status original_status = verifier.status
@ -926,8 +930,8 @@ class _Verifier(APIGroup):
finally: finally:
verifier.update_status(original_status) verifier.update_status(original_status)
LOG.info("Extension for verifier %s has been successfully added!", LOG.info("Extension for verifier %s has been successfully added!"
verifier) % verifier)
def list_extensions(self, verifier_id): def list_extensions(self, verifier_id):
"""List all verifier extensions. """List all verifier extensions.
@ -958,10 +962,10 @@ class _Verifier(APIGroup):
verifier, verifier.status, consts.VerifierStatus.INSTALLED) verifier, verifier.status, consts.VerifierStatus.INSTALLED)
) )
LOG.info("Deleting extension for verifier %s.", verifier) LOG.info("Deleting extension for verifier %s." % verifier)
verifier.manager.uninstall_extension(name) verifier.manager.uninstall_extension(name)
LOG.info("Extension for verifier %s has been successfully deleted!", LOG.info("Extension for verifier %s has been successfully deleted!"
verifier) % verifier)
class _Verification(APIGroup): class _Verification(APIGroup):
@ -1007,9 +1011,11 @@ class _Verification(APIGroup):
verifier_id=verifier_id, deployment_id=deployment_id, tags=tags, verifier_id=verifier_id, deployment_id=deployment_id, tags=tags,
run_args=run_args) run_args=run_args)
LOG.info("Starting verification (UUID=%s) for deployment '%s' " LOG.info("Starting verification (UUID=%s) for deployment '%s' "
"(UUID=%s) by verifier %s.", verification.uuid, "(UUID=%s) by verifier %s."
verifier.deployment["name"], verifier.deployment["uuid"], % (verification.uuid,
verifier) verifier.deployment["name"],
verifier.deployment["uuid"],
verifier))
verification.update_status(consts.VerificationStatus.RUNNING) verification.update_status(consts.VerificationStatus.RUNNING)
context = {"config": verifier.manager._meta_get("context"), context = {"config": verifier.manager._meta_get("context"),
@ -1029,8 +1035,9 @@ class _Verification(APIGroup):
verification.finish(results.totals, results.tests) verification.finish(results.totals, results.tests)
LOG.info("Verification (UUID=%s) has been successfully finished for " LOG.info("Verification (UUID=%s) has been successfully finished for "
"deployment '%s' (UUID=%s)!", verification.uuid, "deployment '%s' (UUID=%s)!"
verifier.deployment["name"], verifier.deployment["uuid"]) % (verification.uuid,
verifier.deployment["name"], verifier.deployment["uuid"]))
return {"verification": verification.to_dict(), return {"verification": verification.to_dict(),
"totals": results.totals, "totals": results.totals,
@ -1069,8 +1076,10 @@ class _Verification(APIGroup):
else verification.deployment_uuid) else verification.deployment_uuid)
deployment = self.api.deployment.get(deployment=deployment) deployment = self.api.deployment.get(deployment=deployment)
LOG.info("Re-running %stests from verification (UUID=%s) for " LOG.info("Re-running %stests from verification (UUID=%s) for "
"deployment '%s' (UUID=%s).", "failed " if failed else "", "deployment '%s' (UUID=%s)."
verification.uuid, deployment["name"], deployment["uuid"]) % ("failed " if failed else "",
verification.uuid,
deployment["name"], deployment["uuid"]))
return self.start(verifier_id=verification.verifier_uuid, return self.start(verifier_id=verification.verifier_uuid,
deployment_id=deployment["uuid"], deployment_id=deployment["uuid"],
load_list=tests, tags=tags, **run_args) load_list=tests, tags=tags, **run_args)
@ -1104,7 +1113,7 @@ class _Verification(APIGroup):
:param verification_uuid: Verification UUID :param verification_uuid: Verification UUID
""" """
verification = self._get(verification_uuid) verification = self._get(verification_uuid)
LOG.info("Deleting verification (UUID=%s).", verification.uuid) LOG.info("Deleting verification (UUID=%s)." % verification.uuid)
verification.delete() verification.delete()
LOG.info("Verification has been successfully deleted!") LOG.info("Verification has been successfully deleted!")
@ -1120,12 +1129,12 @@ class _Verification(APIGroup):
reporter_cls = vreporter.VerificationReporter.get(output_type) reporter_cls = vreporter.VerificationReporter.get(output_type)
reporter_cls.validate(output_dest) reporter_cls.validate(output_dest)
LOG.info("Building '%s' report for the following verification(s): " LOG.info("Building '%s' report for the following verification(s): '%s'"
"'%s'.", output_type, "', '".join(uuids)) % (output_type, "', '".join(uuids)))
result = vreporter.VerificationReporter.make(reporter_cls, result = vreporter.VerificationReporter.make(reporter_cls,
verifications, verifications,
output_dest) output_dest)
LOG.info(_LI("The report has been successfully built.")) LOG.info("The report has been successfully built.")
return result return result
def import_results(self, verifier_id, deployment_id, data, **run_args): def import_results(self, verifier_id, deployment_id, data, **run_args):
@ -1143,9 +1152,10 @@ class _Verification(APIGroup):
verifier = self.api.verifier._get(verifier_id) verifier = self.api.verifier._get(verifier_id)
verifier.set_deployment(deployment_id) verifier.set_deployment(deployment_id)
LOG.info("Importing test results into a new verification for " LOG.info("Importing test results into a new verification for "
"deployment '%s' (UUID=%s), using verifier %s.", "deployment '%s' (UUID=%s), using verifier %s."
verifier.deployment["name"], verifier.deployment["uuid"], % (verifier.deployment["name"],
verifier) verifier.deployment["uuid"],
verifier))
verifier.manager.validate_args(run_args) verifier.manager.validate_args(run_args)
@ -1233,8 +1243,8 @@ class API(object):
except cfg.ConfigFilesNotFoundError as e: except cfg.ConfigFilesNotFoundError as e:
cfg_files = e.config_files cfg_files = e.config_files
raise exceptions.RallyException(_( raise exceptions.RallyException(
"Failed to read configuration file(s): %s") % cfg_files) "Failed to read configuration file(s): %s" % cfg_files)
# Check that db is upgraded to the latest revision # Check that db is upgraded to the latest revision
if not skip_db_check: if not skip_db_check:
@ -1266,13 +1276,13 @@ class API(object):
# Check that db exists # Check that db exists
if rev["revision"] is None: if rev["revision"] is None:
raise exceptions.RallyException(_( raise exceptions.RallyException(
"Database is missing. Create database by command " "Database is missing. Create database by command "
"`rally db create'")) "`rally db create'")
# Check that db is updated # Check that db is updated
if rev["revision"] != rev["current_head"]: if rev["revision"] != rev["current_head"]:
raise exceptions.RallyException(_( raise exceptions.RallyException((
"Database seems to be outdated. Run upgrade from " "Database seems to be outdated. Run upgrade from "
"revision %(revision)s to %(current_head)s by command " "revision %(revision)s to %(current_head)s by command "
"`rally db upgrade'") % rev) "`rally db upgrade'") % rev)

View File

@ -32,7 +32,6 @@ import six
import sqlalchemy.exc import sqlalchemy.exc
from rally import api from rally import api
from rally.common.i18n import _
from rally.common import logging from rally.common import logging
from rally.common.plugin import info from rally.common.plugin import info
from rally import exceptions from rally import exceptions
@ -50,7 +49,7 @@ class MissingArgs(Exception):
"""Supplied arguments are not sufficient for calling a function.""" """Supplied arguments are not sufficient for calling a function."""
def __init__(self, missing): def __init__(self, missing):
self.missing = missing self.missing = missing
msg = _("Missing arguments: %s") % ", ".join(missing) msg = "Missing arguments: %s" % ", ".join(missing)
super(MissingArgs, self).__init__(msg) super(MissingArgs, self).__init__(msg)
@ -112,9 +111,9 @@ def print_list(objs, fields, formatters=None, sortby_index=0,
mixed_case_fields = mixed_case_fields or [] mixed_case_fields = mixed_case_fields or []
field_labels = field_labels or fields field_labels = field_labels or fields
if len(field_labels) != len(fields): if len(field_labels) != len(fields):
raise ValueError(_("Field labels list %(labels)s has different number " raise ValueError("Field labels list %(labels)s has different number of"
"of elements than fields list %(fields)s"), " elements than fields list %(fields)s"
{"labels": field_labels, "fields": fields}) % {"labels": field_labels, "fields": fields})
if sortby_index is None: if sortby_index is None:
kwargs = {} kwargs = {}
@ -276,8 +275,8 @@ def make_table_header(table_label, table_width,
""" """
if len(table_label) >= (table_width - 2): if len(table_label) >= (table_width - 2):
raise ValueError(_("Table header %s is longer than total" raise ValueError(
"width of the table.")) "Table header %s is longer than total width of the table.")
label_and_space_width = table_width - len(table_label) - 2 label_and_space_width = table_width - len(table_label) - 2
padding = 0 if label_and_space_width % 2 == 0 else 1 padding = 0 if label_and_space_width % 2 == 0 else 1
@ -324,13 +323,13 @@ def process_keystone_exc(f, *args, **kwargs):
try: try:
return f(*args, **kwargs) return f(*args, **kwargs)
except keystone_exc.Unauthorized as e: except keystone_exc.Unauthorized as e:
print(_("User credentials are wrong! \n%s") % e) print("User credentials are wrong! \n%s" % e)
return 1 return 1
except keystone_exc.AuthorizationFailure as e: except keystone_exc.AuthorizationFailure as e:
print(_("Failed to authorize! \n%s") % e) print("Failed to authorize! \n%s" % e)
return 1 return 1
except keystone_exc.ConnectionRefused as e: except keystone_exc.ConnectionRefused as e:
print(_("Rally can't reach the Keystone service! \n%s") % e) print("Rally can't reach the Keystone service! \n%s" % e)
return 1 return 1
@ -375,7 +374,7 @@ class CategoryParser(argparse.ArgumentParser):
# error message it WILL NOT LIST ALL the missing arguments # error message it WILL NOT LIST ALL the missing arguments
# at once INSTEAD only 1 missing argument at a time # at once INSTEAD only 1 missing argument at a time
missing_arg = message.split()[1] missing_arg = message.split()[1]
print(_("Missing argument:\n%s") % missing_arg) print("Missing argument:\n%s" % missing_arg)
sys.exit(2) sys.exit(2)
@ -663,20 +662,20 @@ def run(argv, categories):
except (IOError, TypeError, ValueError, except (IOError, TypeError, ValueError,
exceptions.RallyException, jsonschema.ValidationError) as e: exceptions.RallyException, jsonschema.ValidationError) as e:
if logging.is_debug(): if logging.is_debug():
LOG.exception(e) LOG.exception("Unexpected exception in CLI")
else: else:
print(e) print(e)
return 1 return 1
except sqlalchemy.exc.OperationalError as e: except sqlalchemy.exc.OperationalError as e:
if logging.is_debug(): if logging.is_debug():
LOG.exception(e) LOG.exception("Something went wrong with database")
print(e) print(e)
print("Looks like Rally can't connect to its DB.") print("Looks like Rally can't connect to its DB.")
print("Make sure that connection string in rally.conf is proper:") print("Make sure that connection string in rally.conf is proper:")
print(CONF.database.connection) print(CONF.database.connection)
return 1 return 1
except Exception: except Exception:
print(_("Command failed, please check log for more info")) print("Command failed, please check log for more info")
raise raise

View File

@ -26,7 +26,6 @@ import jsonschema
from rally.cli import cliutils from rally.cli import cliutils
from rally.cli import envutils from rally.cli import envutils
from rally.common import fileutils from rally.common import fileutils
from rally.common.i18n import _
from rally.common import logging from rally.common import logging
from rally.common import utils from rally.common import utils
from rally.common import yamlutils as yaml from rally.common import yamlutils as yaml
@ -101,10 +100,10 @@ class DeploymentCommands(object):
try: try:
deployment = api.deployment.create(config=config, name=name) deployment = api.deployment.create(config=config, name=name)
except jsonschema.ValidationError: except jsonschema.ValidationError:
print(_("Config schema validation error: %s.") % sys.exc_info()[1]) print("Config schema validation error: %s." % sys.exc_info()[1])
return 1 return 1
except exceptions.DeploymentNameExists: except exceptions.DeploymentNameExists:
print(_("Error: %s") % sys.exc_info()[1]) print("Error: %s" % sys.exc_info()[1])
return 1 return 1
self.list(api, deployment_list=[deployment]) self.list(api, deployment_list=[deployment])
@ -166,9 +165,8 @@ class DeploymentCommands(object):
cliutils.print_list(table_rows, headers, cliutils.print_list(table_rows, headers,
sortby_index=headers.index("created_at")) sortby_index=headers.index("created_at"))
else: else:
print(_("There are no deployments. " print("There are no deployments. To create a new deployment, use:"
"To create a new deployment, use:" "\nrally deployment create")
"\nrally deployment create"))
@cliutils.args("--deployment", dest="deployment", type=str, @cliutils.args("--deployment", dest="deployment", type=str,
metavar="<uuid>", required=False, metavar="<uuid>", required=False,
@ -230,7 +228,7 @@ class DeploymentCommands(object):
return bool([item for item in lst if field in item]) return bool([item for item in lst if field in item])
def print_error(user_type, error): def print_error(user_type, error):
print(_("Error while checking %s credentials:") % user_type) print("Error while checking %s credentials:" % user_type)
if logging.is_debug(): if logging.is_debug():
print(error["trace"]) print(error["trace"])
else: else:

View File

@ -31,7 +31,6 @@ import six
from rally.cli import cliutils from rally.cli import cliutils
from rally.cli import envutils from rally.cli import envutils
from rally.common import fileutils from rally.common import fileutils
from rally.common.i18n import _
from rally.common.io import junit from rally.common.io import junit
from rally.common import logging from rally.common import logging
from rally.common import utils as rutils from rally.common import utils as rutils
@ -126,12 +125,12 @@ OLD_TASK_RESULT_SCHEMA = {
class FailedToLoadTask(exceptions.RallyException): class FailedToLoadTask(exceptions.RallyException):
error_code = 472 error_code = 472
msg_fmt = _("Invalid %(source)s passed:\n\n\t %(msg)s") msg_fmt = "Invalid %(source)s passed:\n\n\t %(msg)s"
class FailedToLoadResults(exceptions.RallyException): class FailedToLoadResults(exceptions.RallyException):
error_code = 529 error_code = 529
msg_fmt = _("ERROR: Invalid task result format in %(source)s\n\n\t%(msg)s") msg_fmt = "ERROR: Invalid task result format in %(source)s\n\n\t%(msg)s"
class TaskCommands(object): class TaskCommands(object):
@ -205,7 +204,7 @@ class TaskCommands(object):
source="--task", source="--task",
msg="Failed to render task template.\n\n%s" % e) msg="Failed to render task template.\n\n%s" % e)
print(_("Task is:\n%s\n") % rendered_task.strip()) print("Task is:\n%s\n" % rendered_task.strip())
try: try:
parsed_task = yaml.safe_load(rendered_task) parsed_task = yaml.safe_load(rendered_task)
except Exception as e: except Exception as e:
@ -214,7 +213,7 @@ class TaskCommands(object):
msg="Wrong format of rendered input task. It should be YAML or" msg="Wrong format of rendered input task. It should be YAML or"
" JSON. Details:\n\n%s" % e) " JSON. Details:\n\n%s" % e)
print(_("Task syntax is correct :)")) print("Task syntax is correct :)")
return parsed_task return parsed_task
@cliutils.args("--deployment", dest="deployment", type=str, @cliutils.args("--deployment", dest="deployment", type=str,
@ -259,7 +258,7 @@ class TaskCommands(object):
api.task.validate(deployment=deployment, config=task) api.task.validate(deployment=deployment, config=task)
print(_("Task config is valid :)")) print("Input Task is valid :)")
@cliutils.args("--deployment", dest="deployment", type=str, @cliutils.args("--deployment", dest="deployment", type=str,
metavar="<uuid>", required=False, metavar="<uuid>", required=False,
@ -318,7 +317,7 @@ class TaskCommands(object):
tags = "[tags: '%s']" % "', '".join(tags) if tags else "" tags = "[tags: '%s']" % "', '".join(tags) if tags else ""
print(cliutils.make_header( print(cliutils.make_header(
_("Task %(tags)s %(uuid)s: started") "Task %(tags)s %(uuid)s: started"
% {"uuid": task_instance["uuid"], "tags": tags})) % {"uuid": task_instance["uuid"], "tags": tags}))
print("Running Task... This can take a while...\n") print("Running Task... This can take a while...\n")
print("To track task status use:\n") print("To track task status use:\n")
@ -332,7 +331,7 @@ class TaskCommands(object):
abort_on_sla_failure=abort_on_sla_failure) abort_on_sla_failure=abort_on_sla_failure)
except exceptions.DeploymentNotFinishedStatus as e: except exceptions.DeploymentNotFinishedStatus as e:
print(_("Cannot start a task on unfinished deployment: %s") % e) print("Cannot start a task on unfinished deployment: %s" % e)
return 1 return 1
self.detailed(api, task_id=task_instance["uuid"]) self.detailed(api, task_id=task_instance["uuid"])
@ -369,7 +368,7 @@ class TaskCommands(object):
""" """
task = api.task.get(task_id=task_id) task = api.task.get(task_id=task_id)
print(_("Task %(task_id)s: %(status)s") print("Task %(task_id)s: %(status)s"
% {"task_id": task_id, "status": task["status"]}) % {"task_id": task_id, "status": task["status"]})
@cliutils.args("--uuid", type=str, dest="task_id", @cliutils.args("--uuid", type=str, dest="task_id",
@ -393,7 +392,7 @@ class TaskCommands(object):
print() print()
print("-" * 80) print("-" * 80)
print(_("Task %(task_id)s: %(status)s") print("Task %(task_id)s: %(status)s"
% {"task_id": task_id, "status": task["status"]}) % {"task_id": task_id, "status": task["status"]})
if task["status"] == consts.TaskStatus.CRASHED or task["status"] == ( if task["status"] == consts.TaskStatus.CRASHED or task["status"] == (
@ -405,15 +404,15 @@ class TaskCommands(object):
else: else:
print(validation["etype"]) print(validation["etype"])
print(validation["msg"]) print(validation["msg"])
print(_("\nFor more details run:\nrally -d task detailed %s") print("\nFor more details run:\nrally -d task detailed %s"
% task["uuid"]) % task["uuid"])
return 0 return 0
elif task["status"] not in [consts.TaskStatus.FINISHED, elif task["status"] not in [consts.TaskStatus.FINISHED,
consts.TaskStatus.ABORTED]: consts.TaskStatus.ABORTED]:
print("-" * 80) print("-" * 80)
print(_("\nThe task %s marked as '%s'. Results " print("\nThe task %s marked as '%s'. Results "
"available when it is '%s'.") % ( "available when it is '%s'."
task_id, task["status"], consts.TaskStatus.FINISHED)) % (task_id, task["status"], consts.TaskStatus.FINISHED))
return 0 return 0
for workload in itertools.chain( for workload in itertools.chain(
@ -542,6 +541,7 @@ class TaskCommands(object):
% rutils.format_float_to_str(workload["load_duration"])) % rutils.format_float_to_str(workload["load_duration"]))
print("Full duration: %s" print("Full duration: %s"
% rutils.format_float_to_str(workload["full_duration"])) % rutils.format_float_to_str(workload["full_duration"]))
print("\nHINTS:") print("\nHINTS:")
print("* To plot HTML graphics with this data, run:") print("* To plot HTML graphics with this data, run:")
print("\trally task report %s --out output.html\n" % task["uuid"]) print("\trally task report %s --out output.html\n" % task["uuid"])
@ -565,8 +565,8 @@ class TaskCommands(object):
finished_statuses = (consts.TaskStatus.FINISHED, finished_statuses = (consts.TaskStatus.FINISHED,
consts.TaskStatus.ABORTED) consts.TaskStatus.ABORTED)
if task["status"] not in finished_statuses: if task["status"] not in finished_statuses:
print(_("Task status is %s. Results available when it is one " print("Task status is %s. Results available when it is one of %s."
"of %s.") % (task["status"], ", ".join(finished_statuses))) % (task["status"], ", ".join(finished_statuses)))
return 1 return 1
# TODO(chenhb): Ensure `rally task results` puts out old format. # TODO(chenhb): Ensure `rally task results` puts out old format.
@ -639,9 +639,8 @@ class TaskCommands(object):
if status in consts.TaskStatus: if status in consts.TaskStatus:
filters["status"] = status filters["status"] = status
elif status: elif status:
print(_("Error: Invalid task status '%s'.\n" print("Error: Invalid task status '%s'.\nAvailable statuses: %s"
"Available statuses: %s") % ( % (status, ", ".join(consts.TaskStatus)),
status, ", ".join(consts.TaskStatus)),
file=sys.stderr) file=sys.stderr)
return(1) return(1)
@ -675,12 +674,12 @@ class TaskCommands(object):
formatters=formatters) formatters=formatters)
else: else:
if status: if status:
print(_("There are no tasks in '%s' status. " print("There are no tasks in '%s' status. "
"To run a new task, use:\n" "To run a new task, use:\n\trally task start"
"\trally task start") % status) % status)
else: else:
print(_("There are no tasks. To run a new task, use:\n" print("There are no tasks. To run a new task, use:\n"
"\trally task start")) "\trally task start")
def _load_task_results_file(self, api, task_id): def _load_task_results_file(self, api, task_id):
"""Load the json file which is created by `rally task results` """ """Load the json file which is created by `rally task results` """
@ -791,7 +790,7 @@ class TaskCommands(object):
tasks = kwargs.get("tasks", []) or list(args) tasks = kwargs.get("tasks", []) or list(args)
if not tasks: if not tasks:
print(_("ERROR: At least one task must be specified"), print("ERROR: At least one task must be specified",
file=sys.stderr) file=sys.stderr)
return 1 return 1
@ -802,8 +801,8 @@ class TaskCommands(object):
elif uuidutils.is_uuid_like(task_id): elif uuidutils.is_uuid_like(task_id):
task_results = api.task.get(task_id=task_id, detailed=True) task_results = api.task.get(task_id=task_id, detailed=True)
else: else:
print(_("ERROR: Invalid UUID or file name passed: %s") print("ERROR: Invalid UUID or file name passed: %s" % task_id,
% task_id, file=sys.stderr) file=sys.stderr)
return 1 return 1
results.append(task_results) results.append(task_results)
@ -878,8 +877,8 @@ class TaskCommands(object):
elif uuidutils.is_uuid_like(task_file_or_uuid): elif uuidutils.is_uuid_like(task_file_or_uuid):
task = api.task.get(task_id=task_file_or_uuid, detailed=True) task = api.task.get(task_id=task_file_or_uuid, detailed=True)
else: else:
print(_("ERROR: Invalid UUID or file name passed: %s" print("ERROR: Invalid UUID or file name passed: %s"
) % task_file_or_uuid, % task_file_or_uuid,
file=sys.stderr) file=sys.stderr)
return 1 return 1
@ -913,7 +912,7 @@ class TaskCommands(object):
message) message)
result = test_suite.to_xml() result = test_suite.to_xml()
else: else:
print(_("Invalid output format: %s") % out_format, file=sys.stderr) print("Invalid output format: %s" % out_format, file=sys.stderr)
return 1 return 1
if out: if out:
@ -1060,9 +1059,9 @@ class TaskCommands(object):
@staticmethod @staticmethod
def _format_task_error(data): def _format_task_error(data):
error_type = _("Unknown type") error_type = "Unknown type"
error_message = _("Rally hasn't caught anything yet") error_message = "Rally hasn't caught anything yet"
error_traceback = _("No traceback available.") error_traceback = "No traceback available."
try: try:
error_type = data["error"][0] error_type = data["error"][0]
error_message = data["error"][1] error_message = data["error"][1]
@ -1096,8 +1095,8 @@ class TaskCommands(object):
task = api.task.import_results(deployment=deployment, task = api.task.import_results(deployment=deployment,
task_results=tasks_results, task_results=tasks_results,
tags=tags) tags=tags)
print(_("Task UUID: %s.") % task["uuid"]) print("Task UUID: %s." % task["uuid"])
else: else:
print(_("ERROR: Invalid file name passed: %s") % task_file, print("ERROR: Invalid file name passed: %s" % task_file,
file=sys.stderr) file=sys.stderr)
return 1 return 1

View File

@ -27,7 +27,6 @@ from six.moves import configparser
from rally.cli import cliutils from rally.cli import cliutils
from rally.cli import envutils from rally.cli import envutils
from rally.common import fileutils from rally.common import fileutils
from rally.common.i18n import _
from rally.common import logging from rally.common import logging
from rally.common import yamlutils as yaml from rally.common import yamlutils as yaml
from rally import exceptions from rally import exceptions
@ -77,8 +76,8 @@ class VerifyCommands(object):
len(failures), "tests" if len(failures) > 1 else "test") len(failures), "tests" if len(failures) > 1 else "test")
self._print_failures(h_text, failures, "=") self._print_failures(h_text, failures, "=")
else: else:
print(_("\nCongratulations! Verification doesn't have failed " print("\nCongratulations! "
"tests! :)")) "Verification doesn't have failed tests ;)")
@staticmethod @staticmethod
def _base_dir(uuid): def _base_dir(uuid):
@ -152,9 +151,9 @@ class VerifyCommands(object):
"""Choose a verifier to use for the future operations.""" """Choose a verifier to use for the future operations."""
verifier = api.verifier.get(verifier_id=verifier_id) verifier = api.verifier.get(verifier_id=verifier_id)
fileutils.update_globals_file(envutils.ENV_VERIFIER, verifier["uuid"]) fileutils.update_globals_file(envutils.ENV_VERIFIER, verifier["uuid"])
print(_("Using verifier '%s' (UUID=%s) as the default verifier " print("Using verifier '%s' (UUID=%s) as the default verifier "
"for the future operations.") % (verifier["name"], "for the future CLI operations."
verifier["uuid"])) % (verifier["name"], verifier["uuid"]))
@cliutils.help_group("verifier") @cliutils.help_group("verifier")
@cliutils.args("--status", dest="status", type=str, required=False, @cliutils.args("--status", dest="status", type=str, required=False,
@ -176,10 +175,10 @@ class VerifyCommands(object):
cliutils.print_list(verifiers, fields, formatters=formatters, cliutils.print_list(verifiers, fields, formatters=formatters,
normalize_field_names=True, sortby_index=4) normalize_field_names=True, sortby_index=4)
elif status: elif status:
print(_("There are no verifiers with status '%s'.") % status) print("There are no verifiers with status '%s'." % status)
else: else:
print(_("There are no verifiers. You can create verifier, using " print("There are no verifiers. You can create verifier, using "
"command `rally verify create-verifier`.")) "command `rally verify create-verifier`.")
@cliutils.help_group("verifier") @cliutils.help_group("verifier")
@cliutils.args("--id", dest="verifier_id", type=str, @cliutils.args("--id", dest="verifier_id", type=str,
@ -210,8 +209,8 @@ class VerifyCommands(object):
cliutils.print_dict(verifier, fields=fields, formatters=formatters, cliutils.print_dict(verifier, fields=fields, formatters=formatters,
normalize_field_names=True, print_header=False, normalize_field_names=True, print_header=False,
table_label="Verifier") table_label="Verifier")
print(_("Attention! All you do in the verifier repository or " print("Attention! All you do in the verifier repository or verifier "
"verifier virtual environment, you do it at your own risk!")) "virtual environment, you do it at your own risk!")
@cliutils.help_group("verifier") @cliutils.help_group("verifier")
@cliutils.args("--id", dest="verifier_id", type=str, required=True, @cliutils.args("--id", dest="verifier_id", type=str, required=True,
@ -259,12 +258,12 @@ class VerifyCommands(object):
update_venv=None): update_venv=None):
"""Update a verifier.""" """Update a verifier."""
if not (version or system_wide or no_system_wide or update_venv): if not (version or system_wide or no_system_wide or update_venv):
print(_("At least one of the following arguments should be " print("At least one of the following arguments should be "
"provided: '--update-venv', '--version', '--system-wide', " "provided: '--update-venv', '--version', '--system-wide', "
"'--no-system-wide'.")) "'--no-system-wide'.")
return 1 return 1
msg = _("Arguments '--%s' and '--%s' cannot be used simultaneously. " msg = ("Arguments '--%s' and '--%s' cannot be used simultaneously. "
"You can use only one of the mentioned arguments.") "You can use only one of the mentioned arguments.")
if update_venv and system_wide: if update_venv and system_wide:
print(msg % ("update-venv", "system-wide")) print(msg % ("update-venv", "system-wide"))
@ -279,9 +278,9 @@ class VerifyCommands(object):
version=version, version=version,
update_venv=update_venv) update_venv=update_venv)
print(_("HINT: In some cases the verifier config file should be " print("HINT: In some cases the verifier config file should be "
"updated as well. Use `rally verify configure-verifier` " "updated as well. Use `rally verify configure-verifier` "
"command to update the config file.")) "command to update the config file.")
@cliutils.help_group("verifier") @cliutils.help_group("verifier")
@cliutils.args("--id", dest="verifier_id", type=str, @cliutils.args("--id", dest="verifier_id", type=str,
@ -313,15 +312,14 @@ class VerifyCommands(object):
# TODO(ylobankov): Add an ability to read extra options from # TODO(ylobankov): Add an ability to read extra options from
# a json or yaml file. # a json or yaml file.
if new_configuration and (extra_options or reconfigure): if new_configuration and (extra_options or reconfigure):
print(_("Argument '--override' cannot be used with arguments " print("Argument '--override' cannot be used with arguments "
"'--reconfigure' and '--extend'.")) "'--reconfigure' and '--extend'.")
return 1 return 1
if new_configuration: if new_configuration:
if not os.path.exists(new_configuration): if not os.path.exists(new_configuration):
print(_("File '%s' not found.") % new_configuration) print("File '%s' not found." % new_configuration)
return 1 return 1
with open(new_configuration) as f: with open(new_configuration) as f:
@ -370,7 +368,7 @@ class VerifyCommands(object):
for test in tests: for test in tests:
print(test) print(test)
else: else:
print(_("No tests found.")) print("No tests found.")
@cliutils.help_group("verifier-ext") @cliutils.help_group("verifier-ext")
@cliutils.args("--id", dest="verifier_id", type=str, @cliutils.args("--id", dest="verifier_id", type=str,
@ -407,9 +405,8 @@ class VerifyCommands(object):
cliutils.print_list(verifier_exts, fields, cliutils.print_list(verifier_exts, fields,
normalize_field_names=True) normalize_field_names=True)
else: else:
print(_("There are no verifier extensions. You can add " print("There are no verifier extensions. You can add verifier "
"verifier extension, using command `rally verify " "extension, using command `rally verify add-verifier-ext`.")
"add-verifier-ext`."))
@cliutils.help_group("verifier-ext") @cliutils.help_group("verifier-ext")
@cliutils.args("--id", dest="verifier_id", type=str, @cliutils.args("--id", dest="verifier_id", type=str,
@ -468,9 +465,8 @@ class VerifyCommands(object):
xfail_list=None, detailed=False, do_use=True): xfail_list=None, detailed=False, do_use=True):
"""Start a verification (run verifier tests).""" """Start a verification (run verifier tests)."""
if pattern and load_list: if pattern and load_list:
print(_("Arguments '--pattern' and '--load-list' cannot be used " print("Arguments '--pattern' and '--load-list' cannot be used "
"simultaneously. You can use only one of the mentioned " "together, use only one of them.")
"arguments."))
return 1 return 1
def parse(filename): def parse(filename):
@ -479,20 +475,20 @@ class VerifyCommands(object):
if load_list: if load_list:
if not os.path.exists(load_list): if not os.path.exists(load_list):
print(_("File '%s' not found.") % load_list) print("File '%s' not found." % load_list)
return 1 return 1
with open(load_list, "r") as f: with open(load_list, "r") as f:
load_list = [test for test in f.read().split("\n") if test] load_list = [test for test in f.read().split("\n") if test]
if skip_list: if skip_list:
if not os.path.exists(skip_list): if not os.path.exists(skip_list):
print(_("File '%s' not found.") % skip_list) print("File '%s' not found." % skip_list)
return 1 return 1
skip_list = parse(skip_list) skip_list = parse(skip_list)
if xfail_list: if xfail_list:
if not os.path.exists(xfail_list): if not os.path.exists(xfail_list):
print(_("File '%s' not found.") % xfail_list) print("File '%s' not found." % xfail_list)
return 1 return 1
xfail_list = parse(xfail_list) xfail_list = parse(xfail_list)
@ -507,8 +503,8 @@ class VerifyCommands(object):
tags=tags, **run_args) tags=tags, **run_args)
verification_uuid = results["verification"]["uuid"] verification_uuid = results["verification"]["uuid"]
except exceptions.DeploymentNotFinishedStatus as e: except exceptions.DeploymentNotFinishedStatus as e:
print(_("Cannot start a verefication on " print("Cannot start a verefication against unfinished deployment: "
"unfinished deployment: %s") % e) " %s" % e)
return 1 return 1
if detailed: if detailed:
@ -519,7 +515,7 @@ class VerifyCommands(object):
if do_use: if do_use:
self.use(api, verification_uuid) self.use(api, verification_uuid)
else: else:
print(_("Verification UUID: %s.") % verification_uuid) print("Verification UUID: %s." % verification_uuid)
@cliutils.help_group("verification") @cliutils.help_group("verification")
@cliutils.args("--uuid", dest="verification_uuid", type=str, required=True, @cliutils.args("--uuid", dest="verification_uuid", type=str, required=True,
@ -530,8 +526,8 @@ class VerifyCommands(object):
verification_uuid=verification_uuid) verification_uuid=verification_uuid)
fileutils.update_globals_file( fileutils.update_globals_file(
envutils.ENV_VERIFICATION, verification["uuid"]) envutils.ENV_VERIFICATION, verification["uuid"])
print(_("Using verification (UUID=%s) as the default verification " print("Using verification (UUID=%s) as the default verification "
"for the future operations.") % verification["uuid"]) "for the future operations." % verification["uuid"])
@cliutils.help_group("verification") @cliutils.help_group("verification")
@cliutils.args("--uuid", dest="verification_uuid", type=str, @cliutils.args("--uuid", dest="verification_uuid", type=str,
@ -574,8 +570,7 @@ class VerifyCommands(object):
if do_use: if do_use:
self.use(api, results["verification"]["uuid"]) self.use(api, results["verification"]["uuid"])
else: else:
print(_("Verification UUID: %s.") print("Verification UUID: %s." % results["verification"]["uuid"])
% results["verification"]["uuid"])
@cliutils.help_group("verification") @cliutils.help_group("verification")
@cliutils.args("--uuid", dest="verification_uuid", type=str, @cliutils.args("--uuid", dest="verification_uuid", type=str,
@ -641,7 +636,7 @@ class VerifyCommands(object):
table_label="Verification") table_label="Verification")
if detailed: if detailed:
h = _("Run arguments") h = "Run arguments"
print("\n%s" % cliutils.make_header(h, len(h)).strip()) print("\n%s" % cliutils.make_header(h, len(h)).strip())
print("\n%s\n" % json.dumps(verification["run_args"], indent=4)) print("\n%s\n" % json.dumps(verification["run_args"], indent=4))
@ -660,8 +655,7 @@ class VerifyCommands(object):
if failures: if failures:
self._print_failures("Failures", failures) self._print_failures("Failures", failures)
else: else:
print(_("\nCongratulations! Verification doesn't have failed " print("\nCongratulations! Verification passed all tests ;)")
"tests! :)"))
@cliutils.help_group("verification") @cliutils.help_group("verification")
@cliutils.args("--id", dest="verifier_id", type=str, required=False, @cliutils.args("--id", dest="verifier_id", type=str, required=False,
@ -698,11 +692,10 @@ class VerifyCommands(object):
cliutils.print_list(verifications, fields, formatters=formatters, cliutils.print_list(verifications, fields, formatters=formatters,
normalize_field_names=True, sortby_index=4) normalize_field_names=True, sortby_index=4)
elif verifier_id or deployment or status or tags: elif verifier_id or deployment or status or tags:
print(_("There are no verifications that meet specified filter " print("There are no verifications that meet specified criteria.")
"arguments."))
else: else:
print(_("There are no verifications. You can start verification, " print("There are no verifications. You can start verification, "
"using command `rally verify start`.")) "using command `rally verify start`.")
@cliutils.help_group("verification") @cliutils.help_group("verification")
@cliutils.args("--uuid", nargs="+", dest="verification_uuid", type=str, @cliutils.args("--uuid", nargs="+", dest="verification_uuid", type=str,
@ -743,7 +736,7 @@ class VerifyCommands(object):
output_type=output_type, output_type=output_type,
output_dest=output_dest) output_dest=output_dest)
if "files" in result: if "files" in result:
print(_("Saving the report to '%s' file. It may take some time.") print("Saving the report to '%s' file. It may take some time."
% output_dest) % output_dest)
for path in result["files"]: for path in result["files"]:
full_path = os.path.abspath(os.path.expanduser(path)) full_path = os.path.abspath(os.path.expanduser(path))
@ -751,12 +744,12 @@ class VerifyCommands(object):
os.makedirs(os.path.dirname(full_path)) os.makedirs(os.path.dirname(full_path))
with open(full_path, "w") as f: with open(full_path, "w") as f:
f.write(result["files"][path]) f.write(result["files"][path])
print(_("The report has been successfully saved.")) print("The report has been successfully saved.")
if open_it: if open_it:
if "open" not in result: if "open" not in result:
print(_("Cannot open '%s' report in the browser because " print("Cannot open '%s' report in the browser because "
"report type doesn't support it.") % output_type) "report type doesn't support it." % output_type)
return 1 return 1
webbrowser.open_new_tab( webbrowser.open_new_tab(
"file://" + os.path.abspath(result["open"])) "file://" + os.path.abspath(result["open"]))
@ -764,7 +757,7 @@ class VerifyCommands(object):
if "print" in result: if "print" in result:
# NOTE(andreykurilin): we need a separation between logs and # NOTE(andreykurilin): we need a separation between logs and
# printed information to be able to parse output # printed information to be able to parse output
h = _("Verification Report") h = "Verification Report"
print("\n%s\n%s" % (cliutils.make_header(h, len(h)), print("\n%s\n%s" % (cliutils.make_header(h, len(h)),
result["print"])) result["print"]))
@ -791,7 +784,7 @@ class VerifyCommands(object):
file_to_parse=None, run_args=None, do_use=True): file_to_parse=None, run_args=None, do_use=True):
"""Import results of a test run into the Rally database.""" """Import results of a test run into the Rally database."""
if not os.path.exists(file_to_parse): if not os.path.exists(file_to_parse):
print(_("File '%s' not found.") % file_to_parse) print("File '%s' not found." % file_to_parse)
return 1 return 1
with open(file_to_parse, "r") as f: with open(file_to_parse, "r") as f:
data = f.read() data = f.read()
@ -806,4 +799,4 @@ class VerifyCommands(object):
if do_use: if do_use:
self.use(api, verification_uuid) self.use(api, verification_uuid)
else: else:
print(_("Verification UUID: %s.") % verification_uuid) print("Verification UUID: %s." % verification_uuid)

View File

@ -19,7 +19,6 @@ import decorator
from oslo_utils import strutils from oslo_utils import strutils
from rally.common import fileutils from rally.common import fileutils
from rally.common.i18n import _
from rally import exceptions from rally import exceptions
ENV_DEPLOYMENT = "RALLY_DEPLOYMENT" ENV_DEPLOYMENT = "RALLY_DEPLOYMENT"
@ -28,7 +27,7 @@ ENV_VERIFIER = "RALLY_VERIFIER"
ENV_VERIFICATION = "RALLY_VERIFICATION" ENV_VERIFICATION = "RALLY_VERIFICATION"
ENVVARS = [ENV_DEPLOYMENT, ENV_TASK, ENV_VERIFIER, ENV_VERIFICATION] ENVVARS = [ENV_DEPLOYMENT, ENV_TASK, ENV_VERIFIER, ENV_VERIFICATION]
MSG_MISSING_ARG = _("Missing argument: --%(arg_name)s") MSG_MISSING_ARG = "Missing argument: --%(arg_name)s"
def clear_global(global_key): def clear_global(global_key):
@ -70,14 +69,13 @@ def default_from_global(arg_name, env_name,
def with_default_deployment(cli_arg_name="uuid"): def with_default_deployment(cli_arg_name="uuid"):
return default_from_global("deployment", ENV_DEPLOYMENT, cli_arg_name, return default_from_global(
message=_("There is no default deployment.\n" "deployment", ENV_DEPLOYMENT, cli_arg_name,
message="There is no default deployment.\n"
"\tPlease use command:\n" "\tPlease use command:\n"
"\trally deployment use " "\trally deployment use <deployment_uuid>|<deployment_name>\n"
"<deployment_uuid>|<deployment_name>" "or pass uuid of deployment to the --%(arg_name)s "
"\nor pass uuid of deployment to " "argument of this command")
"the --%(arg_name)s argument of "
"this command"))
def with_default_verifier_id(cli_arg_name="id"): def with_default_verifier_id(cli_arg_name="id"):

View File

@ -15,7 +15,6 @@
import six import six
from rally.common.i18n import _
from rally.common.plugin import discover from rally.common.plugin import discover
@ -30,7 +29,7 @@ class RallyException(Exception):
with the keyword arguments provided to the constructor. with the keyword arguments provided to the constructor.
""" """
msg_fmt = _("%(message)s") msg_fmt = "%(message)s"
error_code = 500 error_code = 500
def __init__(self, message=None, **kwargs): def __init__(self, message=None, **kwargs):
@ -68,22 +67,22 @@ def make_exception(exc):
class InvalidArgumentsException(RallyException): class InvalidArgumentsException(RallyException):
error_code = 455 error_code = 455
msg_fmt = _("Invalid arguments: '%(message)s'") msg_fmt = "Invalid arguments: '%(message)s'"
class InvalidConfigException(RallyException): class InvalidConfigException(RallyException):
error_code = 456 error_code = 456
msg_fmt = _("This config has invalid schema: `%(message)s`") msg_fmt = "This config has invalid schema: `%(message)s`"
class InvalidTaskException(InvalidConfigException): class InvalidTaskException(InvalidConfigException):
error_code = 457 error_code = 457
msg_fmt = _("Task config is invalid: `%(message)s`") msg_fmt = "Task config is invalid: `%(message)s`"
class InvalidTaskConfig(InvalidTaskException): class InvalidTaskConfig(InvalidTaskException):
error_code = 458 error_code = 458
msg_fmt = _("Input task is invalid!\n\n" msg_fmt = ("Input task is invalid!\n\n"
"Subtask %(name)s[%(pos)s] has wrong configuration" "Subtask %(name)s[%(pos)s] has wrong configuration"
"\nSubtask configuration:\n%(config)s\n" "\nSubtask configuration:\n%(config)s\n"
"\nReason(s):\n %(reason)s") "\nReason(s):\n %(reason)s")
@ -91,138 +90,134 @@ class InvalidTaskConfig(InvalidTaskException):
class NotFoundException(RallyException): class NotFoundException(RallyException):
error_code = 404 error_code = 404
msg_fmt = _("The resource can not be found: %(message)s") msg_fmt = "The resource can not be found: %(message)s"
class ThreadTimeoutException(RallyException): class ThreadTimeoutException(RallyException):
error_code = 515 error_code = 515
msg_fmt = _("Iteration interrupted due to timeout.") msg_fmt = "Iteration interrupted due to timeout."
class PluginNotFound(NotFoundException): class PluginNotFound(NotFoundException):
error_code = 459 error_code = 459
msg_fmt = _("There is no plugin with name: `%(name)s` in " msg_fmt = "There is no plugin `%(name)s` in %(platform)s platform."
"%(platform)s platform.")
class PluginWithSuchNameExists(RallyException): class PluginWithSuchNameExists(RallyException):
error_code = 516 error_code = 516
msg_fmt = _("Plugin with such name: %(name)s already exists in " msg_fmt = (
"%(platform)s platform. It's module allocates at " "Plugin with such name: %(name)s already exists in %(platform)s "
"%(existing_path)s. You are trying to add plugin whose module " "platform. It's module allocates at %(existing_path)s. You are trying "
"allocates at %(new_path)s.") "to add plugin whose module allocates at %(new_path)s.")
class TaskNotFound(NotFoundException): class TaskNotFound(NotFoundException):
error_code = 460 error_code = 460
msg_fmt = _("Task with uuid=%(uuid)s not found.") msg_fmt = "Task with uuid=%(uuid)s not found."
class DeploymentNotFound(NotFoundException): class DeploymentNotFound(NotFoundException):
error_code = 461 error_code = 461
msg_fmt = _("Deployment %(deployment)s not found.") msg_fmt = "Deployment %(deployment)s not found."
class DeploymentNameExists(RallyException): class DeploymentNameExists(RallyException):
error_code = 462 error_code = 462
msg_fmt = _("Deployment name '%(deployment)s' already registered.") msg_fmt = "Deployment name '%(deployment)s' already registered."
class DeploymentNotFinishedStatus(RallyException): class DeploymentNotFinishedStatus(RallyException):
error_code = 463 error_code = 463
msg_fmt = _("Deployment '%(name)s' (UUID=%(uuid)s) is in" msg_fmt = "Deployment '%(name)s' (UUID=%(uuid)s) is '%(status)s'."
" '%(status)s' status.")
class DeploymentIsBusy(RallyException): class DeploymentIsBusy(RallyException):
error_code = 464 error_code = 464
msg_fmt = _("There are allocated resources for the deployment with " msg_fmt = "There are allocated resources for the deployment %(uuid)s."
"uuid=%(uuid)s.")
class RallyAssertionError(RallyException): class RallyAssertionError(RallyException):
msg_fmt = _("Assertion error: %(message)s") msg_fmt = "Assertion error: %(message)s"
class ResourceNotFound(NotFoundException): class ResourceNotFound(NotFoundException):
error_code = 465 error_code = 465
msg_fmt = _("Resource with id=%(id)s not found.") msg_fmt = "Resource with id=%(id)s not found."
class TimeoutException(RallyException): class TimeoutException(RallyException):
error_code = 517 error_code = 517
msg_fmt = _("Rally tired waiting for %(resource_type)s %(resource_name)s:" msg_fmt = ("Rally tired waiting for %(resource_type)s %(resource_name)s:"
"%(resource_id)s to become %(desired_status)s current " "%(resource_id)s to become %(desired_status)s current "
"status %(resource_status)s") "status %(resource_status)s")
class GetResourceFailure(RallyException): class GetResourceFailure(RallyException):
error_code = 518 error_code = 518
msg_fmt = _("Failed to get the resource %(resource)s: %(err)s") msg_fmt = "Failed to get the resource %(resource)s: %(err)s"
class GetResourceNotFound(GetResourceFailure): class GetResourceNotFound(GetResourceFailure):
error_code = 519 error_code = 519
msg_fmt = _("Resource %(resource)s is not found.") msg_fmt = "Resource %(resource)s is not found."
class GetResourceErrorStatus(GetResourceFailure): class GetResourceErrorStatus(GetResourceFailure):
error_code = 520 error_code = 520
msg_fmt = _("Resource %(resource)s has %(status)s status.\n" msg_fmt = "Resource %(resource)s has %(status)s status.\n Fault: %(fault)s"
"Fault: %(fault)s")
class ScriptError(RallyException): class ScriptError(RallyException):
msg_fmt = _("Script execution failed: %(message)s") msg_fmt = "Script execution failed: %(message)s"
class TaskInvalidStatus(RallyException): class TaskInvalidStatus(RallyException):
error_code = 466 error_code = 466
msg_fmt = _("Task `%(uuid)s` in `%(actual)s` status but `%(require)s` is " msg_fmt = ("Task `%(uuid)s` in `%(actual)s` status but `%(require)s` is "
"required.") "required.")
class InvalidAdminException(InvalidArgumentsException): class InvalidAdminException(InvalidArgumentsException):
error_code = 521 error_code = 521
msg_fmt = _("user '%(username)s' doesn't have 'admin' role") msg_fmt = "user '%(username)s' doesn't have 'admin' role"
class AuthenticationFailed(InvalidArgumentsException): class AuthenticationFailed(InvalidArgumentsException):
error_code = 401 error_code = 401
msg_fmt = _("Failed to authenticate to %(url)s for user '%(username)s'" msg_fmt = ("Failed to authenticate to %(url)s for user '%(username)s'"
" in project '%(project)s': %(etype)s: %(error)s") " in project '%(project)s': %(etype)s: %(error)s")
class InvalidScenarioArgument(RallyException): class InvalidScenarioArgument(RallyException):
error_code = 467 error_code = 467
msg_fmt = _("Invalid scenario argument: '%(message)s'") msg_fmt = "Invalid scenario argument: '%(message)s'"
class ContextSetupFailure(RallyException): class ContextSetupFailure(RallyException):
error_code = 524 error_code = 524
msg_fmt = _("Unable to setup context '%(ctx_name)s': '%(msg)s'") msg_fmt = "Unable to setup context '%(ctx_name)s': '%(msg)s'"
class ValidationError(RallyException): class ValidationError(RallyException):
error_code = 468 error_code = 468
msg_fmt = _("Validation error: %(message)s") msg_fmt = "Validation error: %(message)s"
class WorkerNotFound(NotFoundException): class WorkerNotFound(NotFoundException):
error_code = 469 error_code = 469
msg_fmt = _("Worker %(worker)s could not be found") msg_fmt = "Worker %(worker)s could not be found"
class WorkerAlreadyRegistered(RallyException): class WorkerAlreadyRegistered(RallyException):
error_code = 525 error_code = 525
msg_fmt = _("Worker %(worker)s already registered") msg_fmt = "Worker %(worker)s already registered"
class MultiplePluginsFound(RallyException): class MultiplePluginsFound(RallyException):
error_code = 470 error_code = 470
msg_fmt = _("Multiple plugins found: %(plugins)s for name %(name)s. " msg_fmt = ("Multiple plugins found: %(plugins)s for name %(name)s. "
"Use full name in input task.") "Use full name with platform to fix issue.")
class SSHTimeout(RallyException): class SSHTimeout(RallyException):
@ -237,10 +232,9 @@ class SSHError(RallyException):
class InvalidConnectionString(RallyException): class InvalidConnectionString(RallyException):
error_code = 471 error_code = 471
msg_fmt = _("The connection string is not valid: %(message)s. Please " msg_fmt = "Invalid connection string: %(message)s."
"check your connection string.")
class DowngradeNotSupported(RallyException): class DowngradeNotSupported(RallyException):
error_code = 528 error_code = 528
msg_fmt = _("Database schema downgrade is not supported.") msg_fmt = "Database schema downgrade is not supported."

View File

@ -20,7 +20,6 @@ from oslo_config import cfg
from six.moves.urllib import parse from six.moves.urllib import parse
from rally.cli import envutils from rally.cli import envutils
from rally.common.i18n import _
from rally.common import logging from rally.common import logging
from rally.common.plugin import plugin from rally.common.plugin import plugin
from rally import consts from rally import consts
@ -114,18 +113,17 @@ class OSClient(plugin.Plugin):
supported_versions = cls.get_supported_versions() supported_versions = cls.get_supported_versions()
if supported_versions: if supported_versions:
if str(version) not in supported_versions: if str(version) not in supported_versions:
raise exceptions.ValidationError(_( raise exceptions.ValidationError(
"'%(vers)s' is not supported. Should be one of " "'%(vers)s' is not supported. Should be one of "
"'%(supported)s'") % {"vers": version, "'%(supported)s'"
"supported": supported_versions}) % {"vers": version, "supported": supported_versions})
else: else:
raise exceptions.RallyException( raise exceptions.RallyException("Setting version is not supported")
_("Setting version is not supported."))
try: try:
float(version) float(version)
except ValueError: except ValueError:
raise exceptions.ValidationError(_( raise exceptions.ValidationError(
"'%s' is invalid. Should be numeric value.") % version) "'%s' is invalid. Should be numeric value." % version)
def choose_service_type(self, service_type=None): def choose_service_type(self, service_type=None):
"""Return service_type string. """Return service_type string.
@ -141,8 +139,8 @@ class OSClient(plugin.Plugin):
def is_service_type_configurable(cls): def is_service_type_configurable(cls):
"""Just checks that client supports setting service type.""" """Just checks that client supports setting service type."""
if cls._meta_get("default_service_type") is None: if cls._meta_get("default_service_type") is None:
raise exceptions.RallyException(_( raise exceptions.RallyException(
"Setting service type is not supported.")) "Setting service type is not supported.")
@property @property
def keystone(self): def keystone(self):
@ -223,8 +221,8 @@ class Keystone(OSClient):
@property @property
def keystone(self): def keystone(self):
raise exceptions.RallyException(_("Method 'keystone' is restricted " raise exceptions.RallyException(
"for keystoneclient. :)")) "Method 'keystone' is restricted for keystoneclient. :)")
@property @property
def service_catalog(self): def service_catalog(self):
@ -702,7 +700,7 @@ class EC2(OSClient):
if kc.version != "v2.0": if kc.version != "v2.0":
raise exceptions.RallyException( raise exceptions.RallyException(
_("Rally EC2 scenario supports only Keystone version 2")) "Rally EC2 scenario supports only Keystone version 2")
ec2_credential = kc.ec2.create(user_id=kc.auth_user_id, ec2_credential = kc.ec2.create(user_id=kc.auth_user_id,
tenant_id=kc.auth_tenant_id) tenant_id=kc.auth_tenant_id)
client = boto.connect_ec2_endpoint( client = boto.connect_ec2_endpoint(

View File

@ -21,7 +21,6 @@ import sys
import six import six
from rally.common.i18n import _LE, _LI
from rally.common.io import subunit_v2 from rally.common.io import subunit_v2
from rally.common import logging from rally.common import logging
from rally.common.plugin import plugin from rally.common.plugin import plugin
@ -196,10 +195,10 @@ class VerifierManager(plugin.Plugin):
% source) % source)
if logging.is_debug(): if logging.is_debug():
LOG.debug("Cloning verifier repo from %s into %s.", source, LOG.debug("Cloning verifier repo from %s into %s."
self.repo_dir) % (source, self.repo_dir))
else: else:
LOG.info("Cloning verifier repo from %s.", source) LOG.info("Cloning verifier repo from %s." % source)
cmd = ["git", "clone", source, self.repo_dir] cmd = ["git", "clone", source, self.repo_dir]
@ -259,8 +258,8 @@ class VerifierManager(plugin.Plugin):
LOG.info("Creating virtual environment. It may take a few minutes.") LOG.info("Creating virtual environment. It may take a few minutes.")
LOG.debug("Initializing virtual environment in %s directory.", LOG.debug("Initializing virtual environment in %s directory."
self.venv_dir) % self.venv_dir)
utils.check_output(["virtualenv", "-p", sys.executable, self.venv_dir], utils.check_output(["virtualenv", "-p", sys.executable, self.venv_dir],
cwd=self.repo_dir, cwd=self.repo_dir,
msg_on_err="Failed to initialize virtual env " msg_on_err="Failed to initialize virtual env "
@ -293,7 +292,7 @@ class VerifierManager(plugin.Plugin):
def checkout(self, version): def checkout(self, version):
"""Switch a verifier repo.""" """Switch a verifier repo."""
LOG.info("Switching verifier repo to the '%s' version.", version) LOG.info("Switching verifier repo to the '%s' version." % version)
utils.check_output(["git", "checkout", "master"], cwd=self.repo_dir) utils.check_output(["git", "checkout", "master"], cwd=self.repo_dir)
utils.check_output(["git", "remote", "update"], cwd=self.repo_dir) utils.check_output(["git", "remote", "update"], cwd=self.repo_dir)
utils.check_output(["git", "pull"], cwd=self.repo_dir) utils.check_output(["git", "pull"], cwd=self.repo_dir)
@ -309,7 +308,7 @@ class VerifierManager(plugin.Plugin):
configuration configuration
""" """
raise NotImplementedError( raise NotImplementedError(
_LI("'%s' verifiers don't support configuration at all.") "'%s' verifiers don't support configuration at all."
% self.get_name()) % self.get_name())
def is_configured(self): def is_configured(self):
@ -330,7 +329,7 @@ class VerifierManager(plugin.Plugin):
configuration configuration
""" """
raise NotImplementedError( raise NotImplementedError(
_LE("'%s' verifiers don't support configuration at all.") "'%s' verifiers don't support configuration at all."
% self.get_name()) % self.get_name())
def extend_configuration(self, extra_options): def extend_configuration(self, extra_options):
@ -342,7 +341,7 @@ class VerifierManager(plugin.Plugin):
configuration configuration
""" """
raise NotImplementedError( raise NotImplementedError(
_LE("'%s' verifiers don't support configuration at all.") "'%s' verifiers don't support configuration at all."
% self.get_name()) % self.get_name())
def install_extension(self, source, version=None, extra_settings=None): def install_extension(self, source, version=None, extra_settings=None):
@ -358,7 +357,7 @@ class VerifierManager(plugin.Plugin):
extensions extensions
""" """
raise NotImplementedError( raise NotImplementedError(
_LE("'%s' verifiers don't support extensions.") % self.get_name()) "'%s' verifiers don't support extensions." % self.get_name())
def list_extensions(self): def list_extensions(self):
"""List all verifier extensions.""" """List all verifier extensions."""
@ -373,7 +372,7 @@ class VerifierManager(plugin.Plugin):
extensions extensions
""" """
raise NotImplementedError( raise NotImplementedError(
_LE("'%s' verifiers don't support extensions.") % self.get_name()) "'%s' verifiers don't support extensions." % self.get_name())
@abc.abstractmethod @abc.abstractmethod
def list_tests(self, pattern=""): def list_tests(self, pattern=""):

View File

@ -59,7 +59,7 @@ def check_output(*args, **kwargs):
raise raise
if output and debug_output: if output and debug_output:
LOG.debug("Subprocess output: '%s'", encodeutils.safe_decode(output)) LOG.debug("Subprocess output: '%s'" % encodeutils.safe_decode(output))
return output return output

View File

@ -13,7 +13,6 @@
# 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 rally.common.i18n import _
from rally.common.plugin import plugin from rally.common.plugin import plugin
from rally.task import sla from rally.task import sla
@ -48,5 +47,5 @@ class MaxDurationRange(sla.SLA):
return self.success return self.success
def details(self): def details(self):
return (_("%s - Maximum allowed duration range: %.2f%% <= %.2f%%") % return ("%s - Maximum allowed duration range: %.2f%% <= %.2f%%" %
(self.status(), self._max - self._min, self.criterion_value)) (self.status(), self._max - self._min, self.criterion_value))

View File

@ -243,7 +243,7 @@ def _read_requirements():
"""Read all rally requirements.""" """Read all rally requirements."""
LOG.info("Reading rally requirements...") LOG.info("Reading rally requirements...")
for file_name in RALLY_REQUIREMENTS_FILES: for file_name in RALLY_REQUIREMENTS_FILES:
LOG.debug("Try to read '%s'.", file_name) LOG.debug("Try to read '%s'." % file_name)
with open(file_name) as f: with open(file_name) as f:
data = f.read() data = f.read()
LOG.info("Parsing requirements from %s." % file_name) LOG.info("Parsing requirements from %s." % file_name)
@ -263,7 +263,7 @@ def _sync():
LOG.info("Obtaining global-requirements...") LOG.info("Obtaining global-requirements...")
for i in range(0, len(GLOBAL_REQUIREMENTS_LOCATIONS)): for i in range(0, len(GLOBAL_REQUIREMENTS_LOCATIONS)):
url = GLOBAL_REQUIREMENTS_LOCATIONS[i] + GLOBAL_REQUIREMENTS_FILENAME url = GLOBAL_REQUIREMENTS_LOCATIONS[i] + GLOBAL_REQUIREMENTS_FILENAME
LOG.debug("Try to obtain global-requirements from %s", url) LOG.debug("Try to obtain global-requirements from %s" % url)
try: try:
raw_gr = requests.get(url).text raw_gr = requests.get(url).text
except requests.ConnectionError as e: except requests.ConnectionError as e:
@ -309,7 +309,7 @@ def format_requirements():
def add_uppers(): def add_uppers():
"""Obtains latest version of packages and put them to requirements.""" """Obtains latest version of packages and put them to requirements."""
for filename, requirements in _sync(): for filename, requirements in _sync():
LOG.info("Obtaining latest versions of packages for %s.", filename) LOG.info("Obtaining latest versions of packages for %s." % filename)
for req in requirements: for req in requirements:
if isinstance(req, Requirement): if isinstance(req, Requirement):
if isinstance(req.version, dict) and not req.version["max"]: if isinstance(req.version, dict) and not req.version["max"]: