diff --git a/CHANGES/2477.bugfix b/CHANGES/2477.bugfix new file mode 100644 index 0000000000..41cc4accad --- /dev/null +++ b/CHANGES/2477.bugfix @@ -0,0 +1,2 @@ +Removed il8n from the logs written so they will always show up in English for speedy resolution of +error messages. All user facing strings are still expected to be il8n. diff --git a/CHANGES/plugin_api/2477.doc b/CHANGES/plugin_api/2477.doc new file mode 100644 index 0000000000..afe23f428a --- /dev/null +++ b/CHANGES/plugin_api/2477.doc @@ -0,0 +1,2 @@ +Added docs on the expectation that all user-facing strings are i8ln wrapped with gettext, but log +messages are not. diff --git a/docs/plugins/plugin-writer/concepts/index.rst b/docs/plugins/plugin-writer/concepts/index.rst index 4b7c2beb48..c74956014a 100644 --- a/docs/plugins/plugin-writer/concepts/index.rst +++ b/docs/plugins/plugin-writer/concepts/index.rst @@ -516,3 +516,19 @@ is allowed to handle. This includes two types of "checksum handling": requested that is not listed in the ``ALLOWED_CONTENT_CHECKSUMS`` setting. This is a convenience facility allowing plugin writers to not check the ``ALLOWED_CONTENT_CHECKSUMS`` setting themselves. + + +.. _il8n-expectations: + +Internationalization Expectations +--------------------------------- + +pulpcore and its plugins are expected to internationalize all user-facing strings using Python's +gettext facilities. This allows Pulp to be translated to other languages and be more usable for a +broader base of users. + +Administrator facing strings are expected *not* to be internationalized. These include all log +statements, migration output print statements, django management commands, etc. These not being +internationalized will remain in English. This expectation was formed after feedback from +multi-language speakers who believe having error messages for admins in English would reduce the +time to finding a fix and was generally less surprising. diff --git a/pulpcore/app/apps.py b/pulpcore/app/apps.py index 4ad572238f..35f36a5282 100644 --- a/pulpcore/app/apps.py +++ b/pulpcore/app/apps.py @@ -66,10 +66,9 @@ def __init__(self, app_name, app_module): try: self.version except AttributeError: - msg = _( - "The plugin `{}` is missing a version declaration. Starting with " - "pulpcore==3.10, plugins are required to define their version on the " - "PulpPluginAppConfig subclass." + msg = ( + "The plugin `{}` is missing a version declaration. Starting with pulpcore==3.10, " + "plugins are required to define their version on the PulpPluginAppConfig subclass." ) raise ImproperlyConfigured(msg.format(self.label)) @@ -218,7 +217,7 @@ def _populate_access_policies(sender, apps, verbosity, **kwargs): if created: if verbosity >= 1: print( - _("Access policy for {viewset_name} created.").format( + "Access policy for {viewset_name} created.".format( viewset_name=viewset_name ) ) @@ -228,7 +227,7 @@ def _populate_access_policies(sender, apps, verbosity, **kwargs): db_access_policy.save() if verbosity >= 1: print( - _("Access policy for {viewset_name} updated.").format( + "Access policy for {viewset_name} updated.".format( viewset_name=viewset_name ) ) diff --git a/pulpcore/app/management/commands/add-signing-service.py b/pulpcore/app/management/commands/add-signing-service.py index 25255fd14a..a53321a9c1 100644 --- a/pulpcore/app/management/commands/add-signing-service.py +++ b/pulpcore/app/management/commands/add-signing-service.py @@ -16,7 +16,7 @@ class Command(BaseCommand): This command is in tech-preview. """ - help = _("Adds a new AsciiArmoredDetachedSigningService. [tech-preview]") + help = "Adds a new AsciiArmoredDetachedSigningService. [tech-preview]" def add_arguments(self, parser): parser.add_argument( @@ -75,7 +75,7 @@ def handle(self, *args, **options): raise CommandError(str(e)) print( - _("Successfully added signing service {name} for key {fingerprint}.").format( + ("Successfully added signing service {name} for key {fingerprint}.").format( name=name, fingerprint=fingerprint ) ) diff --git a/pulpcore/app/management/commands/analyze-publication.py b/pulpcore/app/management/commands/analyze-publication.py index 7b7365fd46..21e897e65a 100644 --- a/pulpcore/app/management/commands/analyze-publication.py +++ b/pulpcore/app/management/commands/analyze-publication.py @@ -10,7 +10,7 @@ class Command(BaseCommand): """Django management command for viewing files in a publication and the artifacts on disk.""" - help = _(__doc__) + help = __doc__ def add_arguments(self, parser): """Set up arguments.""" diff --git a/pulpcore/app/management/commands/datarepair-2327.py b/pulpcore/app/management/commands/datarepair-2327.py index f8ed783f57..8d7bc5a4c2 100644 --- a/pulpcore/app/management/commands/datarepair-2327.py +++ b/pulpcore/app/management/commands/datarepair-2327.py @@ -16,7 +16,7 @@ class Command(BaseCommand): Django management command for repairing incorrectly migrated remote data. """ - help = _( + help = ( "Repairs issue #2327. A small number of configuration settings may have been " "corrupted during an upgrade from a previous version of Pulp to a Pulp version " "between 3.15-3.18, resulting in trouble when syncing or viewing certain remotes. " diff --git a/pulpcore/app/management/commands/handle-artifact-checksums.py b/pulpcore/app/management/commands/handle-artifact-checksums.py index df26973b32..6184c20b0d 100644 --- a/pulpcore/app/management/commands/handle-artifact-checksums.py +++ b/pulpcore/app/management/commands/handle-artifact-checksums.py @@ -27,7 +27,7 @@ class Command(BaseCommand): Django management command for populating or removing checksums on artifacts. """ - help = _("Handle missing and forbidden checksums on the artifacts") + help = "Handle missing and forbidden checksums on the artifacts" def add_arguments(self, parser): parser.add_argument("--report", action="store_true") @@ -44,13 +44,11 @@ def _print_out_repository_version_hrefs(self, repo_versions): """ for repo_version in repo_versions.iterator(): self.stdout.write( - _( - "/repositories/{plugin}/{type}/{pk}/versions/{number}/".format( - plugin=repo_version.repository.pulp_type.split(".")[0], - type=repo_version.repository.pulp_type.split(".")[1], - pk=str(repo_version.repository.pk), - number=repo_version.number, - ) + "/repositories/{plugin}/{type}/{pk}/versions/{number}/".format( + plugin=repo_version.repository.pulp_type.split(".")[0], + type=repo_version.repository.pulp_type.split(".")[1], + pk=str(repo_version.repository.pk), + number=repo_version.number, ) ) @@ -69,11 +67,11 @@ def _show_on_demand_content(self, checksums): repo_versions = RepositoryVersion.objects.with_content(content).select_related("repository") self.stdout.write( - _("Found {} on-demand content units with forbidden checksums.").format(content.count()) + "Found {} on-demand content units with forbidden checksums.".format(content.count()) ) if content.count(): self.stdout.write( - _("There is approx {:.2f}Mb of content to be downloaded.").format( + "There is approx {:.2f}Mb of content to be downloaded.".format( ras_size / (1024**2) ) ) @@ -100,13 +98,13 @@ def _show_immediate_content(self, forbidden_checksums): repo_versions = RepositoryVersion.objects.with_content(content).select_related("repository") self.stdout.write( - _("Found {} downloaded content units with forbidden or missing checksums.").format( + "Found {} downloaded content units with forbidden or missing checksums.".format( content.count() ) ) if content.count() > 0: self.stdout.write( - _("There is approx. {:.2f}Mb content data to be re-hashed.").format( + "There is approx. {:.2f}Mb content data to be re-hashed.".format( artifacts.aggregate(Sum("size"))["size__sum"] / (1024**2) ) ) @@ -150,10 +148,8 @@ def _report(self, allowed_checksums): ) self.stderr.write( - _( - "Warning: the handle-artifact-checksums report is in " - "tech preview and may change in the future." - ) + "Warning: the handle-artifact-checksums report is in tech preview and may change in " + "the future." ) self._show_on_demand_content(forbidden_checksums) self._show_immediate_content(forbidden_checksums) @@ -197,7 +193,7 @@ def handle(self, *args, **options): if hrefs: raise CommandError( - _("Some files that were missing could not be restored: {}").format(hrefs) + "Some files that were missing could not be restored: {}".format(hrefs) ) forbidden_checksums = set(constants.ALL_KNOWN_CONTENT_CHECKSUMS).difference( @@ -208,9 +204,7 @@ def handle(self, *args, **options): update_params = {f"{checksum}": None} artifacts_qs = Artifact.objects.filter(**search_params) if artifacts_qs.exists(): - self.stdout.write( - _("Removing forbidden checksum {} from database").format(checksum) - ) + self.stdout.write("Removing forbidden checksum {} from database".format(checksum)) artifacts_qs.update(**update_params) self.stdout.write(_("Finished aligning checksums with settings.ALLOWED_CONTENT_CHECKSUMS")) diff --git a/pulpcore/app/management/commands/remove-plugin.py b/pulpcore/app/management/commands/remove-plugin.py index 2d9d157b92..c83b91939b 100644 --- a/pulpcore/app/management/commands/remove-plugin.py +++ b/pulpcore/app/management/commands/remove-plugin.py @@ -36,7 +36,7 @@ class Command(BaseCommand): This command is in tech-preview. """ - help = _( + help = ( "[tech-preview] Disable a Pulp plugin and remove all the relevant data from the database. " "Destructive!" ) @@ -55,9 +55,7 @@ def _check_pulp_services(self): waiting_time = max(settings.CONTENT_APP_TTL, settings.WORKER_TTL) check_started = time.time() self.stdout.write( - _("Checking if Pulp services are running, it can take up to {}s...").format( - waiting_time - ) + "Checking if Pulp services are running, it can take up to {}s...".format(waiting_time) ) while is_pulp_running and (time.time() - check_started) < waiting_time: is_pulp_running = ( @@ -68,11 +66,8 @@ def _check_pulp_services(self): if is_pulp_running: raise CommandError( - _( - "The command can't be used when Pulp services are running. " - "Please stop the services: pulpcore-api, pulpcore-content and all " - "pulpcore-worker@*." - ) + "The command can't be used when Pulp services are running. Please stop the " + "services: pulpcore-api, pulpcore-content and all pulpcore-worker@*." ) def _remove_indirect_plugin_data(self, app_label): @@ -127,7 +122,7 @@ def _remove_plugin_data(self, app_label): if models_to_delete: # Never-happen case raise CommandError( - _( + ( "Data for the following models can't be removed: {}. Please contact plugin " "maintainers." ).format(list(models_to_delete)) @@ -178,7 +173,7 @@ def handle(self, *args, **options): available_plugins = {app.label for app in pulp_plugin_configs()} - {"core"} if plugin_name not in available_plugins: raise CommandError( - _( + ( "Plugin name is incorrectly specified or plugin is not installed. Please " "specify one of the following plugin names: {}." ).format(list(available_plugins)) @@ -193,7 +188,7 @@ def handle(self, *args, **options): self._unapply_migrations(app_label=plugin_name) self.stdout.write( - _( + ( "Successfully removed the {} plugin data. It is ready to be uninstalled. " "NOTE: Please do uninstall, otherwise `pulp status` might not show you the correct " "list of plugins available." diff --git a/pulpcore/app/management/commands/reset-admin-password.py b/pulpcore/app/management/commands/reset-admin-password.py index 0eda1bc9d7..f1173940e6 100644 --- a/pulpcore/app/management/commands/reset-admin-password.py +++ b/pulpcore/app/management/commands/reset-admin-password.py @@ -12,7 +12,7 @@ class Command(BaseCommand): Django management command for resetting the password of the 'admin' user in Pulp. """ - help = _('Resets "admin" user\'s password.') + help = 'Resets "admin" user\'s password.' def add_arguments(self, parser): exclusive = parser.add_mutually_exclusive_group() diff --git a/pulpcore/app/management/commands/stage-profile-summary.py b/pulpcore/app/management/commands/stage-profile-summary.py index d5a57a2653..0cfb1539bb 100644 --- a/pulpcore/app/management/commands/stage-profile-summary.py +++ b/pulpcore/app/management/commands/stage-profile-summary.py @@ -8,7 +8,7 @@ class Command(BaseCommand): Django management command for printing a summary report of a Stages API pipeline run. """ - help = _( + help = ( "Print a summary of a Stages API pipeline run. This command is provided as a tech " "preview and may not work properly or change in the future." ) @@ -55,7 +55,7 @@ def handle(self, *args, **options): stages_map[row[0]]["interarrival_time_sum"] += row[2] for stage in stages: - msg = _("{name}\n\tservice time average: {srv_avg:4f}\n") + msg = "{name}\n\tservice time average: {srv_avg:4f}\n" if in_queue_count == 0: # This is the first queue that gets no put() calls, so avoid DivisionByZero errors waiting_avg = srv_avg = length_avg = interarrival_avg = 0 diff --git a/pulpcore/app/migrations/0061_call_handle_artifact_checksums_command.py b/pulpcore/app/migrations/0061_call_handle_artifact_checksums_command.py index 2f1b64c563..8a74c73108 100644 --- a/pulpcore/app/migrations/0061_call_handle_artifact_checksums_command.py +++ b/pulpcore/app/migrations/0061_call_handle_artifact_checksums_command.py @@ -43,8 +43,8 @@ def handle_artifact_checksums(apps): Artifact.objects.bulk_update(objs=artifacts, fields=[checksum], batch_size=1000) if paths: - _logger.warn( - _( + _logger.warning( + ( "Missing files needed to update artifact {checksum} checksum: {paths}. " "Please run 'pulpcore-manager handle-artifact-checksums'." ).format(checksum=checksum, paths=paths) @@ -66,8 +66,8 @@ def run_handle_artifact_checksums(apps, schema_editor): try: handle_artifact_checksums(apps) except Exception as exc: - _logger.warn( - _( + _logger.warning( + ( "Failed to update checksums for artifacts: {}. " "Please run 'pulpcore-manager handle-artifact-checksums'." ).format(exc) diff --git a/pulpcore/app/models/repository.py b/pulpcore/app/models/repository.py index b73cc7a63e..948616a7d2 100644 --- a/pulpcore/app/models/repository.py +++ b/pulpcore/app/models/repository.py @@ -242,9 +242,7 @@ def cleanup_old_versions(self): self.retain_repo_versions : ]: _logger.info( - _("Deleting repository version {} due to version retention limit.").format( - version - ) + "Deleting repository version {} due to version retention limit.".format(version) ) version.delete() diff --git a/pulpcore/app/models/task.py b/pulpcore/app/models/task.py index d7dd0ae56d..49f1893539 100644 --- a/pulpcore/app/models/task.py +++ b/pulpcore/app/models/task.py @@ -258,7 +258,7 @@ def set_completed(self): .update(state=TASK_STATES.COMPLETED, finished_at=timezone.now()) ) if rows != 1: - msg = _("Task set_completed() occurred but Task %s is already in final state") + msg = "Task set_completed() occurred but Task %s is already in final state" _logger.warning(msg % self.pk) self.refresh_from_db() diff --git a/pulpcore/app/settings.py b/pulpcore/app/settings.py index 96d93155f7..64bbe1986e 100644 --- a/pulpcore/app/settings.py +++ b/pulpcore/app/settings.py @@ -11,7 +11,6 @@ import sys from contextlib import suppress -from gettext import gettext as _ from importlib import import_module from logging import getLogger from pathlib import Path @@ -304,7 +303,7 @@ "CONTENT_ORIGIN", must_exist=True, messages={ - "must_exist_true": _( + "must_exist_true": ( "CONTENT_ORIGIN is a required setting but it was not configured. This may be caused " "by invalid read permissions of the settings file. Note that CONTENT_ORIGIN is set by " "the installer automatically." @@ -317,7 +316,7 @@ redis_host_validator = Validator("REDIS_HOST", must_exist=True, when=cache_enabled_validator) redis_port_validator = Validator("REDIS_PORT", must_exist=True, when=cache_enabled_validator) cache_validator = redis_url_validator | (redis_host_validator & redis_port_validator) -cache_validator.messages["combined"] = _( +cache_validator.messages["combined"] = ( "CACHE_ENABLED is enabled but it requires to have REDIS configured. Please check " "https://docs.pulpproject.org/pulpcore/configuration/settings.html#redis-settings " "for more information." @@ -336,7 +335,7 @@ "ALLOWED_CONTENT_CHECKSUMS", condition=lambda x: len(set(x).difference(constants.ALL_KNOWN_CONTENT_CHECKSUMS)) == 0, messages={ - "condition": _( + "condition": ( "ALLOWED_CONTENT_CHECKSUMS may only contain algorithms known to pulp - see " "constants.ALL_KNOWN_CONTENT_CHECKSUMS for the allowed list." ) @@ -347,7 +346,7 @@ "API_ROOT", condition=lambda x: x.startswith("/") and x.endswith("/"), messages={ - "condition": _("The API_ROOT must start and end with a '/', currently it is '{value}'") + "condition": ("The API_ROOT must start and end with a '/', currently it is '{value}'") }, ) @@ -384,7 +383,7 @@ Fernet(key_file.read()) except Exception as ex: raise ImproperlyConfigured( - _("Could not load DB_ENCRYPTION_KEY file '{file}': {err}").format( + ("Could not load DB_ENCRYPTION_KEY file '{file}': {err}").format( file=DB_ENCRYPTION_KEY, err=ex ) ) @@ -405,7 +404,7 @@ row = cursor.fetchone() if row[0] > 0: raise ImproperlyConfigured( - _( + ( "There have been identified artifacts missing checksum '{}'. " "Run 'pulpcore-manager handle-artifact-checksums' first to populate " "missing artifact checksums." @@ -419,7 +418,7 @@ row = cursor.fetchone() if row[0] > 0: raise ImproperlyConfigured( - _( + ( "There have been identified artifacts with forbidden checksum '{}'. " "Run 'pulpcore-manager handle-artifact-checksums' first to unset " "forbidden checksums." @@ -436,8 +435,8 @@ ) row = cursor.fetchone() if row[0] > 0: - _logger.warn( - _( + _logger.warning( + ( "Warning: detected remote content without allowed checksums. " "Run 'pulpcore-manager handle-artifact-checksums --report' to " "view this content." diff --git a/pulpcore/app/tasks/export.py b/pulpcore/app/tasks/export.py index 5ad7931911..f801582742 100644 --- a/pulpcore/app/tasks/export.py +++ b/pulpcore/app/tasks/export.py @@ -98,9 +98,9 @@ def fs_publication_export(exporter_pk, publication_pk): CreatedResource.objects.create(content_object=export) log.info( - _( - "Exporting: file_system_exporter={exporter}, publication={publication}, path=path" - ).format(exporter=exporter.name, publication=publication.pk, path=exporter.path) + "Exporting: file_system_exporter={exporter}, publication={publication}, path={path}".format( + exporter=exporter.name, publication=publication.pk, path=exporter.path + ) ) content_artifacts = ContentArtifact.objects.filter( @@ -134,9 +134,10 @@ def fs_repo_version_export(exporter_pk, repo_version_pk): CreatedResource.objects.create(content_object=export) log.info( - _( - "Exporting: file_system_exporter={exporter}, repo_version={repo_version}, path=path" - ).format(exporter=exporter.name, repo_version=repo_version.pk, path=exporter.path) + "Exporting: file_system_exporter={exporter}, repo_version={repo_version}, " + "path={path}".format( + exporter=exporter.name, repo_version=repo_version.pk, path=exporter.path + ) ) content_artifacts = ContentArtifact.objects.filter(content__in=repo_version.content) diff --git a/pulpcore/app/tasks/importer.py b/pulpcore/app/tasks/importer.py index bb6467d64f..097063bef9 100644 --- a/pulpcore/app/tasks/importer.py +++ b/pulpcore/app/tasks/importer.py @@ -71,7 +71,7 @@ def _import_file(fpath, resource_class, retry=False): a_result = resource.import_data(data, raise_errors=False) if a_result.has_errors(): log.info( - _("...{} import-errors encountered importing {}, retrying").format( + "...{} import-errors encountered importing {}, retrying".format( a_result.totals["error"], fpath ) ) @@ -351,7 +351,7 @@ def validate_and_assemble(toc_filename): subprocess.run(["rm", "-f", os.path.join(toc_dir, chunk)]) except OSError: log.warning( - _("Failed to remove chunk {} after recombining. Continuing.").format( + "Failed to remove chunk {} after recombining. Continuing.".format( os.path.join(toc_dir, chunk) ), exc_info=True, @@ -422,9 +422,7 @@ def validate_and_assemble(toc_filename): dest_repo = _destination_repo(importer, src_repo["name"]) except Repository.DoesNotExist: log.warning( - _("Could not find destination repo for {}. Skipping.").format( - src_repo["name"] - ) + "Could not find destination repo for {}. Skipping.".format(src_repo["name"]) ) continue diff --git a/pulpcore/app/tasks/repository.py b/pulpcore/app/tasks/repository.py index 512f19ac2d..241e56f714 100644 --- a/pulpcore/app/tasks/repository.py +++ b/pulpcore/app/tasks/repository.py @@ -52,7 +52,7 @@ def delete_version(pk): ) log.info( - _("Deleting and squashing version {num} of repository '{repo}'").format( + "Deleting and squashing version {num} of repository '{repo}'".format( num=version.number, repo=version.repository.name ) ) @@ -66,8 +66,8 @@ async def _repair_ca(content_artifact, repaired=None): ) if not remote_artifacts: - log.warn( - _("Artifact {} is unrepairable - no remote source".format(content_artifact.artifact)) + log.warning( + "Artifact {} is unrepairable - no remote source".format(content_artifact.artifact) ) return False @@ -166,7 +166,7 @@ def repair_version(repository_version_pk, verify_checksums): version = models.RepositoryVersion.objects.get(pk=repository_version_pk) log.info( - _("Repairing version {num} of repository '{repo}'").format( + "Repairing version {num} of repository '{repo}'".format( num=version.number, repo=version.repository.name ), ) diff --git a/pulpcore/app/viewsets/base.py b/pulpcore/app/viewsets/base.py index 09943aa203..27049cef0c 100644 --- a/pulpcore/app/viewsets/base.py +++ b/pulpcore/app/viewsets/base.py @@ -138,10 +138,10 @@ def get_serializer_class(self): The intention is that ViewSets can define a second, more minimal serializer with only the most important fields. """ - assert self.serializer_class is not None, _( + assert self.serializer_class is not None, ( "'{}' should either include a `serializer_class` attribute, or override the " - "`get_serializer_class()` method.".format(self.__class__.__name__) - ) + "`get_serializer_class()` method." + ).format(self.__class__.__name__) minimal_serializer_class = getattr(self, "minimal_serializer_class", None) if minimal_serializer_class: @@ -424,10 +424,9 @@ def async_reserved_resources(self, instance): AssertionError if instance is None (which happens for creation) """ - assert instance is not None, _( - "'{}' must not use the default `async_reserved_resources` method " - "when using create.".format(self.__class__.__name__) - ) + assert instance is not None, ( + "'{}' must not use the default `async_reserved_resources` method " "when using create." + ).format(self.__class__.__name__) return [instance] diff --git a/pulpcore/content/__init__.py b/pulpcore/content/__init__.py index bc96134a10..d6a47a847a 100644 --- a/pulpcore/content/__init__.py +++ b/pulpcore/content/__init__.py @@ -1,6 +1,5 @@ import asyncio from contextlib import suppress -from gettext import gettext as _ from importlib import import_module import logging import os @@ -37,8 +36,9 @@ async def _heartbeat(): name = "{pid}@{hostname}".format(pid=os.getpid(), hostname=socket.gethostname()) heartbeat_interval = settings.CONTENT_APP_TTL // 4 - i8ln_msg = _("Content App '{name}' heartbeat written, sleeping for '{interarrival}' seconds") - msg = i8ln_msg.format(name=name, interarrival=heartbeat_interval) + msg = "Content App '{name}' heartbeat written, sleeping for '{interarrival}' seconds".format( + name=name, interarrival=heartbeat_interval + ) while True: @@ -53,11 +53,10 @@ async def _heartbeat(): log.debug(msg) except (InterfaceError, OperationalError): await sync_to_async(Handler._reset_db_connection)() - i8ln_msg = _( + msg = ( "Content App '{name}' failed to write a heartbeat to the database, sleeping for " "'{interarrival}' seconds." - ) - msg = i8ln_msg.format(name=name, interarrival=heartbeat_interval) + ).format(name=name, interarrival=heartbeat_interval) log.info(msg) await asyncio.sleep(heartbeat_interval) diff --git a/pulpcore/content/handler.py b/pulpcore/content/handler.py index 55a80af49e..a5bf5ec688 100644 --- a/pulpcore/content/handler.py +++ b/pulpcore/content/handler.py @@ -250,7 +250,7 @@ def _match_distribution(cls, path): ) except ObjectDoesNotExist: log.debug( - _("Distribution not matched for {path} using: {base_paths}").format( + "Distribution not matched for {path} using: {base_paths}".format( path=path, base_paths=base_paths ) ) @@ -261,7 +261,7 @@ def _match_distribution(cls, path): ).get(base_path__in=base_paths) except ObjectDoesNotExist: log.debug( - _("Distribution not matched for {path} using: {base_paths}").format( + "Distribution not matched for {path} using: {base_paths}".format( path=path, base_paths=base_paths ) ) @@ -289,7 +289,7 @@ def _permit(request, distribution): guard.cast().permit(request) except PermissionError as pe: log.debug( - _('Path: %(p)s not permitted by guard: "%(g)s" reason: %(r)s'), + 'Path: %(p)s not permitted by guard: "%(g)s" reason: %(r)s', {"p": request.path, "g": guard.name, "r": str(pe)}, ) raise HTTPForbidden(reason=str(pe)) @@ -530,7 +530,7 @@ def get_contentartifact_blocking(): ca = await sync_to_async(get_contentartifact_blocking)() except MultipleObjectsReturned: log.error( - _("Multiple (pass-through) matches for {b}/{p}"), + "Multiple (pass-through) matches for {b}/{p}", {"b": distro.base_path, "p": rel_path}, ) raise @@ -576,7 +576,7 @@ def get_contentartifact_blocking(): ca = await sync_to_async(get_contentartifact_blocking)() except MultipleObjectsReturned: log.error( - _("Multiple (pass-through) matches for {b}/{p}"), + "Multiple (pass-through) matches for {b}/{p}", {"b": distro.base_path, "p": rel_path}, ) raise @@ -664,7 +664,7 @@ def get_remote_artifacts_blocking(): except (ClientResponseError, UnsupportedDigestValidationError) as e: log.warning( - _("Could not download remote artifact at '{}': {}").format( + "Could not download remote artifact at '{}': {}".format( remote_artifact.url, str(e) ) ) @@ -823,7 +823,7 @@ async def _stream_remote_artifact(self, request, response, remote_artifact): remote = await sync_to_async(remote_artifact.remote.cast)() log.debug( - _("Streaming content for {url} from Remote {remote}-{source}").format( + "Streaming content for {url} from Remote {remote}-{source}".format( url=request.match_info["path"], remote=remote.name, source=remote_artifact.url ) ) diff --git a/pulpcore/plugin/stages/api.py b/pulpcore/plugin/stages/api.py index 0fd2a3ab9b..006d7167c9 100644 --- a/pulpcore/plugin/stages/api.py +++ b/pulpcore/plugin/stages/api.py @@ -149,7 +149,7 @@ def add_to_batch(content): if batch and (len(batch) >= minsize or shutdown or no_block): log.debug( - _("%(name)s - next batch[%(length)d]."), {"name": self, "length": len(batch)} + "%(name)s - next batch[%(length)d].", {"name": self, "length": len(batch)} ) for content in batch: content._thaw_queue_event = None diff --git a/pulpcore/plugin/stages/artifact_stages.py b/pulpcore/plugin/stages/artifact_stages.py index 480df862ba..e93f771672 100644 --- a/pulpcore/plugin/stages/artifact_stages.py +++ b/pulpcore/plugin/stages/artifact_stages.py @@ -350,7 +350,7 @@ async def _handle_remote_artifacts(self, batch): ] ) if avail_paths: - msg = _( + msg = ( "No declared artifact with relative path '{rp}' for content '{c}'" " from remote '{rname}'. Using last from available-paths : '{ap}'" ) diff --git a/pulpcore/tasking/pulpcore_worker.py b/pulpcore/tasking/pulpcore_worker.py index af1eeceb1b..8a5f5e8404 100644 --- a/pulpcore/tasking/pulpcore_worker.py +++ b/pulpcore/tasking/pulpcore_worker.py @@ -105,7 +105,7 @@ def handle_worker_heartbeat(worker_name): worker.save_heartbeat() - msg = _("Worker heartbeat from '{name}' at time {timestamp}").format( + msg = "Worker heartbeat from '{name}' at time {timestamp}".format( timestamp=worker.last_heartbeat, name=worker_name ) @@ -184,7 +184,7 @@ def cancel_abandoned_task(self, task, final_state, reason=None): if task.state == TASK_STATES.CANCELING: if reason: _logger.info( - _("Cleaning up task %s and marking as %s. Reason: %s"), + "Cleaning up task %s and marking as %s. Reason: %s", task.pk, final_state, reason, @@ -338,18 +338,18 @@ def supervise_task(self, task): if self.shutdown_requested: if self.task_grace_timeout > 0: _logger.info( - _("Worker shutdown requested, waiting for task %s to finish."), task.pk + "Worker shutdown requested, waiting for task %s to finish.", task.pk ) else: - _logger.info(_("Aborting current task %s due to worker shutdown."), task.pk) + _logger.info("Aborting current task %s due to worker shutdown.", task.pk) os.kill(task_process.pid, signal.SIGUSR1) cancel_state = TASK_STATES.FAILED cancel_reason = "Aborted during worker shutdown." break task_process.join() if not cancel_state and task_process.exitcode != 0: - _logger.warn( - _("Task process for %s exited with non zero exitcode %i."), + _logger.warning( + "Task process for %s exited with non zero exitcode %i.", task.pk, task_process.exitcode, ) diff --git a/pulpcore/tasking/tasks.py b/pulpcore/tasking/tasks.py index 67501c567e..0fcdcb26e4 100644 --- a/pulpcore/tasking/tasks.py +++ b/pulpcore/tasking/tasks.py @@ -120,13 +120,13 @@ def dispatch_scheduled_tasks(): task_schedule.save(update_fields=["next_dispatch", "last_task"]) _logger.info( - _("Dispatched scheduled task {task_name} as task id {task_id}").format( + "Dispatched scheduled task {task_name} as task id {task_id}".format( task_name=task_schedule.task_name, task_id=task_schedule.last_task.pk ) ) except Exception as e: - _logger.warn( - _("Dispatching scheduled task {task_name} failed. {error}").format( + _logger.warning( + "Dispatching scheduled task {task_name} failed. {error}".format( task_name=task_schedule.task_name, error=str(e) ) ) diff --git a/pulpcore/tasking/util.py b/pulpcore/tasking/util.py index 6a9ac6cff4..b7394902c1 100644 --- a/pulpcore/tasking/util.py +++ b/pulpcore/tasking/util.py @@ -33,8 +33,11 @@ def cancel(task_id): if task_status.state in TASK_FINAL_STATES: # If the task is already done, just stop - msg = _("Task [{task_id}] already in a final state: {state}") - _logger.debug(msg.format(task_id=task_id, state=task_status.state)) + _logger.debug( + "Task [{task_id}] already in a final state: {state}".format( + task_id=task_id, state=task_status.state + ) + ) return task_status _logger.info(_("Canceling task: {id}").format(id=task_id))