{{ message }}
forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker.mjs
More file actions
300 lines (260 loc) · 7.57 KB
/
Copy pathdocker.mjs
File metadata and controls
300 lines (260 loc) · 7.57 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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { inspect } from "node:util";
import { $, isCI, spawn, spawnSafe, which } from "./utils.mjs";
export const docker = {
get name() {
return "docker";
},
/**
* @typedef {"linux" | "darwin" | "windows"} DockerOs
* @typedef {"amd64" | "arm64"} DockerArch
* @typedef {`${DockerOs}/${DockerArch}`} DockerPlatform
*/
/**
* @param {Platform} platform
* @returns {DockerPlatform}
*/
getPlatform(platform) {
const { os, arch } = platform;
if (arch === "aarch64") {
return `${os}/arm64`;
} else if (arch === "x64") {
return `${os}/amd64`;
}
throw new Error(`Unsupported platform: ${inspect(platform)}`);
},
/**
* @typedef DockerSpawnOptions
* @property {DockerPlatform} [platform]
* @property {boolean} [json]
*/
/**
* @param {string[]} args
* @param {DockerSpawnOptions & import("./utils.mjs").SpawnOptions} [options]
* @returns {Promise<unknown>}
*/
async spawn(args, options = {}) {
const docker = which("docker", { required: true });
let env = { ...process.env };
if (isCI) {
env["BUILDKIT_PROGRESS"] = "plain";
}
const { json, platform } = options;
if (json) {
args.push("--format=json");
}
if (platform) {
args.push(`--platform=${platform}`);
}
const { error, stdout } = await spawnSafe($`${docker} ${args}`, { env, ...options });
if (error) {
return;
}
if (!json) {
return stdout;
}
try {
return JSON.parse(stdout);
} catch {
return;
}
},
/**
* @typedef {Object} DockerImage
* @property {string} Id
* @property {string[]} RepoTags
* @property {string[]} RepoDigests
* @property {string} Created
* @property {DockerOs} Os
* @property {DockerArch} Architecture
* @property {number} Size
*/
/**
* @param {string} url
* @param {DockerPlatform} [platform]
* @returns {Promise<boolean>}
*/
async pullImage(url, platform) {
const done = await this.spawn($`pull ${url}`, {
platform,
throwOnError: error => !/No such image|manifest unknown/i.test(inspect(error)),
});
return !!done;
},
/**
* @param {string} url
* @param {DockerPlatform} [platform]
* @returns {Promise<DockerImage | undefined>}
*/
async inspectImage(url, platform) {
/** @type {DockerImage[]} */
const images = await this.spawn($`image inspect ${url}`, {
json: true,
throwOnError: error => !/No such image/i.test(inspect(error)),
});
if (!images) {
const pulled = await this.pullImage(url, platform);
if (pulled) {
return this.inspectImage(url, platform);
}
}
const { os, arch } = platform || {};
return images
?.filter(({ Os, Architecture }) => !os || !arch || (Os === os && Architecture === arch))
?.find((a, b) => (a.Created < b.Created ? 1 : -1));
},
/**
* @typedef {Object} DockerContainer
* @property {string} Id
* @property {string} Name
* @property {string} Image
* @property {string} Created
* @property {DockerContainerState} State
* @property {DockerContainerNetworkSettings} NetworkSettings
*/
/**
* @typedef {Object} DockerContainerState
* @property {"exited" | "running"} Status
* @property {number} [Pid]
* @property {number} ExitCode
* @property {string} [Error]
* @property {string} StartedAt
* @property {string} FinishedAt
*/
/**
* @typedef {Object} DockerContainerNetworkSettings
* @property {string} [IPAddress]
*/
/**
* @param {string} containerId
* @returns {Promise<DockerContainer | undefined>}
*/
async inspectContainer(containerId) {
const containers = await this.spawn($`container inspect ${containerId}`, { json: true });
return containers?.find(a => a.Id === containerId);
},
/**
* @returns {Promise<DockerContainer[]>}
*/
async listContainers() {
const containers = await this.spawn($`container ls --all`, { json: true });
return containers || [];
},
/**
* @typedef {Object} DockerRunOptions
* @property {string[]} [command]
* @property {DockerPlatform} [platform]
* @property {string} [name]
* @property {boolean} [detach]
* @property {"always" | "never"} [pull]
* @property {boolean} [rm]
* @property {"no" | "on-failure" | "always"} [restart]
*/
/**
* @param {string} url
* @param {DockerRunOptions} [options]
* @returns {Promise<DockerContainer>}
*/
async runContainer(url, options = {}) {
const { detach, command = [], ...containerOptions } = options;
const args = Object.entries(containerOptions)
.filter(([_, value]) => typeof value !== "undefined")
.map(([key, value]) => (typeof value === "boolean" ? `--${key}` : `--${key}=${value}`));
if (detach) {
args.push("--detach");
} else {
args.push("--tty", "--interactive");
}
const stdio = detach ? "pipe" : "inherit";
const result = await this.spawn($`run ${args} ${url} ${command}`, { stdio });
if (!detach) {
return;
}
const containerId = result.trim();
const container = await this.inspectContainer(containerId);
if (!container) {
throw new Error(`Failed to run container: ${inspect(result)}`);
}
return container;
},
/**
* @param {Platform} platform
* @returns {Promise<DockerImage>}
*/
async getBaseImage(platform) {
const { os, distro, release } = platform;
const dockerPlatform = this.getPlatform(platform);
let url;
if (os === "linux") {
if (distro === "debian" || distro === "ubuntu" || distro === "alpine") {
url = `docker.io/library/${distro}:${release}`;
} else if (distro === "amazonlinux") {
url = `public.ecr.aws/amazonlinux/amazonlinux:${release}`;
}
}
if (url) {
const image = await this.inspectImage(url, dockerPlatform);
if (image) {
return image;
}
}
throw new Error(`Unsupported platform: ${inspect(platform)}`);
},
/**
* @param {DockerContainer} container
* @param {MachineOptions} [options]
* @returns {Machine}
*/
toMachine(container, options = {}) {
const { Id: containerId } = container;
const exec = (command, options) => {
return spawn(["docker", "exec", containerId, ...command], options);
};
const execSafe = (command, options) => {
return spawnSafe(["docker", "exec", containerId, ...command], options);
};
const upload = async (source, destination) => {
await spawn(["docker", "cp", source, `${containerId}:${destination}`]);
};
const attach = async () => {
const { exitCode, error } = await spawn(["docker", "exec", "-it", containerId, "sh"], {
stdio: "inherit",
});
if (exitCode === 0 || exitCode === 130) {
return;
}
throw error;
};
const snapshot = async name => {
await spawn(["docker", "commit", containerId]);
};
const kill = async () => {
await spawn(["docker", "kill", containerId]);
};
return {
cloud: "docker",
id: containerId,
spawn: exec,
spawnSafe: execSafe,
upload,
attach,
snapshot,
close: kill,
[Symbol.asyncDispose]: kill,
};
},
/**
* @param {MachineOptions} options
* @returns {Promise<Machine>}
*/
async createMachine(options) {
const { Id: imageId, Os, Architecture } = await docker.getBaseImage(options);
const container = await docker.runContainer(imageId, {
platform: `${Os}/${Architecture}`,
command: ["sleep", "1d"],
detach: true,
rm: true,
restart: "no",
});
return this.toMachine(container, options);
},
};
You can’t perform that action at this time.
