Fix invalid UTF-8 characters in execute output

It's rare but the output of commands called by execute can
contain invalid UTF-8 characters.
While the execute command does not care about the output
itself and will finish execution correctly, transposing
that into string (for example when logging the output)
will raise a Unicode exception.
When that happens we should escape the invalid characters
and log a trimmed output.

Closes-Bug: 2071935
Change-Id: I0c776e3fe5efa82b3220f573953bcac1678883f2
This commit is contained in:
Riccardo Pittau
2024-08-09 12:01:35 +02:00
parent c3d59dfffc
commit 1ca3c8cf1a

View File

@@ -96,8 +96,20 @@ def execute(*cmd, use_standard_locale=False, log_stdout=True, **kwargs):
def _log(stdout, stderr):
if log_stdout:
LOG.debug('Command stdout is: "%s"', stdout)
LOG.debug('Command stderr is: "%s"', stderr)
try:
LOG.debug('Command stdout is: "%s"', stdout)
except UnicodeEncodeError:
LOG.debug('stdout contains invalid UTF-8 characters')
stdout = (stdout.encode('utf8', 'surrogateescape')
.decode('utf8', 'ignore'))
LOG.debug('Command stdout is: "%s"', stdout)
try:
LOG.debug('Command stderr is: "%s"', stderr)
except UnicodeEncodeError:
LOG.debug('stderr contains invalid UTF-8 characters')
stderr = (stderr.encode('utf8', 'surrogateescape')
.decode('utf8', 'ignore'))
LOG.debug('Command stderr is: "%s"', stderr)
try:
result = processutils.execute(*cmd, **kwargs)