2019-06-12 21:11:36 +02:00
|
|
|
import logging
|
2019-04-03 07:30:14 +02:00
|
|
|
import subprocess
|
|
|
|
|
2019-05-12 11:30:22 +02:00
|
|
|
from borgmatic.logger import get_logger
|
2019-04-03 07:30:14 +02:00
|
|
|
|
2019-05-12 11:30:22 +02:00
|
|
|
logger = get_logger(__name__)
|
2019-04-03 07:30:14 +02:00
|
|
|
|
|
|
|
|
2019-06-12 22:09:04 +02:00
|
|
|
def execute_and_log_output(full_command, output_log_level, shell):
|
|
|
|
process = subprocess.Popen(
|
|
|
|
full_command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=shell
|
|
|
|
)
|
2019-06-12 01:42:04 +02:00
|
|
|
|
|
|
|
while process.poll() is None:
|
2019-06-12 22:09:04 +02:00
|
|
|
line = process.stdout.readline().rstrip().decode()
|
2019-06-13 05:56:20 +02:00
|
|
|
if not line:
|
|
|
|
continue
|
|
|
|
|
2019-06-12 01:42:04 +02:00
|
|
|
if line.startswith('borg: error:'):
|
|
|
|
logger.error(line)
|
|
|
|
else:
|
2019-06-12 21:11:36 +02:00
|
|
|
logger.log(output_log_level, line)
|
2019-06-12 01:42:04 +02:00
|
|
|
|
2019-06-12 22:09:04 +02:00
|
|
|
remaining_output = process.stdout.read().rstrip().decode()
|
2019-06-12 20:49:35 +02:00
|
|
|
if remaining_output:
|
2019-06-13 19:48:21 +02:00
|
|
|
logger.log(output_log_level, remaining_output)
|
2019-06-12 01:42:04 +02:00
|
|
|
|
2019-06-12 20:49:35 +02:00
|
|
|
exit_code = process.poll()
|
2019-06-12 01:42:04 +02:00
|
|
|
if exit_code != 0:
|
|
|
|
raise subprocess.CalledProcessError(exit_code, full_command)
|
|
|
|
|
|
|
|
|
2019-06-12 22:09:04 +02:00
|
|
|
def execute_command(full_command, output_log_level=logging.INFO, shell=False):
|
2019-04-03 07:30:14 +02:00
|
|
|
'''
|
2019-06-12 21:11:36 +02:00
|
|
|
Execute the given command (a sequence of command/argument strings) and log its output at the
|
2019-06-12 22:09:04 +02:00
|
|
|
given log level. If output log level is None, instead capture and return the output. If
|
|
|
|
shell is True, execute the command within a shell.
|
2019-04-03 07:30:14 +02:00
|
|
|
'''
|
|
|
|
logger.debug(' '.join(full_command))
|
|
|
|
|
2019-06-12 21:11:36 +02:00
|
|
|
if output_log_level is None:
|
2019-06-12 22:09:04 +02:00
|
|
|
output = subprocess.check_output(full_command, shell=shell)
|
2019-04-03 07:30:14 +02:00
|
|
|
return output.decode() if output is not None else None
|
|
|
|
else:
|
2019-06-12 22:09:04 +02:00
|
|
|
execute_and_log_output(full_command, output_log_level, shell=shell)
|