Exemple #1
0
def make_cwd(api, entry=None, example=False):
    with temp_env(api.environ):
        workdir = os.path.expandvars(api.workdir)
    def generate_cwd(workdir):
        if os.path.isabs(workdir):
            return workdir
        if example:
            return os.path.join(API_ROOT, 'example', workdir)
        return os.path.join(API_ROOT, entry.mime.media_type, entry.mime.subtype, workdir)
    return os.path.realpath(generate_cwd(workdir))
Exemple #2
0
def run(command, cwd=None, env=None, mime='example', file='unknown'):
    # prepare log path
    logs_path = os.path.join(API_LOGS, mime)
    os.makedirs(logs_path, exist_ok=True)

    # prepare runtime
    logs = os.path.join(logs_path, file)
    with temp_env(env):
        if isinstance(command, str):
            shell = True
            args = os.path.expandvars(command)
        else:
            shell = False
            args = [os.path.expandvars(arg) for arg in command]
    env_line = f'{os.linesep}#      '.join(f'{key}={shlex.quote(val)}'
                                           for (key, val) in env.items())

    suffix = ''
    for retry in range(MAX_RETRY):
        log = logs + suffix
        print_file(f'# open: {time.strftime("%Y-%m-%d-%H-%M-%S")}', file=log)
        print_file(f'# cwd: {cwd}', file=log)
        print_file(f'# env: {env_line}', file=log)
        print_file(f'# args: {args}', file=log)
        try:
            with open(log, 'w') as stdout:
                returncode = subprocess.check_call(args,
                                                   shell=shell,
                                                   cwd=cwd,
                                                   env=env,
                                                   stdout=stdout,
                                                   stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as error:
            print_file(f'# exit: {error.returncode}', file=log)
            print_file(f'# close: {time.strftime("%Y-%m-%d-%H-%M-%S")}',
                       file=log)
            print_file(error.args, file=FAIL)
            suffix = f'_{retry+1}'
            time.sleep(INTERVAL)
            continue
        print_file(f'# exit: {returncode}', file=log)
        print_file(f'# close: {time.strftime("%Y-%m-%d-%H-%M-%S")}', file=log)
        return EXIT_SUCCESS
    return EXIT_FAILURE