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/project/sage_restart.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { executeCode } from "@cocalc/backend/execute-code";
7
import { getLogger } from "@cocalc/backend/logger";
8
import { to_json } from "@cocalc/util/misc";
9
10
const winston = getLogger("sage-restart");
11
12
// Wait up to this long for the Sage server to start responding
13
// connection requests, after we restart it. It can
14
// take a while, since it pre-imports the sage library
15
// at startup, before forking.
16
export const SAGE_SERVER_MAX_STARTUP_TIME_S = 60;
17
18
let restarting = false;
19
let restarted = 0; // time when we last restarted it
20
21
export async function restart_sage_server() {
22
const dbg = (m) => winston.debug(`restart_sage_server: ${to_json(m)}`);
23
if (restarting) {
24
dbg("hit lock");
25
throw new Error("already restarting sage server");
26
}
27
28
const t = Date.now() - restarted;
29
30
if (t <= SAGE_SERVER_MAX_STARTUP_TIME_S * 1000) {
31
const err = `restarted sage server ${t}ms ago: not allowing too many restarts too quickly...`;
32
dbg(err);
33
throw new Error(err);
34
}
35
36
restarting = true;
37
38
dbg("restarting the daemon");
39
40
try {
41
const output = await executeCode({
42
command: "smc-sage-server restart",
43
timeout: 45,
44
ulimit_timeout: false, // very important -- so doesn't kill after 30 seconds of cpu!
45
err_on_exit: true,
46
bash: true,
47
});
48
dbg(
49
`successfully restarted sage server daemon -- '${JSON.stringify(output)}'`
50
);
51
} catch (err) {
52
const msg = `failed to restart sage server daemon -- ${err}`;
53
dbg(msg);
54
throw new Error(msg);
55
} finally {
56
restarting = false;
57
restarted = Date.now();
58
}
59
}
60
61