Debian Codegraph @

pkg/packagekit/autoupdates.jsx

raw
1 /*
2 * Copyright (C) 2017 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7 import React, { useState } from "react";
8 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
9 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
10 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
11 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
12 import { FormSelect, FormSelectOption } from "@patternfly/react-core/dist/esm/components/FormSelect/index.js";
13 import {
14 Modal, ModalBody, ModalFooter, ModalHeader
15 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
16 import { Radio } from "@patternfly/react-core/dist/esm/components/Radio/index.js";
17 import { TimePicker } from "@patternfly/react-core/dist/esm/components/TimePicker/index.js";
18
19 import { install_dialog } from "cockpit-components-install-dialog.jsx";
20 import { useDialogs } from "dialogs.jsx";
21
22 import { debug } from "./utils";
23
24 const _ = cockpit.gettext;
25
26 /**
27 * Package manager specific implementations; PackageKit does not cover
28 * automatic updates, so we have to implement dnf-automatic and
29 * unattended-upgrades configuration ourselves
30 */
31
32 class ImplBase {
33 constructor() {
34 this.supported = true; // false if system was customized in a way that we cannot parse
35 this.enabled = null; // boolean
36 this.type = null; // "all" or "security"
37 this.day = null; // systemd.time(7) day of week (e. g. "mon"), or empty for daily
38 this.time = null; // systemd.time(7) time (e. g. "06:00") or empty for "any time"
39 this.installed = null; // boolean
40 this.packageName = null; // name of the package providing automatic updates
41 }
42
43 // Init data members. Return a promise that resolves when done.
44 async getConfig() {
45 throw new Error("abstract method");
46 }
47
48 // Update configuration for given non-null values, and update member variables on success;
49 // return a promise that resolves when done, or fails when configuration writing fails
50 async setConfig(enabled, type, day, time) {
51 throw new Error("abstract method", enabled, type, day, time);
52 }
53
54 parseCalendar(spec) {
55 // see systemd.time(7); we only support what we write, otherwise we treat it as custom config and "unsupported"
56 const daysOfWeek = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
57 const validTime = /^((|0|1)[0-9]|2[0-3]):[0-5][0-9]$/;
58
59 const words = spec.trim().toLowerCase()
60 .split(/\s+/);
61
62 // check if we have a day of week
63 if (daysOfWeek.indexOf(words[0]) >= 0) {
64 this.day = words.shift();
65 } else if (words[0] === '*-*-*') {
66 this.day = ""; // daily with "all matches" date specification
67 words.shift();
68 } else {
69 this.day = ""; // daily without date specification
70 }
71
72 // now there should only be a time left
73 if (words.length == 1 && validTime.test(words[0]))
74 this.time = words[0].replace(/^0+/, "");
75 else
76 this.supported = false;
77 }
78 }
79
80 class Dnf4Impl extends ImplBase {
81 async getConfig() {
82 this.packageName = "dnf-automatic";
83
84 try {
85 // - dnf 4 has two ways to enable automatic updates: Either by enabling dnf-automatic-install.timer
86 // or by setting "apply_updates = yes" in the config file and enabling dnf-automatic.timer
87 // - the config file determines whether to apply security updates only
88 // - by default this runs every day (OnUnitInactiveSec=1d), but the timer can be changed with a timer unit
89 // drop-in, so get the last line
90 const output = await cockpit.script(
91 "set -e; if rpm -q " + this.packageName + " >/dev/null; then echo installed; fi; " +
92 "if grep -q '^[ \\t]*upgrade_type[ \\t]*=[ \\t]*security' /etc/dnf/automatic.conf; then echo security; fi; " +
93 "TIMER=dnf-automatic-install.timer; " +
94 "if systemctl --quiet is-enabled dnf-automatic-install.timer 2>/dev/null; then echo enabled; " +
95 "elif systemctl --quiet is-enabled dnf-automatic.timer 2>/dev/null && grep -q '^[ \t]*apply_updates[ \t]*=[ \t]*yes' " +
96 " /etc/dnf/automatic.conf; then echo enabled; TIMER=dnf-automatic.timer; " +
97 "fi; " +
98 'OUT=$(systemctl cat $TIMER 2>/dev/null || true); ' +
99 'echo "$OUT" | grep "^OnUnitInactiveSec= *[^ ]" | tail -n1; ' +
100 'echo "$OUT" | grep "^OnCalendar= *[^ ]" | tail -n1; ',
101 [], { err: "message" });
102
103 this.installed = (output.indexOf("installed\n") >= 0);
104 this.enabled = (output.indexOf("enabled\n") >= 0);
105 this.type = (output.indexOf("security\n") >= 0) ? "security" : "all";
106
107 // if we have OnCalendar=, use that (we disable OnUnitInactiveSec= in our drop-in)
108 const calIdx = output.indexOf("OnCalendar=");
109 if (calIdx >= 0) {
110 this.parseCalendar(output.substring(calIdx).split('\n')[0].split("=")[1]);
111 } else {
112 if (output.indexOf("InactiveSec=1d\n") >= 0)
113 this.day = this.time = "";
114 else if (this.installed)
115 this.supported = false;
116 }
117
118 debug(`dnf4 getConfig: supported ${this.supported}, enabled ${this.enabled}, type ${this.type}, day ${this.day}, time ${this.time}, installed ${this.installed}; raw response '${output}'`);
119 } catch (error) {
120 console.error("dnf4 getConfig failed:", error);
121 this.supported = false;
122 }
123 }
124
125 async setConfig(enabled, type, day, time) {
126 const timerConf = "/etc/systemd/system/dnf-automatic-install.timer.d/time.conf";
127 let script = "set -e; ";
128
129 if (type !== null) {
130 const value = (type == "security") ? "security" : "default";
131
132 // normally upgrade_type = should already be in the file, so replace that line;
133 // if it's not already present, append it to the file
134 script += "sed -i '/\\bupgrade_type\\b[ \\t]*=/ { h; s/^.*$/upgrade_type = " + value + "/ }; " +
135 "$ { x; /^$/ { s//upgrade_type = " + value + "/; H }; x }' /etc/dnf/automatic.conf; ";
136 }
137
138 // if we enable through Cockpit, make sure that starting the timer doesn't start the .service right away,
139 // due to the packaged default OnBootSec=1h; just set a reasonable initial time which will trigger the code below
140 if (enabled && !this.enabled && !this.time && !this.day)
141 time = "6:00";
142
143 if (time !== null || day !== null) {
144 if (day === "" && time === "") {
145 // restore defaults
146 script += "rm -f " + timerConf + "; ";
147 } else {
148 if (day == null)
149 day = this.day;
150 if (time == null)
151 time = this.time;
152 script += "mkdir -p /etc/systemd/system/dnf-automatic-install.timer.d; ";
153 script += "printf '[Timer]\\nOnBootSec=\\nOnCalendar=" + day + " " + time + "\\n' > " + timerConf + "; ";
154 script += "systemctl daemon-reload; ";
155 }
156 }
157
158 if (enabled !== null) {
159 const rebootConf = "/etc/systemd/system/dnf-automatic-install.service.d/autoreboot.conf";
160
161 script += "systemctl " + (enabled ? "enable" : "disable") + " --now dnf-automatic-install.timer; ";
162
163 if (enabled) {
164 /* dnf 4.15+ supports automatic reboots; check if the config option exists, and if so, change the
165 default to "when-needed"; but be strict about the format, to avoid changing a customized setting */
166 script += "if grep '^[[:space:]]*reboot\\b' /etc/dnf/automatic.conf; then ";
167 script += " sed -i 's/^reboot = never$/reboot = when-needed/' /etc/dnf/automatic.conf; ";
168 // and drop the previous hack on upgrades */
169 script += " rm -f " + rebootConf + "; ";
170 /* HACK for older dnf: enable automatic reboots after updating; dnf-automatic does not leave a log
171 file behind for deciding whether it actually installed anything, so resort to grepping the journal
172 for the last run (https://bugzilla.redhat.com/show_bug.cgi?id=1491190) */
173 script += "else ";
174 script += " mkdir -p /etc/systemd/system/dnf-automatic-install.service.d; ";
175 script += " printf '[Service]\\nExecStartPost=/bin/sh -ec \"" +
176 "if systemctl status --no-pager --lines=100 dnf-automatic-install.service| grep -q ===========$$; then " +
177 "shutdown -r +5 rebooting after applying package updates; fi\"\\n' > " + rebootConf + "; ";
178 script += " systemctl daemon-reload; ";
179 script += "fi";
180 } else {
181 // also make sure that the legacy unit name is disabled; this can fail if the unit does not exist
182 script += "systemctl disable --now dnf-automatic.timer 2>/dev/null || true; ";
183 script += "rm -f " + rebootConf + "; ";
184 }
185 }
186
187 debug(`dnf4 setConfig(${enabled}, "${type}", "${day}", "${time}"): script "${script}"`);
188
189 try {
190 await cockpit.script(script, [], { superuser: "require" });
191 debug("dnf4 setConfig: configuration updated successfully");
192 if (enabled !== null)
193 this.enabled = enabled;
194 if (type !== null)
195 this.type = type;
196 if (day !== null)
197 this.day = day;
198 if (time !== null)
199 this.time = time;
200 } catch (error) {
201 console.error("dnf4 setConfig failed:", error.toString());
202 }
203 }
204 }
205
206 class Dnf5Impl extends ImplBase {
207 async getConfig() {
208 this.packageName = "dnf5-plugin-automatic";
209 this.configFile = "/etc/dnf/dnf5-plugins/automatic.conf";
210
211 try {
212 await cockpit.spawn(["rpm", "-q", this.packageName], { err: "ignore" });
213 this.installed = true;
214 } catch (ex) {
215 this.installed = false;
216 debug("dnf5 getConfig: not installed:", ex);
217 return;
218 }
219
220 // - dnf 5 only has a single timer dnf5-automatic.timer and a config file with
221 // "apply_updates" (yes/no) and "upgrade_type" (default/security)
222 // - by default this runs every day (OnCalendar)
223 try {
224 const output = await cockpit.script(
225 "set -eu;" +
226 "if grep -q '^[ \\t]*upgrade_type[ \\t]*=[ \\t]*security' " + this.configFile + "; then echo security; fi; " +
227 "if systemctl --quiet is-enabled dnf5-automatic.timer && " +
228 " grep -q '^[ \t]*apply_updates[ \t]*=[ \t]*yes' " + this.configFile + "; then echo enabled; fi; " +
229 'OUT=$(systemctl cat dnf5-automatic.timer || true); ' +
230 'echo "$OUT" | grep "^OnUnitInactiveSec= *[^ ]" | tail -n1; ' +
231 'echo "$OUT" | grep "^OnCalendar= *[^ ]" | tail -n1; ',
232 [], { err: "message" });
233
234 this.enabled = (output.indexOf("enabled\n") >= 0);
235 this.type = (output.indexOf("security\n") >= 0) ? "security" : "all";
236
237 // if we have OnCalendar=, use that (we disable OnUnitInactiveSec= in our drop-in)
238 const calIdx = output.indexOf("OnCalendar=");
239 if (calIdx >= 0) {
240 this.parseCalendar(output.substring(calIdx).split('\n')[0].split("=")[1]);
241 } else {
242 if (output.indexOf("InactiveSec=1d\n") >= 0)
243 this.day = this.time = "";
244 else if (this.installed)
245 this.supported = false;
246 }
247
248 debug(`dnf5 getConfig: supported ${this.supported}, enabled ${this.enabled}, type ${this.type}, day ${this.day}, time ${this.time}, installed ${this.installed}; raw response '${output}'`);
249 } catch (error) {
250 console.error("dnf5 getConfig failed:", error);
251 this.supported = false;
252 }
253 }
254
255 async setConfig(enabled, type, day, time) {
256 const timerConfD = "/etc/systemd/system/dnf5-automatic.timer.d";
257 const timerConf = timerConfD + "/time.conf";
258 let script = "set -e; ";
259
260 // there's no default config file, admins are supposed to put their own settings into a new file
261 const settings = [];
262
263 if (type !== null)
264 settings.push(["upgrade_type", (type == "security") ? "security" : "default"]);
265
266 if (time !== null || day !== null) {
267 if (day === "" && time === "") {
268 // restore defaults
269 script += "rm -f " + timerConf + "; ";
270 } else {
271 if (day == null)
272 day = this.day;
273 if (time == null)
274 time = this.time;
275 script += "mkdir -p " + timerConfD + "; ";
276 script += "printf '[Timer]\\nOnBootSec=\\nOnCalendar=" + day + " " + time + "\\n' > " + timerConf + "; ";
277 script += "systemctl daemon-reload; ";
278 }
279 }
280
281 if (enabled !== null) {
282 script += "systemctl " + (enabled ? "enable" : "disable") + " --now dnf5-automatic.timer; ";
283
284 if (enabled) {
285 settings.push(["apply_updates", "yes"]);
286 settings.push(["reboot", "when-needed"]);
287 }
288 }
289
290 debug(`dnf5 setConfig(${enabled}, "${type}", "${day}", "${time}"): script "${script}", settings ${settings}`);
291
292 try {
293 if (settings.length > 0) {
294 // parse/update automatic.conf with the new settings; modify existing or append
295 await cockpit.file(this.configFile, { superuser: "require" }).modify(content => {
296 const lines = content ? content.split('\n') : [];
297 settings.forEach(([key, value]) => {
298 const idx = lines.findIndex(line => line.startsWith(key));
299 if (idx >= 0)
300 lines[idx] = key + " = " + value;
301 else
302 // let's avoid context sensitive parsing/writing; multiple sections are ok
303 lines.push(`[commands]\n${key} = ${value}`);
304 });
305 return lines.join('\n');
306 });
307 }
308
309 await cockpit.script(script, [], { superuser: "require" });
310 debug("dnf5 setConfig: configuration updated successfully");
311 if (enabled !== null)
312 this.enabled = enabled;
313 if (type !== null)
314 this.type = type;
315 if (day !== null)
316 this.day = day;
317 if (time !== null)
318 this.time = time;
319 } catch (error) {
320 console.error("dnf5 setConfig failed:", error.toString());
321 }
322 }
323 }
324
325 // Returns a promise for instantiating "backend"; this will never fail, if
326 // automatic updates are not supported, backend will be null.
327 export function getBackend(packagekit_backend, forceReinit) {
328 if (!getBackend.promise || forceReinit) {
329 debug("getBackend() called first time or forceReinit passed, initializing promise");
330 getBackend.promise = new Promise((resolve, reject) => {
331 if (packagekit_backend === "dnf5") {
332 const backend = new Dnf5Impl();
333 backend.getConfig().then(() => resolve(backend));
334 } else if (packagekit_backend === "dnf") {
335 // we need to do this runtime check -- you can e.g. install dnf5 on Fedora 40, but it's not the "main" dnf
336 cockpit.spawn(["dnf", "--version"], { err: "message" })
337 .then(version => {
338 const backend = version.includes("dnf5") ? new Dnf5Impl() : new Dnf4Impl();
339 backend.getConfig().then(() => resolve(backend));
340 })
341 .catch(ex => {
342 console.error("failed to run dnf --version:", ex);
343 resolve(null);
344 });
345 } else {
346 // TODO: apt backend
347 resolve(null);
348 }
349 });
350 }
351 return getBackend.promise;
352 }
353
354 const AutoUpdatesDialog = ({ backend }) => {
355 const Dialogs = useDialogs();
356 const [pending, setPending] = useState(false);
357 const [enabled, setEnabled] = useState(backend.enabled);
358 const [type, setType] = useState(backend.type);
359 const [day, setDay] = useState(backend.day);
360 const [time, setTime] = useState(backend.time && backend.time.padStart(5, "0"));
361
362 function save(event) {
363 setPending(true);
364 backend.setConfig(enabled, type, day, time)
365 .finally(Dialogs.close);
366
367 if (event)
368 event.preventDefault();
369 return false;
370 }
371
372 return (
373 <Modal position="top" variant="small" id="automatic-updates-dialog" isOpen
374 onClose={Dialogs.close}>
375 <ModalHeader title={_("Automatic updates")} />
376 <ModalBody>
377 <Form isHorizontal onSubmit={save}>
378 <FormGroup fieldId="type" label={_("Type")} hasNoPaddingTop>
379 <Radio isChecked={!enabled}
380 onChange={() => { setEnabled(false); setType(null) }}
381 isDisabled={pending}
382 label={_("No updates")}
383 id="no-updates"
384 name="type" />
385 <Radio isChecked={enabled && type === "security"}
386 onChange={() => { setEnabled(true); setType("security") }}
387 isDisabled={pending}
388 label={_("Security updates only")}
389 id="security-updates"
390 name="type" />
391 <Radio isChecked={enabled && type === "all"}
392 onChange={() => { setEnabled(true); setType("all") }}
393 isDisabled={pending}
394 label={_("All updates")}
395 id="all-updates"
396 name="type" />
397 </FormGroup>
398
399 {enabled &&
400 <>
401 <FormGroup fieldId="when" label={_("When")}>
402 <Flex className="auto-update-group">
403 <FormSelect id="auto-update-day"
404 isDisabled={pending}
405 value={day == "" ? "everyday" : day}
406 onChange={(_, d) => setDay(d == "everyday" ? "" : d) }>
407 <FormSelectOption value="everyday" label={_("every day")} />
408 <FormSelectOption value="mon" label={_("Mondays")} />
409 <FormSelectOption value="tue" label={_("Tuesdays")} />
410 <FormSelectOption value="wed" label={_("Wednesdays")} />
411 <FormSelectOption value="thu" label={_("Thursdays")} />
412 <FormSelectOption value="fri" label={_("Fridays")} />
413 <FormSelectOption value="sat" label={_("Saturdays")} />
414 <FormSelectOption value="sun" label={_("Sundays")} />
415 </FormSelect>
416
417 <span className="auto-conf-text">{_("at")}</span>
418
419 <TimePicker time={time} is24Hour
420 menuAppendTo={() => document.body}
421 id="auto-update-time" isDisabled={pending}
422 invalidFormatErrorMessage={_("Invalid time format")}
423 onChange={(_, time) => setTime(time)} />
424 </Flex>
425 </FormGroup>
426
427 <Alert variant="info" title={_("This host will reboot after updates are installed.")} isInline />
428 </>}
429 </Form>
430 </ModalBody>
431 <ModalFooter>
432 <Button variant="primary"
433 isLoading={pending}
434 isDisabled={pending}
435 onClick={save}>
436 {_("Save changes")}
437 </Button>
438 <Button variant="link"
439 isDisabled={pending}
440 onClick={Dialogs.close}>
441 {_("Cancel")}
442 </Button>
443 </ModalFooter>
444 </Modal>);
445 };
446
447 export const AutoUpdates = ({ privileged, packagekit_backend, initial_backend }) => {
448 const Dialogs = useDialogs();
449 const [backend, setBackend] = useState(initial_backend);
450
451 if (!backend)
452 return null;
453
454 let state = null;
455 if (!backend.enabled)
456 state = _("Disabled");
457 if (!backend.installed)
458 state = _("Not set up");
459
460 const days = {
461 "": _("every day"),
462 mon: _("every Monday"),
463 tue: _("every Tuesday"),
464 wed: _("every Wednesday"),
465 thu: _("every Thursday"),
466 fri: _("every Friday"),
467 sat: _("every Saturday"),
468 sun: _("every Sunday")
469 };
470
471 let desc = null;
472
473 if (backend.enabled && backend.supported) {
474 const day = days[backend.day];
475 const time = backend.time;
476 desc = backend.type == "security"
477 ? cockpit.format(_("Security updates will be applied $0 at $1"), day, time)
478 : cockpit.format(_("Updates will be applied $0 at $1"), day, time);
479 }
480
481 if (privileged && backend.installed && !backend.supported)
482 return (
483 <div id="autoupdates-settings">
484 <Alert isInline
485 variant="info"
486 className="autoupdates-card-error"
487 title={_("Failed to parse unit files for dnf-automatic.timer or dnf-automatic-install.timer. Please remove custom overrides to configure automatic updates.")} />
488 </div>
489 );
490
491 return (
492 <div id="autoupdates-settings">
493 <Flex alignItems={{ default: 'alignItemsCenter' }}>
494 <Flex grow={{ default: 'grow' }} alignItems={{ default: 'alignItemsBaseline' }}>
495 <FlexItem>
496 <b>{_("Automatic updates")}</b>
497 </FlexItem>
498 <FlexItem>
499 {state}
500 </FlexItem>
501 </Flex>
502 <Flex>
503 <Button variant="secondary"
504 isDisabled={!privileged}
505 size="sm"
506 onClick={() => {
507 if (!backend.installed) {
508 install_dialog(backend.packageName)
509 .then(() => {
510 getBackend(packagekit_backend, true).then(b => {
511 setBackend(b);
512 Dialogs.show(<AutoUpdatesDialog backend={b} />);
513 });
514 }, () => null);
515 } else {
516 Dialogs.show(<AutoUpdatesDialog backend={backend} />);
517 }
518 }}>
519 {!backend.installed ? _("Enable") : _("Edit")}
520 </Button>
521 </Flex>
522 </Flex>
523 {desc}
524 </div>);
525 };