CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/pages/api/v2/compute/scripts.ts
Views: 687
1
/*
2
Returns a bash script that when run as root starts
3
a compute server and connects it to a project.
4
5
This is meant to be used for on prem compute servers,
6
hence it includes installing the /cocalc code and the "user" user.
7
*/
8
9
import {
10
getStartupScript,
11
getStopScript,
12
getDeprovisionScript,
13
} from "@cocalc/server/compute/control";
14
import { getAccountWithApiKey as getProjectIdWithApiKey } from "@cocalc/server/api/manage";
15
import getParams from "lib/api/get-params";
16
import getPool from "@cocalc/database/pool";
17
18
import { apiRoute, apiRouteOperation } from "lib/api";
19
import {
20
ComputeServerScriptsInputSchema,
21
ComputeServerScriptsOutputSchema,
22
} from "lib/api/schema/compute/scripts";
23
24
async function handle(req, res) {
25
try {
26
res.send(await get(req));
27
} catch (err) {
28
res.json({ error: `${err.message}` });
29
return;
30
}
31
}
32
33
export async function get(req) {
34
const { api_key, id: id0, action } = getParams(req);
35
// use api_key to get project, and also verify access:
36
const id = parseInt(id0);
37
return await getScript({ api_key, id, action });
38
}
39
40
export async function getScript({
41
api_key,
42
id,
43
action,
44
}: {
45
api_key: string;
46
id: number;
47
action: "start" | "stop" | "deprovision";
48
}): Promise<string> {
49
const project_id = await getProjectIdWithApiKey(api_key);
50
if (!project_id) {
51
throw Error("api_key must be a valid project api key");
52
}
53
const { rows } = await getPool().query(
54
"SELECT COUNT(*) AS count FROM compute_servers WHERE id=$1 AND project_id=$2",
55
[id, project_id],
56
);
57
if (rows[0]?.count != 1) {
58
throw Error(`no compute server with id=${id} in project with this api key`);
59
}
60
if (action == "start") {
61
return await getStartupScript({
62
id,
63
api_key,
64
installUser: true,
65
});
66
} else if (action == "stop") {
67
return await getStopScript({
68
id,
69
api_key,
70
});
71
} else if (action == "deprovision") {
72
return await getDeprovisionScript({
73
id,
74
api_key,
75
});
76
} else {
77
throw Error(`unknown action=${action}`);
78
}
79
}
80
81
export default apiRoute({
82
scripts: apiRouteOperation({
83
method: "POST",
84
openApiOperation: {
85
tags: ["Compute"],
86
},
87
})
88
.input({
89
contentType: "application/json",
90
body: ComputeServerScriptsInputSchema,
91
})
92
.outputs([
93
{
94
status: 200,
95
contentType: "text/plain",
96
body: ComputeServerScriptsOutputSchema,
97
},
98
])
99
.handler(handle),
100
});
101
102