Debian Codegraph @

pkg/lib/long-running-process.js

raw
1 /*
2 * Copyright (C) 2020 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 /* Manage a long-running precious process that runs independently from a Cockpit
7 * session in a transient systemd service unit. See
8 * examples/long-running-process/README.md for details.
9 *
10 * The unit will run as root, on the system systemd manager, so that every privileged
11 * Cockpit session shares the same unit. The same approach works in principle on
12 * the user's systemd instance, but the current code does not support that as it
13 * is not a common use case for Cockpit.
14 */
15
16 /* global cockpit */
17
18 // systemd D-Bus API names
19 const O_SD_OBJ = "/org/freedesktop/systemd1";
20 const I_SD_MGR = "org.freedesktop.systemd1.Manager";
21 const I_SD_UNIT = "org.freedesktop.systemd1.Unit";
22 const I_DBUS_PROP = "org.freedesktop.DBus.Properties";
23
24 /* Possible LongRunningProcess.state values */
25 export const ProcessState = {
26 INIT: 'init',
27 STOPPED: 'stopped',
28 RUNNING: 'running',
29 FAILED: 'failed',
30 };
31
32 export class LongRunningProcess {
33 /* serviceName: systemd unit name to start or reattach to
34 * updateCallback: function that gets called whenever the state changed; first and only
35 * argument is `this` LongRunningProcess instance.
36 */
37 constructor(serviceName, updateCallback) {
38 this.systemdClient = cockpit.dbus("org.freedesktop.systemd1", { superuser: "require" });
39 this.serviceName = serviceName;
40 this.updateCallback = updateCallback;
41 this._setState(ProcessState.INIT);
42 this.startTimestamp = null; // µs since epoch
43 this.terminated = false;
44
45 // Watch for start event of the service
46 this.systemdClient.subscribe({ interface: I_SD_MGR, member: "JobNew" }, (path, iface, signal, args) => {
47 if (args[2] == this.serviceName)
48 this._checkState();
49 });
50
51 // Check if it is already running
52 this._checkState();
53 }
54
55 /** Start long-running process. Only call this in states STOPPED or FAILED.
56 * This runs as root, thus will be shared with all privileged Cockpit sessions.
57 * Return cockpit.spawn promise. You need to handle exceptions, but not success.
58 * @param {string[]} argv array starting with executable and all of the arguments to pass to it
59 * @param {object} options same properties as cockpit-spawn https://docs.cockpit-project.org/cockpit-guide/latest/guide/cockpit-spawn.html/cockpit-spawn.html
60 * @param {string[]} runArgs arguments to provide to systemd-run itself, such as `--setenv`
61 */
62 run(argv, options, runArgs = []) {
63 if (this.state !== ProcessState.STOPPED && this.state !== ProcessState.FAILED)
64 throw new Error(`cannot start LongRunningProcess in state ${this.state}`);
65 // no need to directly react to this -- JobNew and _checkState() will pick up when the unit runs
66 return cockpit.spawn(
67 [
68 "systemd-run",
69 "--unit", this.serviceName,
70 "--service-type=oneshot",
71 "--no-block",
72 ...runArgs,
73 "--"
74 ].concat(argv),
75 { superuser: "require", err: "message", ...options }
76 );
77 }
78
79 /* Stop long-running process while it is RUNNING, or reset a FAILED one */
80 terminate() {
81 if (this.state !== ProcessState.RUNNING && this.state !== ProcessState.FAILED)
82 throw new Error(`cannot terminate LongRunningProcess in state ${this.state}`);
83
84 /* This sends a SIGTERM to the unit, causing it to go into "failed" state. This would not
85 * happen with `systemd-run -p SuccessExitStatus=0`, but that does not yet work on older
86 * OSes with systemd ≤ 241 So let checkState() know that a failure is due to termination. */
87 this.terminated = true;
88 return this.systemdClient.call(O_SD_OBJ, I_SD_MGR, "StopUnit", [this.serviceName, "replace"], { type: "ss" });
89 }
90
91 reset() {
92 if (this.state === ProcessState.FAILED)
93 this.systemdClient.call(O_SD_OBJ, I_SD_MGR, "ResetFailedUnit", [this.serviceName], { type: "s" });
94 else
95 throw new Error(`cannot reset LongRunningProcess in state ${this.state}`);
96 }
97 /*
98 * below are internal private methods
99 */
100
101 _setState(state) {
102 /* PropertiesChanged often gets fired multiple times with the same values, avoid UI flicker */
103 if (state === this.state)
104 return;
105 this.state = state;
106 this.terminated = false;
107 if (this.updateCallback)
108 this.updateCallback(this);
109 }
110
111 _setStateFromProperties(activeState, stateChangeTimestamp) {
112 switch (activeState) {
113 case 'activating':
114 this.startTimestamp = stateChangeTimestamp;
115 this._setState(ProcessState.RUNNING);
116 break;
117 case 'failed':
118 this.startTimestamp = null; // TODO: can we derive this from InvocationID?
119 if (this.terminated) {
120 /* terminating causes failure; reset that and do not announce it as failed */
121 this.systemdClient.call(O_SD_OBJ, I_SD_MGR, "ResetFailedUnit", [this.serviceName], { type: "s" });
122 } else {
123 this._setState(ProcessState.FAILED);
124 }
125 break;
126 case 'inactive':
127 this._setState(ProcessState.STOPPED);
128 break;
129 case 'deactivating':
130 /* ignore these transitions */
131 break;
132 default:
133 throw new Error(`unexpected state of unit ${this.serviceName}: ${activeState}`);
134 }
135 }
136
137 // check if the transient unit for our command is running
138 _checkState() {
139 this.systemdClient.call(O_SD_OBJ, I_SD_MGR, "GetUnit", [this.serviceName], { type: "s" })
140 .then(([unitObj]) => {
141 /* Some time may pass between getting JobNew and the unit actually getting activated;
142 * we may get an inactive unit here; watch for state changes. This will also update
143 * the UI if the unit stops. */
144 this.subscription = this.systemdClient.subscribe(
145 { interface: I_DBUS_PROP, member: "PropertiesChanged" },
146 (path, iface, signal, args) => {
147 if (path === unitObj && args[1].ActiveState && args[1].StateChangeTimestamp)
148 this._setStateFromProperties(args[1].ActiveState.v, args[1].StateChangeTimestamp.v);
149 });
150
151 this.systemdClient.call(unitObj, I_DBUS_PROP, "GetAll", [I_SD_UNIT], { type: "s" })
152 .then(([props]) => this._setStateFromProperties(props.ActiveState.v, props.StateChangeTimestamp.v))
153 .catch(ex => {
154 throw new Error(`unexpected failure of GetAll(${unitObj}): ${ex.toString()}`);
155 });
156 })
157 .catch(ex => {
158 if (ex.name === "org.freedesktop.systemd1.NoSuchUnit") {
159 if (this.subscription) {
160 this.subscription.remove();
161 this.subscription = null;
162 }
163 this._setState(ProcessState.STOPPED);
164 } else {
165 throw new Error(`unexpected failure of GetUnit(${this.serviceName}): ${ex.toString()}`);
166 }
167 });
168 }
169 }