-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.js
More file actions
271 lines (244 loc) · 9.99 KB
/
Copy pathfunctions.js
File metadata and controls
271 lines (244 loc) · 9.99 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const { dockerCommand } = require('docker-cli-js');
const { randomBytes } = require("crypto");
const { spawn } = require("child_process");
const portfinder = require('portfinder');
const path = require('path');
const { isText, isBinary } = require('istextorbinary');
const { addSlashes } = require('slashes');
const VOLUMES_ROOT = path.resolve(__dirname, 'volumes');
// spawn-based docker runner that sidesteps shell interpretation entirely.
// Required because conformance tests set env var names with $, `, !, (, ), etc.
function dockerSpawn(args) {
return new Promise((resolve, reject) => {
let stdout = '';
let stderr = '';
let p = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });
p.stdout.on('data', (d) => { stdout += d.toString(); });
p.stderr.on('data', (d) => { stderr += d.toString(); });
p.on('error', reject);
p.on('close', (code) => {
if (code === 0) resolve({ raw: stdout, stderr, exitCode: 0 });
else reject(Object.assign(new Error(`docker ${args.join(' ')} exited ${code}: ${stderr}`), { stdout, stderr, exitCode: code }));
});
});
}
const addSlashesToString = (str) => addSlashes(str).replaceAll('`', '\\`');
// Count the entries of a field that is a Map in the schema but a plain object
// once it has been through toJSON. `Object.keys` on a mongoose Map counts the
// document internals instead of the entries, and `.length` on either is
// undefined — both render as a wrong number in a Table cell without erroring.
let countEntries = (value) => {
if (!value) {
return 0;
}
if (value instanceof Map) {
return value.size;
}
return Object.keys(value).length;
};
// Kubernetes' HumanDuration, which is what an AGE column shows. The previous
// implementation concatenated every unit it could — a node up for four months
// printed "113d2h10m5s" where kubectl prints "113d".
let duration = (timeDiff) => {
let seconds = Math.floor(timeDiff / 1000);
if (!Number.isFinite(seconds) || seconds < 0) {
return '0s';
}
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let days = Math.floor(hours / 24);
let years = Math.floor(days / 365);
if (seconds < 120) {
return `${seconds}s`;
}
if (minutes < 10) {
let remainder = seconds % 60;
return remainder === 0 ? `${minutes}m` : `${minutes}m${remainder}s`;
}
if (minutes < 180) {
return `${minutes}m`;
}
if (hours < 8) {
let remainder = minutes % 60;
return remainder === 0 ? `${hours}h` : `${hours}h${remainder}m`;
}
if (hours < 48) {
return `${hours}h`;
}
if (days < 8) {
let remainder = hours % 24;
return remainder === 0 ? `${days}d` : `${days}d${remainder}h`;
}
if (days < 365) {
return `${days}d`;
}
let remainder = days % 365;
return remainder === 0 ? `${years}y` : `${years}y${remainder}d`;
};
// Kubernetes resource quantities: "100m", "1.5", "512Mi", "2Gi", "1e3".
// Returns a plain number — cores for CPU, bytes for memory — so the scheduler
// can add them up. Suffixless values are taken as-is. Anything unparseable
// returns NaN rather than a silent 0, because a request that reads as zero
// fits on every node and is exactly the sort of wrong answer that looks fine.
const QUANTITY_SUFFIXES = {
n: 1e-9, u: 1e-6, m: 1e-3,
'': 1, k: 1e3, M: 1e6, G: 1e9, T: 1e12, P: 1e15, E: 1e18,
Ki: 1024, Mi: 1024 ** 2, Gi: 1024 ** 3, Ti: 1024 ** 4, Pi: 1024 ** 5, Ei: 1024 ** 6,
};
let parseQuantity = (value) => {
if (value === undefined || value === null || value === '') {
return NaN;
}
if (typeof value === 'number') {
return value;
}
// Protobuf decodes a Quantity as {string: "100m"}.
if (typeof value === 'object') {
return parseQuantity(value.string ?? value.Value ?? '');
}
let text = `${value}`.trim();
let match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*([a-zA-Z]{0,2})$/.exec(text);
if (!match) {
return NaN;
}
let [, digits, suffix] = match;
let multiplier = QUANTITY_SUFFIXES[suffix];
if (multiplier === undefined) {
return NaN;
}
return Number(digits) * multiplier;
};
// The AGE cell of a Table. Every caller used to compute this by subtracting
// two ISO *strings*, which is NaN, and duration(NaN) falls through every
// branch and returns '0s' — so AGE read 0s for every object of every kind
// regardless of how old it was.
let age = (creationTimestamp) => {
let created = Date.parse(creationTimestamp);
if (Number.isNaN(created)) {
return '<unknown>';
}
return duration(Math.max(0, Date.now() - created));
};
let imageExists = (imageName, options) => dockerCommand(`inspect --type=image ${imageName.includes(':') ? imageName.split(':')[0] : imageName}`, { echo: false, ...options })
.then((res) => !(res.length === 0 || (imageName.includes(':') && !res.object.find((e) => e.DockerVersion !== imageName.split(':')[1]))));
let buildImage = (imageName, dockerfile = 'Dockerfile', options) => {
return dockerCommand(`build -t ${imageName} -f ${dockerfile} .`, { ...options })
};
let pullImage = (imageName) => dockerCommand(`pull ${imageName}`, { echo: false });
let dockerExec = (containerName, command) => dockerCommand(`exec -t ${containerName} ${command}`, { echo: false });
let runImage = async (imageName, containerName, options) => {
let flags = ['run'];
if (Array.isArray(options?.ports)) {
for (const p of options.ports) flags.push('-p', String(p));
}
if (Array.isArray(options?.expose)) {
for (const p of options.expose) flags.push('--expose', String(p));
}
if (Array.isArray(options?.env)) {
for (const e of options.env) {
flags.push('-e', `${e.name}=${e.value == null ? '' : e.value}`);
}
}
if (Array.isArray(options?.volumeMounts)) {
for (const v of options.volumeMounts) {
let hostPath = path.join(VOLUMES_ROOT, v.sourceDir, v.file);
let containerPath = `${v.mountPath.replace(/\/$/, '')}/${v.file}`;
flags.push('-v', `${hostPath}:${containerPath}`);
}
}
// Kubernetes container.command overrides ENTRYPOINT (docker --entrypoint
// accepts only one token; remaining tokens become CMD args alongside k8s
// container.args).
let cmdAfterImage = [];
let cmd = Array.isArray(options?.command) ? options.command : [];
let cmdArgs = Array.isArray(options?.args) ? options.args : [];
if (cmd.length > 0) {
flags.push('--entrypoint', cmd[0]);
cmdAfterImage = [...cmd.slice(1), ...cmdArgs];
} else if (cmdArgs.length > 0) {
cmdAfterImage = cmdArgs;
}
flags.push('--name', containerName, '-d', imageName, ...cmdAfterImage);
console.log('docker', 'run', '--name', containerName, imageName, '...');
return dockerSpawn(flags);
};
const isContainerRunning = (containerName) => dockerSpawn(['inspect', '-f', '{{.State.Running}}', containerName])
.then((res) => ({ object: String(res.raw || '').trim() === 'true' }))
.catch(() => ({ object: false }));
// True once the container has actually started executing, regardless of whether
// it's still running or has already exited. Needed because short-lived commands
// (e.g., `sh -c env`) finish before our status-polling loop wakes up.
const containerHasStarted = (containerName) => dockerSpawn(['inspect', '-f', '{{.State.Status}}', containerName])
.then((res) => {
let state = String(res.raw || '').trim();
return state === 'running' || state === 'exited' || state === 'dead' || state === 'paused';
})
.catch(() => false);
const waitContainer = (containerName) => dockerSpawn(['wait', containerName])
.then((res) => Number(String(res.raw || '').trim()) || 0)
.catch(() => 1);
const execInContainer = (containerName, cmdOrArgs) => {
let args = ['exec', containerName];
if (Array.isArray(cmdOrArgs)) args.push(...cmdOrArgs);
else args.push('sh', '-c', String(cmdOrArgs));
return dockerSpawn(args)
.then((res) => ({ code: 0, raw: res.raw }))
.catch((err) => ({ code: err.exitCode || 1, raw: err.stderr || '' }));
};
const stopContainer = (containerName) => dockerSpawn(['stop', containerName]);
const getContainerLogs = (containerName) => dockerSpawn(['logs', containerName]);
const killContainer = (containerName) => dockerSpawn(['kill', containerName]);
const removeContainer = (containerName) => dockerSpawn(['rm', '-f', containerName]);
const getContainerIP = (containerName) => dockerSpawn(['inspect', containerName])
.then((data) => JSON.parse(data.raw)[0]?.NetworkSettings.Networks.bridge.IPAddress);
const getAllContainersWithName = (containerName, imageName) => dockerCommand(`ps -q -f name=${containerName} -f ancestor=${imageName}`, { echo: false });
// TODO: figure out why `bin/bash` commands don't work
const addPodsToService = (containerName, pods) => {
let ips = pods.map((e) => e.status.podIP);
return dockerExec(containerName, `bin/bash -c '${ips.map((e) => `echo "pod add ${e}" > /proc/1/fd/0`).join(' ; ')}'`)
.then(() => ips);
}
const addPortsToEndpoint = (containerName, ports) => {
return dockerExec(containerName, `bin/bash -c '${ports.map((e) => `echo "port add ${e}" > /proc/1/fd/0`).join(' ; ')}'`)
.then(() => ports);
}
const addPortToEndpoint = (containerName, port) => {
return dockerExec(containerName, `bin/bash -c 'echo "port add ${port}" > /proc/1/fd/0'`);
}
const addPodToEndpoint = (containerName, podIP) => {
return dockerExec(containerName, `bin/bash -c 'echo "pod add ${podIP}" > /proc/1/fd/0'`);
}
const removePortFromEndpoint = (containerName, port) => {
return dockerExec(containerName, `bin/bash -c 'echo "port remove ${port}" > /proc/1/fd/0'`);
}
const removePodFromEndpoint = (containerName, podIP) => {
return dockerExec(containerName, `bin/bash -c 'echo "pod remove ${podIP}" > /proc/1/fd/0'`);
}
module.exports = {
isText,
isContainerRunning,
isBinary,
imageExists,
duration,
age,
countEntries,
parseQuantity,
getAllContainersWithName,
randomBytes,
addPortsToEndpoint,
addPortToEndpoint,
addPodToEndpoint,
removePortFromEndpoint,
removePodFromEndpoint,
getContainerIP,
buildImage,
pullImage,
runImage,
stopContainer,
killContainer,
removeContainer,
getContainerLogs,
waitContainer,
execInContainer,
containerHasStarted,
};