-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmanage.ts
More file actions
254 lines (227 loc) · 6.81 KB
/
manage.ts
File metadata and controls
254 lines (227 loc) · 6.81 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
import { v7 as uuidv7 } from "uuid";
import type { ExtensionContext, LogOutputChannel, MessageItem } from "vscode";
import { commands, env, Uri, window } from "vscode";
import { checkIsLicenseValid } from "./authenticate.ts";
import { spawnLocalStack } from "./cli.ts";
import { exec } from "./exec.ts";
import { spawn } from "./spawn.ts";
import type { Telemetry } from "./telemetry.ts";
export type LocalstackStatus = "running" | "starting" | "stopping" | "stopped";
let previousStatus: LocalstackStatus | undefined;
async function fetchHealth(): Promise<boolean> {
// health is ok in the majority of use cases, however, determining status based on it can be flaky.
// for example, if localstack becomes unhealthy while running for reasons other that stop then reporting "stopping" may be misleading.
// though we don't know if it happens often.
try {
const response = await fetch("http://localhost:4566/_localstack/health");
return response.ok;
} catch {
return false;
}
}
async function fetchLocalStackSessionId(): Promise<string> {
try {
// TODO info endpoint is not available immediately
// potentially improve this later for tracking "vscode:emulator:started"
const infoResponse = await fetch("http://localhost:4566/_localstack/info");
if (infoResponse.ok) {
const info = (await infoResponse.json()) as { session_id?: string };
return info.session_id ?? "";
}
} catch {
// unable to fetch session id
}
return "";
}
async function getStatusFromCLI(): Promise<LocalstackStatus | undefined> {
try {
const result = await exec(
"docker inspect -f '{{.State.Status}}' localstack-main",
);
if (result.stdout.includes("running")) {
return "running";
} else if (result.stdout.includes("stopped")) {
return "stopped";
}
} catch {
return undefined;
}
}
export async function getLocalstackStatus(): Promise<LocalstackStatus> {
const [healthOk, status] = await Promise.all([
fetchHealth(),
getStatusFromCLI(),
]);
if (healthOk && status === "running") {
previousStatus = "running";
return "running";
}
if (!healthOk && status !== "running") {
previousStatus = "stopped";
return "stopped";
}
if (previousStatus === "stopped" && !healthOk && status === "running") {
previousStatus = "starting";
return "starting";
}
if (previousStatus === "running" && !healthOk) {
previousStatus = "stopping";
return "stopping";
}
return previousStatus ?? "stopped";
}
export async function startLocalStack(
outputChannel: LogOutputChannel,
telemetry: Telemetry,
): Promise<void> {
void showInformationMessage("Starting LocalStack.", {
title: "View Logs",
command: "localstack.viewLogs",
});
try {
await spawnLocalStack(
[
"start",
// DO NOT REMOVE!
// When spawning localstack in a subprocess from a VSCode extension in Windows, the banner will output the whale emoticon (🐳),
// and then omething regarding text encoding fails, making the process to stop with the following error:
// `\u274c Error: 'charmap' codec can't encode character '\U0001f433' in position 35: character maps to <undefined>`.
"--no-banner",
// On Windows, use detached so the process doesn't have a chance to print special unicode characters.
"--detached",
],
{
outputChannel,
onStderr(data: Buffer, context) {
const text = data.toString();
// Currently, the LocalStack CLI does not exit if the container fails to start in specific scenarios.
// As a workaround, we look for a specific error message in the output to determine if the container failed to start.
if (
text.includes(
"localstack.utils.container_utils.container_client.ContainerException",
)
) {
// Abort the process if we detect a ContainerException, otherwise it will hang indefinitely.
context.abort();
throw new Error("ContainerException");
}
},
},
);
const emulatorSessionId = await fetchLocalStackSessionId();
telemetry.track({
name: "started",
payload: {
namespace: "emulator",
status: "COMPLETED",
emulator_session_id: emulatorSessionId,
},
});
} catch (error) {
const isLicenseValid = await checkIsLicenseValid(outputChannel);
if (isLicenseValid === false) {
void showErrorMessage("No valid LocalStack license found.", {
title: "Go to License settings",
command: "localstack.openLicensePage",
});
} else {
void showErrorMessage("Failed to start LocalStack.", {
title: "View Logs",
command: "localstack.viewLogs",
});
throw error;
}
telemetry.track({
name: "started",
payload: {
namespace: "emulator",
status: "FAILED",
errors: [String(error)],
},
});
}
}
export async function stopLocalStack(
outputChannel: LogOutputChannel,
telemetry: Telemetry,
) {
void showInformationMessage("Stopping LocalStack.");
try {
// get session id before killing container
const emulatorSessionId = await fetchLocalStackSessionId();
await spawnLocalStack(["stop"], {
outputChannel,
});
telemetry.track({
name: "stopped",
payload: {
namespace: "emulator",
status: "COMPLETED",
emulator_session_id: emulatorSessionId,
},
});
} catch (error) {
void showErrorMessage("Failed to stop LocalStack.", {
title: "View Logs",
command: "localstack.viewLogs",
});
telemetry.track({
name: "stopped",
payload: {
namespace: "emulator",
status: "FAILED",
errors: [String(error)],
},
});
}
}
export async function openLicensePage() {
const url = new URL("https://app.localstack.cloud/settings/auth-tokens");
await env.openExternal(Uri.parse(url.toString()));
}
async function showInformationMessage(
message: string,
...items: (MessageItem & { command: string })[]
) {
const selection = await window.showInformationMessage(message, ...items);
if (selection) {
await commands.executeCommand(selection.command);
}
}
async function showErrorMessage(
message: string,
...items: (MessageItem & { command: string })[]
) {
const selection = await window.showErrorMessage(message, ...items);
if (selection) {
await commands.executeCommand(selection.command);
}
}
export async function getLocalstackVersion(
outputChannel: LogOutputChannel,
): Promise<string | undefined> {
try {
const { stdout } = await exec("localstack --version");
const versionMatch = stdout.match(/\d+\.\d+\.\d+/);
if (!versionMatch) {
outputChannel.error(
`Failed to parse LocalStack from version output: ${stdout}`,
);
return undefined;
}
return versionMatch[0];
} catch {
return undefined;
}
}
// Checks for session_id in workspaceState, creates if missing
export async function getOrCreateExtensionSessionId(
context: ExtensionContext,
): Promise<string> {
let sessionId = context.workspaceState.get<string>("session_id");
if (!sessionId) {
sessionId = uuidv7();
await context.workspaceState.update("session_id", sessionId);
}
return sessionId;
}