/
index.ts
198 lines (178 loc) · 5.55 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import type { ExecOptions as ChildProcessExecOptions } from 'child_process';
import { dirname, join } from 'upath';
import { GlobalConfig } from '../../config/global';
import { TEMPORARY_ERROR } from '../../constants/error-messages';
import { logger } from '../../logger';
import { generateInstallCommands } from './buildpack';
import {
DockerOptions,
ExecResult,
Opt,
RawExecOptions,
rawExec,
} from './common';
import { generateDockerCommand, removeDockerContainer } from './docker';
import { getChildProcessEnv } from './env';
import type { ToolConstraint } from './types';
type ExtraEnv<T = unknown> = Record<string, T>;
export interface ExecOptions extends ChildProcessExecOptions {
cwdFile?: string;
extraEnv?: Opt<ExtraEnv>;
docker?: Opt<DockerOptions>;
toolConstraints?: Opt<ToolConstraint[]>;
}
function getChildEnv({
extraEnv = {},
env: forcedEnv = {},
}: ExecOptions): ExtraEnv<string> {
const globalConfigEnv = GlobalConfig.get('customEnvVariables');
const inheritedKeys = Object.entries(extraEnv).reduce(
(acc, [key, val]) =>
val === null || val === undefined ? acc : [...acc, key],
[]
);
const parentEnv = getChildProcessEnv(inheritedKeys);
const childEnv = Object.entries({
...extraEnv,
...parentEnv,
...globalConfigEnv,
...forcedEnv,
}).reduce(
(acc, [key, val]) =>
val === null || val === undefined
? acc
: { ...acc, [key]: val.toString() },
{}
);
return childEnv;
}
function dockerEnvVars(
extraEnv: ExtraEnv,
childEnv: ExtraEnv<string>
): string[] {
const extraEnvKeys = Object.keys(extraEnv || {});
return extraEnvKeys.filter(
(key) => typeof childEnv[key] === 'string' && childEnv[key].length > 0
);
}
function getCwd({ cwd, cwdFile }: ExecOptions): string {
const defaultCwd = GlobalConfig.get('localDir');
const paramCwd = cwdFile ? join(defaultCwd, dirname(cwdFile)) : cwd;
return paramCwd || defaultCwd;
}
function getRawExecOptions(opts: ExecOptions): RawExecOptions {
const defaultExecutionTimeout = GlobalConfig.get('executionTimeout');
const execOptions: ExecOptions = { ...opts };
delete execOptions.extraEnv;
delete execOptions.docker;
delete execOptions.cwdFile;
delete execOptions.toolConstraints;
const childEnv = getChildEnv(opts);
const cwd = getCwd(opts);
const rawExecOptions: RawExecOptions = {
encoding: 'utf-8',
...execOptions,
env: childEnv,
cwd,
};
// Set default timeout config.executionTimeout if specified; othrwise to 15 minutes
if (!rawExecOptions.timeout) {
if (defaultExecutionTimeout) {
rawExecOptions.timeout = defaultExecutionTimeout * 60 * 1000;
} else {
rawExecOptions.timeout = 15 * 60 * 1000;
}
}
// Set default max buffer size to 10MB
rawExecOptions.maxBuffer = rawExecOptions.maxBuffer || 10 * 1024 * 1024;
return rawExecOptions;
}
function isDocker({ docker }: ExecOptions): boolean {
const { binarySource } = GlobalConfig.get();
return binarySource === 'docker' && !!docker;
}
interface RawExecArguments {
rawCommands: string[];
rawOptions: RawExecOptions;
}
async function prepareRawExec(
cmd: string | string[],
opts: ExecOptions = {}
): Promise<RawExecArguments> {
const { docker } = opts;
const { customEnvVariables } = GlobalConfig.get();
const rawOptions = getRawExecOptions(opts);
let rawCommands = typeof cmd === 'string' ? [cmd] : cmd;
if (isDocker(opts)) {
logger.debug('Using docker to execute');
const extraEnv = { ...opts.extraEnv, ...customEnvVariables };
const childEnv = getChildEnv(opts);
const envVars = dockerEnvVars(extraEnv, childEnv);
const cwd = getCwd(opts);
const dockerOptions: DockerOptions = { ...docker, cwd, envVars };
dockerOptions.preCommands = [
...(await generateInstallCommands(opts.toolConstraints)),
...(dockerOptions.preCommands || []),
];
const dockerCommand = await generateDockerCommand(
rawCommands,
dockerOptions
);
rawCommands = [dockerCommand];
}
return { rawCommands, rawOptions };
}
export async function exec(
cmd: string | string[],
opts: ExecOptions = {}
): Promise<ExecResult> {
const { docker } = opts;
const { dockerChildPrefix } = GlobalConfig.get();
const { rawCommands, rawOptions } = await prepareRawExec(cmd, opts);
const useDocker = isDocker(opts);
let res: ExecResult | null = null;
for (const rawCmd of rawCommands) {
const startTime = Date.now();
if (useDocker) {
await removeDockerContainer(docker.image, dockerChildPrefix);
}
logger.debug({ command: rawCommands }, 'Executing command');
logger.trace({ commandOptions: rawOptions }, 'Command options');
try {
res = await rawExec(rawCmd, rawOptions);
} catch (err) {
logger.debug({ err }, 'rawExec err');
if (useDocker) {
await removeDockerContainer(docker.image, dockerChildPrefix).catch(
(removeErr: Error) => {
const message: string = err.message;
throw new Error(
`Error: "${removeErr.message}" - Original Error: "${message}"`
);
}
);
}
if (err.signal === `SIGTERM`) {
logger.debug(
{ err },
'exec interrupted by SIGTERM - run needs to be aborted'
);
throw new Error(TEMPORARY_ERROR);
}
throw err;
}
const durationMs = Math.round(Date.now() - startTime);
if (res) {
logger.debug(
{
cmd: rawCmd,
durationMs,
stdout: res.stdout,
stderr: res.stderr,
},
'exec completed'
);
}
}
return res;
}