-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontainer-status.ts
More file actions
223 lines (193 loc) · 4.7 KB
/
container-status.ts
File metadata and controls
223 lines (193 loc) · 4.7 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
import { exec, spawn } from "node:child_process";
import type { Disposable, LogOutputChannel } from "vscode";
import * as z from "zod/v4-mini";
import { createEmitter } from "./emitter.ts";
export type ContainerStatus = "running" | "stopping" | "stopped";
export interface ContainerStatusTracker extends Disposable {
status(): ContainerStatus;
onChange(callback: (status: ContainerStatus) => void): void;
}
/**
* Checks the status of a docker container in realtime.
*/
export async function createContainerStatusTracker(
containerName: string,
outputChannel: LogOutputChannel,
): Promise<ContainerStatusTracker> {
let status: ContainerStatus | undefined;
const emitter = createEmitter<ContainerStatus>(outputChannel);
const disposable = listenToContainerStatus(
containerName,
outputChannel,
(newStatus) => {
if (status !== newStatus) {
status = newStatus;
void emitter.emit(status);
}
},
);
await getContainerStatus(containerName).then((newStatus) => {
status ??= newStatus;
void emitter.emit(status);
});
return {
status() {
// biome-ignore lint/style/noNonNullAssertion: false positive
return status!;
},
onChange(callback) {
emitter.on(callback);
if (status) {
callback(status);
}
},
dispose() {
disposable.dispose();
},
};
}
const DockerEventsSchema = z.object({
Action: z.enum(["start", "kill", "die"]),
Actor: z.object({
Attributes: z.object({
name: z.string(),
}),
}),
});
function safeJsonParse(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return undefined;
}
}
function listenToContainerStatus(
containerName: string,
outputChannel: LogOutputChannel,
onStatusChange: (status: ContainerStatus) => void,
): Disposable {
let dockerEvents: ReturnType<typeof spawn> | undefined;
let isDisposed = false;
let restartTimeout: NodeJS.Timeout | undefined;
const startListening = () => {
if (isDisposed) return;
outputChannel.debug("Spawning 'docker events'...");
try {
dockerEvents = spawn("docker", [
"events",
"--filter",
`container=${containerName}`,
"--filter",
"event=start",
"--filter",
"event=kill",
"--filter",
"event=die",
"--format",
"json",
]);
dockerEvents.on("error", (error) => {
outputChannel.debug(
`Process 'docker events' errored: ${String(error)}`,
);
// Handle docker not installed
if ("code" in error && error.code === "ENOENT") {
outputChannel.error(
"Failed listen to docker container status changes.",
);
return;
}
// Otherwise, try to restart after a delay
if (!isDisposed) {
scheduleRestart();
}
});
dockerEvents.on("close", (code) => {
outputChannel.debug("Process 'docker events' closed");
if (!isDisposed && code !== 0) {
scheduleRestart();
}
});
if (!dockerEvents.stdout) {
throw new Error("Failed to get stdout from docker events process");
}
dockerEvents.stdout.on("data", (data: Buffer) => {
const lines = data.toString().split("\n").filter(Boolean);
for (const line of lines) {
const json = safeJsonParse(line);
const parsed = DockerEventsSchema.safeParse(json);
if (!parsed.success) {
continue;
}
if (parsed.data.Actor.Attributes.name !== containerName) {
continue;
}
switch (parsed.data.Action) {
case "start":
onStatusChange("running");
break;
case "kill":
onStatusChange("stopping");
break;
case "die":
onStatusChange("stopped");
break;
}
}
});
} catch (error) {
// If we can't spawn the process, try again after a delay
scheduleRestart();
}
};
const scheduleRestart = () => {
if (isDisposed) return;
// Clear any existing timeout
clearTimeout(restartTimeout);
// Try to restart after a delay (exponential backoff would be better in production)
restartTimeout = setTimeout(() => {
if (!isDisposed) {
startListening();
}
}, 1_000);
};
// Start the initial listener
startListening();
return {
dispose() {
isDisposed = true;
if (restartTimeout) {
clearTimeout(restartTimeout);
}
dockerEvents?.kill();
},
};
}
async function getContainerStatus(
containerName: string,
): Promise<ContainerStatus> {
return new Promise((resolve) => {
exec(
`docker inspect --format {{.State.Status}} ${containerName}`,
(error, stdout) => {
if (error) {
resolve("stopped");
} else {
switch (stdout.trim()) {
case "created":
case "restarting":
case "running":
resolve("running");
break;
case "removing":
resolve("stopping");
break;
default:
resolve("stopped");
break;
}
}
},
);
});
}