Last active
July 26, 2020 01:11
-
-
Save ojacobson/4962a3f3256f15ec78779fbeb030c492 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse as ap | |
import contextlib as cl | |
import os | |
import pathlib | |
import shlex | |
import sys | |
import tarfile | |
import urllib.request as ur | |
def parse_args(): | |
parser = ap.ArgumentParser( | |
description="Runs application packages in the current container.", | |
) | |
parser.add_argument( | |
'--url', | |
nargs='?', | |
default=os.environ.get('APP_PACKAGE_URL'), | |
help='Application package URL (optional; read from APP_PACKAGE_URL if set)', | |
) | |
parser.add_argument( | |
'--program', | |
nargs='?', | |
default=os.environ.get('APP_PACKAGE_PROGRAM'), | |
help='Program to run (optional; read from APP_PACKAGE_PROGRAM if set; if not set, runs a shell)', | |
) | |
return parser.parse_args() | |
def install_package(source_url): | |
with cl.ExitStack() as stack: | |
response = stack.enter_context(ur.urlopen(source_url)) | |
archive = stack.enter_context(tarfile.open(fileobj=response, mode='r:gz')) | |
archive.extractall(path='/') | |
WHITELIST_ENV_VARS = { | |
'HOSTNAME', | |
'PWD', | |
'HOME', | |
'TERM', | |
'LC_CTYPE', | |
'PATH', | |
} | |
BASH_INIT_FILE = pathlib.Path(__file__).parent / 'bash-init' | |
def base_environment(): | |
return dict( | |
(k, v) for (k, v) in os.environ.items() if k in WHITELIST_ENV_VARS | |
) | |
def program_environment(): | |
return dict( | |
**base_environment(), | |
BASH_ENV=BASH_INIT_FILE, | |
) | |
def start_program(path): | |
environ = program_environment() | |
os.execle('/bin/bash', '/bin/bash', '-c', f"exec {shlex.quote(path)}", environ) | |
def start_interactive_shell(): | |
environ = base_environment() | |
os.execle('/bin/bash', '/bin/bash', '--rcfile', BASH_INIT_FILE, environ) | |
def main(): | |
args = parse_args() | |
if args.url is not None: | |
install_package(args.url) | |
if args.program is not None: | |
start_program(args.program) | |
start_interactive_shell() | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment