mirror of
https://github.com/phusion/baseimage-docker.git
synced 2026-03-26 04:18:46 +00:00
refactor: improve pep8 compliance
This changeset fixes PEP8 issues, minus `E501 line too long (80 > 79 characters)`, as that should be more of a guideline than a strict rule, and harder to follow without silly refactoring. Also removed two unused exception variables.
This commit is contained in:
committed by
GitHub
parent
8f7fcfec33
commit
f7dfb05850
@@ -1,5 +1,14 @@
|
||||
#!/usr/bin/python3 -u
|
||||
import os, os.path, sys, stat, signal, errno, argparse, time, json, re
|
||||
import argparse
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import os.path
|
||||
import re
|
||||
import signal
|
||||
import stat
|
||||
import sys
|
||||
import time
|
||||
|
||||
KILL_PROCESS_TIMEOUT = int(os.environ.get('KILL_PROCESS_TIMEOUT', 5))
|
||||
KILL_ALL_PROCESSES_TIMEOUT = int(os.environ.get('KILL_ALL_PROCESSES_TIMEOUT', 5))
|
||||
@@ -15,33 +24,43 @@ log_level = None
|
||||
|
||||
terminated_child_processes = {}
|
||||
|
||||
_find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
|
||||
|
||||
|
||||
class AlarmException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def error(message):
|
||||
if log_level >= LOG_LEVEL_ERROR:
|
||||
sys.stderr.write("*** %s\n" % message)
|
||||
|
||||
|
||||
def warn(message):
|
||||
if log_level >= LOG_LEVEL_WARN:
|
||||
sys.stderr.write("*** %s\n" % message)
|
||||
|
||||
|
||||
def info(message):
|
||||
if log_level >= LOG_LEVEL_INFO:
|
||||
sys.stderr.write("*** %s\n" % message)
|
||||
|
||||
|
||||
def debug(message):
|
||||
if log_level >= LOG_LEVEL_DEBUG:
|
||||
sys.stderr.write("*** %s\n" % message)
|
||||
|
||||
|
||||
def ignore_signals_and_raise_keyboard_interrupt(signame):
|
||||
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
raise KeyboardInterrupt(signame)
|
||||
|
||||
|
||||
def raise_alarm_exception():
|
||||
raise AlarmException('Alarm')
|
||||
|
||||
|
||||
def listdir(path):
|
||||
try:
|
||||
result = os.stat(path)
|
||||
@@ -52,13 +71,15 @@ def listdir(path):
|
||||
else:
|
||||
return []
|
||||
|
||||
|
||||
def is_exe(path):
|
||||
try:
|
||||
return os.path.isfile(path) and os.access(path, os.X_OK)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
def import_envvars(clear_existing_environment = True, override_existing_environment = True):
|
||||
|
||||
def import_envvars(clear_existing_environment=True, override_existing_environment=True):
|
||||
if not os.path.exists("/etc/container_environment"):
|
||||
return
|
||||
new_env = {}
|
||||
@@ -73,10 +94,11 @@ def import_envvars(clear_existing_environment = True, override_existing_environm
|
||||
if clear_existing_environment:
|
||||
os.environ.clear()
|
||||
for name, value in new_env.items():
|
||||
if override_existing_environment or not name in os.environ:
|
||||
if override_existing_environment or name not in os.environ:
|
||||
os.environ[name] = value
|
||||
|
||||
def export_envvars(to_dir = True):
|
||||
|
||||
def export_envvars(to_dir=True):
|
||||
if not os.path.exists("/etc/container_environment"):
|
||||
return
|
||||
shell_dump = ""
|
||||
@@ -92,7 +114,6 @@ def export_envvars(to_dir = True):
|
||||
with open("/etc/container_environment.json", "w") as f:
|
||||
f.write(json.dumps(dict(os.environ)))
|
||||
|
||||
_find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
|
||||
|
||||
def shquote(s):
|
||||
"""Return a shell-escaped version of the string *s*."""
|
||||
@@ -105,9 +126,11 @@ def shquote(s):
|
||||
# the string $'b is then quoted as '$'"'"'b'
|
||||
return "'" + s.replace("'", "'\"'\"'") + "'"
|
||||
|
||||
|
||||
def sanitize_shenvname(s):
|
||||
return re.sub(SHENV_NAME_WHITELIST_REGEX, "_", s)
|
||||
|
||||
|
||||
# Waits for the child process with the given PID, while at the same time
|
||||
# reaping any other child processes that have exited (e.g. adopted child
|
||||
# processes that have terminated).
|
||||
@@ -143,7 +166,8 @@ def waitpid_reap_other_children(pid):
|
||||
raise
|
||||
return status
|
||||
|
||||
def stop_child_process(name, pid, signo = signal.SIGTERM, time_limit = KILL_PROCESS_TIMEOUT):
|
||||
|
||||
def stop_child_process(name, pid, signo=signal.SIGTERM, time_limit=KILL_PROCESS_TIMEOUT):
|
||||
info("Shutting down %s (PID %d)..." % (name, pid))
|
||||
try:
|
||||
os.kill(pid, signo)
|
||||
@@ -168,13 +192,14 @@ def stop_child_process(name, pid, signo = signal.SIGTERM, time_limit = KILL_PROC
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
|
||||
|
||||
def run_command_killable(*argv):
|
||||
filename = argv[0]
|
||||
status = None
|
||||
pid = os.spawnvp(os.P_NOWAIT, filename, argv)
|
||||
try:
|
||||
status = waitpid_reap_other_children(pid)
|
||||
except BaseException as s:
|
||||
except BaseException:
|
||||
warn("An error occurred. Aborting.")
|
||||
stop_child_process(filename, pid)
|
||||
raise
|
||||
@@ -185,11 +210,13 @@ def run_command_killable(*argv):
|
||||
error("%s failed with status %d\n" % (filename, os.WEXITSTATUS(status)))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def run_command_killable_and_import_envvars(*argv):
|
||||
run_command_killable(*argv)
|
||||
import_envvars()
|
||||
export_envvars(False)
|
||||
|
||||
|
||||
def kill_all_processes(time_limit):
|
||||
info("Killing all processes...")
|
||||
try:
|
||||
@@ -217,6 +244,7 @@ def kill_all_processes(time_limit):
|
||||
finally:
|
||||
signal.alarm(0)
|
||||
|
||||
|
||||
def run_startup_files():
|
||||
# Run /etc/my_init.d/*
|
||||
for name in listdir("/etc/my_init.d"):
|
||||
@@ -230,13 +258,18 @@ def run_startup_files():
|
||||
info("Running /etc/rc.local...")
|
||||
run_command_killable_and_import_envvars("/etc/rc.local")
|
||||
|
||||
|
||||
def start_runit():
|
||||
info("Booting runit daemon...")
|
||||
pid = os.spawnl(os.P_NOWAIT, "/usr/bin/runsvdir", "/usr/bin/runsvdir",
|
||||
"-P", "/etc/service")
|
||||
pid = os.spawnl(os.P_NOWAIT,
|
||||
"/usr/bin/runsvdir",
|
||||
"/usr/bin/runsvdir",
|
||||
"-P",
|
||||
"/etc/service")
|
||||
info("Runit started as PID %d" % pid)
|
||||
return pid
|
||||
|
||||
|
||||
def wait_for_runit_or_interrupt(pid):
|
||||
try:
|
||||
status = waitpid_reap_other_children(pid)
|
||||
@@ -244,11 +277,13 @@ def wait_for_runit_or_interrupt(pid):
|
||||
except KeyboardInterrupt:
|
||||
return (False, None)
|
||||
|
||||
def shutdown_runit_services(quiet = False):
|
||||
|
||||
def shutdown_runit_services(quiet=False):
|
||||
if not quiet:
|
||||
debug("Begin shutting down runit services...")
|
||||
os.system("/usr/bin/sv -w %d down /etc/service/* > /dev/null" % KILL_PROCESS_TIMEOUT)
|
||||
|
||||
|
||||
def wait_for_runit_services():
|
||||
debug("Waiting for runit services to exit...")
|
||||
done = False
|
||||
@@ -263,10 +298,12 @@ def wait_for_runit_services():
|
||||
# services.
|
||||
shutdown_runit_services(True)
|
||||
|
||||
|
||||
def install_insecure_key():
|
||||
info("Installing insecure SSH key for user root")
|
||||
run_command_killable("/usr/sbin/enable_insecure_key")
|
||||
|
||||
|
||||
def main(args):
|
||||
import_envvars(False, False)
|
||||
export_envvars()
|
||||
@@ -295,7 +332,9 @@ def main(args):
|
||||
info("Runit exited with status %d" % exit_status)
|
||||
else:
|
||||
info("Running %s..." % " ".join(args.main_command))
|
||||
pid = os.spawnvp(os.P_NOWAIT, args.main_command[0], args.main_command)
|
||||
pid = os.spawnvp(os.P_NOWAIT,
|
||||
args.main_command[0],
|
||||
args.main_command)
|
||||
try:
|
||||
exit_code = waitpid_reap_other_children(pid)
|
||||
if exit_code is None:
|
||||
@@ -307,7 +346,7 @@ def main(args):
|
||||
except KeyboardInterrupt:
|
||||
stop_child_process(args.main_command[0], pid)
|
||||
raise
|
||||
except BaseException as s:
|
||||
except BaseException:
|
||||
warn("An error occurred. Aborting.")
|
||||
stop_child_process(args.main_command[0], pid)
|
||||
raise
|
||||
@@ -319,25 +358,50 @@ def main(args):
|
||||
stop_child_process("runit daemon", runit_pid)
|
||||
wait_for_runit_services()
|
||||
|
||||
|
||||
# Parse options.
|
||||
parser = argparse.ArgumentParser(description = 'Initialize the system.')
|
||||
parser.add_argument('main_command', metavar = 'MAIN_COMMAND', type = str, nargs = '*',
|
||||
help = 'The main command to run. (default: runit)')
|
||||
parser.add_argument('--enable-insecure-key', dest = 'enable_insecure_key',
|
||||
action = 'store_const', const = True, default = False,
|
||||
help = 'Install the insecure SSH key')
|
||||
parser.add_argument('--skip-startup-files', dest = 'skip_startup_files',
|
||||
action = 'store_const', const = True, default = False,
|
||||
help = 'Skip running /etc/my_init.d/* and /etc/rc.local')
|
||||
parser.add_argument('--skip-runit', dest = 'skip_runit',
|
||||
action = 'store_const', const = True, default = False,
|
||||
help = 'Do not run runit services')
|
||||
parser.add_argument('--no-kill-all-on-exit', dest = 'kill_all_on_exit',
|
||||
action = 'store_const', const = False, default = True,
|
||||
help = 'Don\'t kill all processes on the system upon exiting')
|
||||
parser.add_argument('--quiet', dest = 'log_level',
|
||||
action = 'store_const', const = LOG_LEVEL_WARN, default = LOG_LEVEL_INFO,
|
||||
help = 'Only print warnings and errors')
|
||||
parser = argparse.ArgumentParser(description='Initialize the system.')
|
||||
parser.add_argument(
|
||||
'main_command',
|
||||
metavar='MAIN_COMMAND',
|
||||
type=str,
|
||||
nargs='*',
|
||||
help='The main command to run. (default: runit)')
|
||||
parser.add_argument(
|
||||
'--enable-insecure-key',
|
||||
dest='enable_insecure_key',
|
||||
action='store_const',
|
||||
const=True,
|
||||
default=False,
|
||||
help='Install the insecure SSH key')
|
||||
parser.add_argument(
|
||||
'--skip-startup-files',
|
||||
dest='skip_startup_files',
|
||||
action='store_const',
|
||||
const=True,
|
||||
default=False,
|
||||
help='Skip running /etc/my_init.d/* and /etc/rc.local')
|
||||
parser.add_argument(
|
||||
'--skip-runit',
|
||||
dest='skip_runit',
|
||||
action='store_const',
|
||||
const=True,
|
||||
default=False,
|
||||
help='Do not run runit services')
|
||||
parser.add_argument(
|
||||
'--no-kill-all-on-exit',
|
||||
dest='kill_all_on_exit',
|
||||
action='store_const',
|
||||
const=False,
|
||||
default=True,
|
||||
help='Do not kill all processes on the system upon exiting')
|
||||
parser.add_argument(
|
||||
'--quiet',
|
||||
dest='log_level',
|
||||
action='store_const',
|
||||
const=LOG_LEVEL_WARN,
|
||||
default=LOG_LEVEL_INFO,
|
||||
help='Only print warnings and errors')
|
||||
args = parser.parse_args()
|
||||
log_level = args.log_level
|
||||
|
||||
@@ -346,9 +410,12 @@ if args.skip_runit and len(args.main_command) == 0:
|
||||
sys.exit(1)
|
||||
|
||||
# Run main function.
|
||||
signal.signal(signal.SIGTERM, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGTERM'))
|
||||
signal.signal(signal.SIGINT, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGINT'))
|
||||
signal.signal(signal.SIGALRM, lambda signum, frame: raise_alarm_exception())
|
||||
signal.signal(signal.SIGTERM,
|
||||
lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGTERM'))
|
||||
signal.signal(signal.SIGINT,
|
||||
lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt('SIGINT'))
|
||||
signal.signal(signal.SIGALRM,
|
||||
lambda signum, frame: raise_alarm_exception())
|
||||
try:
|
||||
main(args)
|
||||
except KeyboardInterrupt:
|
||||
|
||||
Reference in New Issue
Block a user