-
Notifications
You must be signed in to change notification settings - Fork 39
/
app.ts
350 lines (275 loc) · 12.4 KB
/
app.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
* Copyright (c) 2022 Peking University and Peking University Institute for Computing and Digital Economy
* SCOW is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
import { getAppConfigs } from "@scow/config/build/app";
import { getPlaceholderKeys } from "@scow/lib-config/build/parse";
import { loggedExec, sftpChmod, sftpExists,
sftpReaddir, sftpReadFile, sftpRealPath, sftpWriteFile } from "@scow/lib-ssh";
import { RunningJob } from "@scow/protos/build/common/job";
import { randomUUID } from "crypto";
import fs from "fs";
import { join } from "path";
import { quote } from "shell-quote";
import { AppOps, AppSession } from "src/clusterops/api/app";
import { displayIdToPort } from "src/clusterops/slurm/bl/port";
import { portalConfig } from "src/config/portal";
import { getClusterLoginNode, sshConnect } from "src/utils/ssh";
import { parseDisplayId, refreshPassword, VNCSERVER_BIN_PATH } from "src/utils/turbovnc";
import { querySqueue } from "./bl/queryJobInfo";
import { generateJobScript, parseSbatchOutput } from "./bl/submitJob";
interface SessionMetadata {
sessionId: string;
jobId: number;
appId: string;
submitTime: string;
}
// All keys are strings except PORT
interface ServerSessionInfoData {
[key: string]: string | number;
HOST: string;
PORT: number;
PASSWORD: string;
}
const SERVER_ENTRY_COMMAND = fs.readFileSync("assets/slurm/server_entry.sh", { encoding: "utf-8" });
const VNC_ENTRY_COMMAND = fs.readFileSync("assets/slurm/vnc_entry.sh", { encoding: "utf-8" });
const VNC_OUTPUT_FILE = "output";
const SESSION_METADATA_NAME = "session.json";
const SERVER_SESSION_INFO = "server_session_info.json";
const VNC_SESSION_INFO = "VNC_SESSION_INFO";
export const slurmAppOps = (cluster: string): AppOps => {
const host = getClusterLoginNode(cluster);
if (!host) { throw new Error(`Cluster ${cluster} has no login node`); }
return {
createApp: async (request, logger) => {
const apps = getAppConfigs();
const { appId, userId, account, coreCount, maxTime, partition, qos, customAttributes } = request;
// prepare script file
const appConfig = apps[appId];
if (!appConfig) { return { code: "APP_NOT_FOUND" }; }
const jobName = randomUUID();
const workingDirectory = join(portalConfig.appJobsDir, jobName);
return await sshConnect(host, userId, logger, async (ssh) => {
// make sure workingDirectory exists.
await ssh.mkdir(workingDirectory);
const sftp = await ssh.requestSFTP();
const submitAndWriteMetadata = async (script: string, env?: Record<string, string>) => {
const remoteEntryPath = join(workingDirectory, "entry.sh");
await sftpWriteFile(sftp)(remoteEntryPath, script);
// submit entry.sh
// createApp is slow already
// use executeAsUser increases code complexity greatly
const { code, stderr, stdout } = await loggedExec(ssh, logger, false,
"sbatch", [remoteEntryPath], { execOptions: { env: env as NodeJS.ProcessEnv } },
);
if (code !== 0) {
return { code: "SBATCH_FAILED", message: stderr } as const;
}
// parse stdout output to get the job id
const jobId = parseSbatchOutput(stdout);
// write session metadata
const metadata: SessionMetadata = {
jobId,
sessionId: jobName,
submitTime: new Date().toISOString(),
appId,
};
await sftpWriteFile(sftp)(join(workingDirectory, SESSION_METADATA_NAME), JSON.stringify(metadata));
return { code: "OK", jobId, sessionId: metadata.sessionId } as const;
};
let customAttributesExport: string = "";
for (const key in customAttributes) {
const quotedAttribute = quote([customAttributes[key] ?? ""]);
const envItem = `export ${key}=${quotedAttribute}`;
customAttributesExport = customAttributesExport + envItem + "\n";
}
if (appConfig.type === "web") {
let customForm = String.raw`\"HOST\":\"$HOST\",\"PORT\":$PORT`;
for (const key in appConfig.web!.connect.formData) {
const texts = getPlaceholderKeys(appConfig.web!.connect.formData[key]);
for (const i in texts) {
customForm += `,\\\"${texts[i]}\\\":\\\"$${texts[i]}\\\"`;
}
}
const sessionInfo = `echo -e "{${customForm}}" >$SERVER_SESSION_INFO`;
const beforeScript = customAttributesExport + appConfig.web!.beforeScript + sessionInfo;
await sftpWriteFile(sftp)(join(workingDirectory, "before.sh"), beforeScript);
await sftpWriteFile(sftp)(join(workingDirectory, "script.sh"), appConfig.web!.script);
const script = generateJobScript({
jobName,
command: SERVER_ENTRY_COMMAND,
account: account,
coreCount: coreCount,
maxTime: maxTime,
nodeCount: 1,
partition: partition,
workingDirectory,
qos: qos,
otherOptions: appConfig.slurm?.options,
});
return await submitAndWriteMetadata(script, { SERVER_SESSION_INFO });
} else {
// vnc app
const beforeScript = customAttributesExport + (appConfig.vnc!.beforeScript ?? "");
await sftpWriteFile(sftp)(join(workingDirectory, "before.sh"), beforeScript);
const xstartupPath = join(workingDirectory, "xstartup");
await sftpWriteFile(sftp)(xstartupPath, appConfig.vnc!.xstartup);
await sftpChmod(sftp)(xstartupPath, "755");
const script = generateJobScript({
jobName,
command: VNC_ENTRY_COMMAND,
account: account,
coreCount: coreCount,
maxTime: maxTime,
nodeCount: 1,
partition: partition,
workingDirectory,
qos: qos,
output: VNC_OUTPUT_FILE,
otherOptions: appConfig.slurm?.options,
});
return await submitAndWriteMetadata(script, { VNC_SESSION_INFO, VNCSERVER_BIN_PATH });
}
});
},
listAppSessions: async (request, logger) => {
const apps = getAppConfigs();
const { userId } = request;
// using squeue to get jobs that are running
// If a job is not running, it cannot be ready
const runningJobsInfo = await sshConnect(host, "root", logger, async (ssh) => {
return querySqueue(ssh, userId, logger, ["-u", userId]);
});
const runningJobInfoMap = runningJobsInfo.reduce((prev, curr) => {
prev[curr.jobId] = curr;
return prev;
}, {} as Record<number, RunningJob>);
return await sshConnect(host, userId, logger, async (ssh) => {
const sftp = await ssh.requestSFTP();
if (!await sftpExists(sftp, portalConfig.appJobsDir)) { return { sessions: []}; }
const list = await sftpReaddir(sftp)(portalConfig.appJobsDir);
const sessions = [] as AppSession[];
await Promise.all(list.map(async ({ filename }) => {
const jobDir = join(portalConfig.appJobsDir, filename);
const metadataPath = join(jobDir, SESSION_METADATA_NAME);
if (!await sftpExists(sftp, metadataPath)) {
return;
}
const content = await sftpReadFile(sftp)(metadataPath);
const sessionMetadata = JSON.parse(content.toString()) as SessionMetadata;
const runningJobInfo: RunningJob | undefined = runningJobInfoMap[sessionMetadata.jobId];
const app = apps[sessionMetadata.appId];
let ready = false;
// judge whether the app is ready
if (runningJobInfo && runningJobInfo.state === "RUNNING") {
if (app.type === "web") {
// for server apps,
// try to read the SESSION_INFO file to get port and password
const infoFilePath = join(jobDir, SERVER_SESSION_INFO);
ready = await sftpExists(sftp, infoFilePath);
} else {
// for vnc apps,
// try to find the output file and try to parse the display number
const outputFilePath = join(jobDir, VNC_OUTPUT_FILE);
if (await sftpExists(sftp, outputFilePath)) {
const content = (await sftpReadFile(sftp)(outputFilePath)).toString();
try {
parseDisplayId(content);
ready = true;
} catch {
// ignored if displayId cannot be parsed
}
}
}
}
sessions.push({
jobId: sessionMetadata.jobId,
appId: sessionMetadata.appId,
sessionId: sessionMetadata.sessionId,
submitTime: new Date(sessionMetadata.submitTime),
state: runningJobInfo?.state ?? "ENDED",
ready,
dataPath: await sftpRealPath(sftp)(jobDir),
runningTime: runningJobInfo?.runningTime ?? "",
timeLimit: runningJobInfo?.timeLimit ?? "",
});
}));
return { sessions };
});
},
connectToApp: async (request, logger) => {
const apps = getAppConfigs();
const { sessionId, userId } = request;
return await sshConnect(host, userId, logger, async (ssh) => {
const sftp = await ssh.requestSFTP();
const jobDir = join(portalConfig.appJobsDir, sessionId);
if (!await sftpExists(sftp, jobDir)) {
return { code: "NOT_FOUND" };
}
const metadataPath = join(jobDir, SESSION_METADATA_NAME);
const content = await sftpReadFile(sftp)(metadataPath);
const sessionMetadata = JSON.parse(content.toString()) as SessionMetadata;
const app = apps[sessionMetadata.appId];
if (app.type === "web") {
const infoFilePath = join(jobDir, SERVER_SESSION_INFO);
if (await sftpExists(sftp, infoFilePath)) {
const content = await sftpReadFile(sftp)(infoFilePath);
const serverSessionInfo = JSON.parse(content.toString()) as ServerSessionInfoData;
const { HOST, PORT, PASSWORD, ...rest } = serverSessionInfo;
const customFormData = rest as {[key: string]: string};
return {
code: "OK",
appId: sessionMetadata.appId,
host: HOST,
port: +PORT,
password: PASSWORD,
customFormData: customFormData ?? {},
};
}
} else {
// for vnc apps,
// try to find the output file and try to parse the display number
const vncSessionInfoPath = join(jobDir, VNC_SESSION_INFO);
// try to read the host info
if (await sftpExists(sftp, vncSessionInfoPath)) {
const host = (await sftpReadFile(sftp)(vncSessionInfoPath)).toString().trim();
const outputFilePath = join(jobDir, VNC_OUTPUT_FILE);
if (await sftpExists(sftp, outputFilePath)) {
const content = (await sftpReadFile(sftp)(outputFilePath)).toString();
let displayId: number | undefined = undefined;
try {
displayId = parseDisplayId(content);
} catch {
// ignored if displayId cannot be parsed
}
if (displayId) {
// the server is run at the compute node
// login to the compute node and refresh the password
// connect as user so that
// the service node doesn't need to be able to connect to compute nodes with public key
return await sshConnect(host, userId, logger, async (computeNodeSsh) => {
const password = await refreshPassword(computeNodeSsh, null, logger, displayId!);
return {
code: "OK",
appId: sessionMetadata.appId,
host,
port: displayIdToPort(displayId!),
password,
};
});
}
}
}
}
return { code: "UNAVAILABLE" };
});
},
};
};