Debian Codegraph @

pkg/systemd/service-details.jsx

raw
1 /*
2 * Copyright (C) 2019 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React, { useState } from "react";
7 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
8 import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
9 import { DropdownItem } from '@patternfly/react-core/dist/esm/components/Dropdown/index.js';
10 import { Divider } from '@patternfly/react-core/dist/esm/components/Divider/index.js';
11 import { Flex } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
12 import { ExpandableSection } from "@patternfly/react-core/dist/esm/components/ExpandableSection/index.js";
13 import { Tooltip, TooltipPosition } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
14 import { Card, CardHeader, CardBody, CardTitle } from "@patternfly/react-core/dist/esm/components/Card/index.js";
15 import { List, ListItem } from "@patternfly/react-core/dist/esm/components/List/index.js";
16 import {
17 Modal, ModalBody, ModalFooter, ModalHeader
18 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
19 import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
20 import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
21 import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
22 import { Icon } from "@patternfly/react-core/dist/esm/components/Icon/index.js";
23 import {
24 AsleepIcon,
25 BanIcon, ErrorCircleOIcon, OnRunningIcon, OffIcon,
26 ExclamationCircleIcon,
27 OkIcon, UserIcon, ThumbtackIcon,
28 } from "@patternfly/react-icons";
29
30 import cockpit from "cockpit";
31 import s_bus from "./busnames.js";
32 import { systemd_client, MAX_UINT64 } from "./services.jsx";
33 import * as timeformat from "timeformat";
34 import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
35 import { useDialogs, DialogsContext } from "dialogs.jsx";
36 import { ModalError } from 'cockpit-components-inline-notification.jsx';
37
38 import './service-details.scss';
39 import { KebabDropdown } from "cockpit-components-dropdown";
40
41 import { TimerDialog } from "./timer-dialog.jsx";
42 import { from_boot_usec, from_on_calendar } from "./timer-dialog-helpers.js";
43
44 const _ = cockpit.gettext;
45 const METRICS_POLL_DELAY = 30000; // 30s
46
47 // This marker comment is inserted at the beginning of unit files created by Cockpit
48 export const CockpitManagedMarker = "# Managed by Cockpit.\n";
49
50 /*
51 * React template for showing basic dialog for confirming action
52 * Required props:
53 * - title
54 * Title of the dialog
55 * - message
56 * Message in the dialog
57 * - close
58 * Action to be executed when Cancel button is selected.
59 * Optional props:
60 * - confirmText
61 * Text of the button for confirming the action
62 * - confirmAction
63 * Action to be executed when the action is confirmed
64 */
65 const ServiceConfirmDialog = ({ id, title, message, confirmText, confirmAction }) => {
66 const Dialogs = useDialogs();
67 return (
68 <Modal id={id} isOpen
69 position="top" variant="medium"
70 onClose={Dialogs.close}>
71 <ModalHeader title={title} />
72 <ModalBody>
73 {message}
74 </ModalBody>
75 <ModalFooter>
76 { confirmText && confirmAction &&
77 <Button variant='danger' onClick={confirmAction}>
78 {confirmText}
79 </Button>
80 }
81 <Button variant='link' className='btn-cancel' onClick={Dialogs.close}>
82 { _("Cancel") }
83 </Button>
84 </ModalFooter>
85 </Modal>
86 );
87 };
88
89 /*
90 * React template for showing possible service action (in a kebab menu)
91 * Required props:
92 * - masked
93 * Unit is masked
94 * - active
95 * Unit is active (running)
96 * - failed
97 * Unit has failed
98 * - isPinned
99 * Unit is pinned
100 * - canReload
101 * Unit can be reloaded
102 * - actionCallback
103 * Method for calling unit methods like `UnitStart`
104 * - fileActionCallback
105 * Method for calling unit file methods like `EnableUnitFiles`
106 * - deleteActionCallback
107 * Method for calling deleting the systemd unit
108 * - pinUnitCallback
109 * Method to pin unit
110 * - disabled
111 * Button is disabled
112 */
113 const ServiceActions = ({ masked, active, failed, canReload, actionCallback, editActionCallback, deleteActionCallback, fileActionCallback, disabled, isPinned, pinUnitCallback }) => {
114 const Dialogs = useDialogs();
115
116 const actions = [];
117
118 // If masked, only show unmasking and nothing else
119 if (masked) {
120 actions.push(
121 <DropdownItem key="unmask" onClick={() => fileActionCallback("UnmaskUnitFiles", undefined)}>{ _("Allow running (unmask)") }</DropdownItem>
122 );
123 } else { // All cases when not masked
124 if (active) {
125 if (canReload) {
126 actions.push(
127 <DropdownItem key="reload" onClick={() => actionCallback("ReloadUnit")}>{ _("Reload") }</DropdownItem>
128 );
129 }
130 actions.push(
131 <DropdownItem key="restart" onClick={() => actionCallback("RestartUnit")}>{ _("Restart") }</DropdownItem>
132 );
133 actions.push(
134 <DropdownItem key="stop" onClick={() => actionCallback("StopUnit")}>{ _("Stop") }</DropdownItem>,
135 );
136 } else {
137 actions.push(
138 <DropdownItem key="start" onClick={() => actionCallback("StartUnit")}>{ _("Start") }</DropdownItem>
139 );
140 }
141
142 if (editActionCallback || deleteActionCallback) {
143 actions.push(<Divider key="modify-unit-divider" />);
144 }
145
146 if (editActionCallback) {
147 actions.push(
148 <DropdownItem key="edit" onClick={() => editActionCallback()}>{_("Edit")}</DropdownItem>
149 );
150 }
151
152 if (deleteActionCallback) {
153 actions.push(
154 <DropdownItem key="delete" className="pf-m-danger"
155 onClick={() => deleteActionCallback()}>{_("Delete")}</DropdownItem>
156 );
157 }
158
159 if (actions.length > 0) {
160 actions.push(
161 <Divider key="divider" />
162 );
163 }
164
165 if (failed)
166 actions.push(
167 <DropdownItem key="reset" onClick={() => actionCallback("ResetFailedUnit", []) }>{ _("Clear 'Failed to start'") }</DropdownItem>
168 );
169
170 const confirm = () => {
171 Dialogs.show(<ServiceConfirmDialog id="mask-service"
172 title={ _("Mask service") }
173 message={ _("Masking service prevents all dependent units from running. This can have bigger impact than anticipated. Please confirm that you want to mask this unit.")}
174 confirmText={ _("Mask service") }
175 confirmAction={() => {
176 fileActionCallback("MaskUnitFiles", false);
177 if (failed)
178 actionCallback("ResetFailedUnit", []);
179 Dialogs.close();
180 }} />);
181 };
182
183 actions.push(
184 <DropdownItem key="mask" onClick={confirm}>{ _("Disallow running (mask)") }</DropdownItem>
185 );
186
187 actions.push(<Divider key="pin-divider" />);
188 actions.push(
189 <DropdownItem key="pin" onClick={() => pinUnitCallback() }>{isPinned ? _("Unpin unit") : _("Pin unit")}</DropdownItem>
190 );
191 }
192
193 return (
194 <KebabDropdown id="service-actions" dropdownItems={actions} isDisabled={disabled} title={ _("Additional actions") } />
195 );
196 };
197
198 /*
199 * React template for a service details
200 * Shows current status and information about the service.
201 * Enables user to control this unit like starting, enabling, etc. the service.
202 * Required props:
203 * - unit
204 * as returned from systemd org.freedesktop.systemd1.{Unit,Socket}
205 * D-Bus interface, but with unwrapped variants, and with additional "path"
206 * property and addTimerProperties()
207 * - permitted
208 * True if user can control this unit
209 * - systemdManager
210 * Callback for displaying errors
211 * - isValid
212 * Method for finding if unit is valid
213 */
214 export class ServiceDetails extends React.Component {
215 static contextType = DialogsContext;
216
217 constructor(props) {
218 super(props);
219
220 this.state = {
221 waitsAction: false,
222 waitsFileAction: false,
223 unit_properties: {},
224 showDeleteDialog: false,
225 unitPaths: [],
226 cockpitManaged: false,
227 isPinned: this.props.pinnedUnits.includes(this.props.unit.Id),
228 };
229
230 this.onOnOffSwitch = this.onOnOffSwitch.bind(this);
231 this.unitAction = this.unitAction.bind(this);
232 this.unitFileAction = this.unitFileAction.bind(this);
233 this.editTimerAction = this.editTimerAction.bind(this);
234 this.deleteAction = this.deleteAction.bind(this);
235 this.deleteTimer = this.deleteTimer.bind(this);
236 this.pinUnit = this.pinUnit.bind(this);
237
238 this.unitType = props.unit.Id.split('.').slice(-1)[0];
239 this.unitTypeCapitalized = this.unitType.charAt(0).toUpperCase() + this.unitType.slice(1);
240 this.doMemoryCurrentPolling = this.doMemoryCurrentPolling.bind(this);
241
242 // MemoryCurrent property does not emit a changed signal - do polling for this property
243 if (props.unit.ActiveState == "active") {
244 this.doMemoryCurrentPolling();
245 this.interval = setInterval(this.doMemoryCurrentPolling, METRICS_POLL_DELAY);
246 }
247 }
248
249 componentDidMount() {
250 if (this.props.unit.FragmentPath?.startsWith("/etc/systemd")) {
251 cockpit.file(this.props.unit.FragmentPath)
252 .read()
253 .then(content => {
254 if (content?.startsWith(CockpitManagedMarker)) {
255 this.setState({ cockpitManaged: true });
256 }
257 });
258 }
259 }
260
261 componentDidUpdate(prevProps) {
262 // If unit became active start property polling and if got inactive stop
263 if (this.props.unit.ActiveState === 'active' && !this.interval) {
264 this.doMemoryCurrentPolling();
265 this.interval = setInterval(this.doMemoryCurrentPolling, METRICS_POLL_DELAY);
266 }
267 if (this.props.unit.ActiveState === 'inactive' && this.interval) {
268 this.doMemoryCurrentPolling();
269 clearInterval(this.interval);
270 }
271 }
272
273 componentWillUnmount() {
274 if (this.interval)
275 clearInterval(this.interval);
276 }
277
278 static getDerivedStateFromProps(nextProps, prevState) {
279 return {
280 waitsAction: nextProps.loadingUnits,
281 waitsFileAction: nextProps.loadingUnits,
282 };
283 }
284
285 show_note(note) {
286 const Dialogs = this.context;
287 Dialogs.show(<ServiceConfirmDialog title={_("Note")} message={note} />);
288 }
289
290 show_error(error) {
291 const Dialogs = this.context;
292 Dialogs.show(<ServiceConfirmDialog title={_("Error")} message={error} />);
293 }
294
295 doMemoryCurrentPolling() {
296 systemd_client[this.props.owner].call(this.props.unit.path,
297 "org.freedesktop.DBus.Properties", "Get",
298 ["org.freedesktop.systemd1." + this.unitTypeCapitalized, 'MemoryCurrent'])
299 .then(result => {
300 this.addUnitProperties(
301 "MemoryCurrent",
302 result[0] && result[0].v > 0 && result[0].v < MAX_UINT64 ? result[0].v : null,
303 );
304 }, ex => console.log(ex.message));
305 }
306
307 addUnitProperties(prop, value) {
308 if (prop == "MemoryCurrent" && this.state.unit_properties.MemoryCurrent !== value)
309 this.setState(prevState => ({ unit_properties: { ...prevState.unit_properties, [prop]: value } }));
310 }
311
312 onOnOffSwitch() {
313 if (this.props.unit.UnitFileState === "enabled") {
314 let promise;
315 if (this.props.unit.ActiveState === "active" || this.props.unit.ActiveState === "activating")
316 promise = this.unitAction("StopUnit");
317 else if (this.props.unit.ActiveState === "failed")
318 promise = this.unitAction("ResetFailedUnit", []);
319 else
320 promise = Promise.resolve();
321
322 promise.then(() => this.unitFileAction("DisableUnitFiles", undefined));
323 } else {
324 this.unitFileAction("EnableUnitFiles", false)
325 .then(() => {
326 if (this.props.unit.ActiveState !== "active" && this.props.unit.ActiveState !== "activating")
327 this.unitAction("StartUnit");
328 });
329 }
330 }
331
332 unitAction(method, extra_args, catchExc = true) {
333 if (extra_args === undefined)
334 extra_args = ["fail"];
335 this.setState({ waitsAction: true });
336 const promise = systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, method, [this.props.unit.Names[0]].concat(extra_args));
337 if (catchExc) {
338 return promise.catch(error => {
339 this.show_error(error.toString());
340 this.setState({ waitsAction: false });
341 });
342 } else {
343 return promise;
344 }
345 }
346
347 pinUnit() {
348 const newPinned = this.state.isPinned
349 ? this.props.pinnedUnits.filter(unitId => unitId != this.props.unit.Id)
350 : [...this.props.pinnedUnits, this.props.unit.Id];
351
352 localStorage.setItem('systemd:pinnedUnits', JSON.stringify(newPinned));
353 this.setState(prevState => ({ isPinned: !prevState.isPinned }));
354 dispatchEvent(new Event('storage'));
355 }
356
357 unitFileAction(method, force, catchExc = true) {
358 this.setState({ waitsFileAction: true });
359 const args = [[this.props.unit.Names[0]], false];
360 if (force !== undefined)
361 args.push(force == "true");
362 const promise = systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, method, args)
363 .then(([results]) => {
364 if (results.length == 2 && !results[0])
365 this.show_note(_("This unit is not designed to be enabled explicitly."));
366 /* Executing daemon reload after file operations is necessary -
367 * see https://github.com/systemd/systemd/blob/main/src/systemctl/systemctl.c [enable_unit function]
368 */
369 return systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "Reload", null);
370 });
371 if (catchExc) {
372 return promise.catch(error => {
373 this.show_error(error.toString());
374 this.setState({ waitsFileAction: false });
375 });
376 } else {
377 return promise;
378 }
379 }
380
381 editTimerAction() {
382 async function getCommand(bus, serviceUnitName) {
383 const serviceDbusPath = await bus.call(s_bus.O_MANAGER, s_bus.I_MANAGER, "LoadUnit", [serviceUnitName]);
384 const serviceProperties = await bus.call(serviceDbusPath[0], s_bus.I_PROPS, "GetAll", [s_bus.I_SERVICE]);
385 const exec = serviceProperties[0].ExecStart.v;
386
387 // ensure there is exactly one ExecStart= in the unit file that matches "/bin/sh -c CMD"
388
389 if (exec.length !== 1) {
390 console.warn(`${exec.length} ExecStart= entries were found for ${serviceUnitName} instead of 1`);
391 return null;
392 }
393
394 const [cmd, args] = exec[0];
395 if (cmd !== "/bin/sh" || args.length !== 3 || args[1] != "-c") {
396 console.warn(`ExecStart= entry is not of the form "/bin/sh -c CMD"`);
397 return null;
398 }
399
400 return args[2];
401 }
402
403 const Dialogs = this.context;
404
405 const timerName = this.props.unit.Id.slice(0, this.props.unit.Id.lastIndexOf("."));
406 const serviceUnitName = timerName + ".service"; // timers created with cockpit only trigger one service
407
408 const timerSettings = {
409 name: timerName,
410 description: this.props.unit.Description
411 };
412
413 let conditions = null;
414 if (this.props.unit.TimersMonotonic.length > 0) {
415 conditions = from_boot_usec(this.props.unit.TimersMonotonic[0][1]);
416 } else if (this.props.unit.TimersCalendar.length > 0) {
417 conditions = from_on_calendar(this.props.unit.TimersCalendar.map(item => item[1]));
418 }
419
420 getCommand(systemd_client[this.props.owner], serviceUnitName).then(command => {
421 const timer = { ...timerSettings, ...conditions, command };
422 Dialogs.show(<TimerDialog owner={this.props.owner} timer={timer} />);
423 });
424 }
425
426 deleteAction() {
427 this.getUnitPaths().then(unitPaths => {
428 this.setState({ showDeleteDialog: true, unitPaths });
429 });
430 }
431
432 async getUnitPaths() {
433 const paths = [this.props.unit.FragmentPath];
434
435 await Promise.all(this.props.unit.Triggers.map(async trigger => {
436 // Getting dbus properties from a non-loaded unit is not possible so resort to systemctl show
437 const unitPath = await cockpit.spawn(["systemctl", "show", "--value",
438 "--property", "FragmentPath", trigger]);
439 paths.push(unitPath.trim());
440 })).catch(err => console.error("failed to look up unit details:", err.toString()));
441
442 return paths;
443 }
444
445 deleteTimer() {
446 // Stop timer so we don't get race conditions when the unit is gone.
447 if (this.interval) {
448 clearInterval(this.interval);
449 this.interval = null;
450 }
451
452 const promises = [];
453 if (this.props.unit.ActiveState === "active" || this.props.unit.ActiveState === "activating")
454 promises.push(this.unitAction("StopUnit", undefined, false));
455 if (this.props.unit.ActiveState === "failed")
456 promises.push(this.unitAction("ResetFailedUnit", undefined, false));
457 if (this.props.unit.UnitFileState === "enabled")
458 promises.push(this.unitFileAction("DisableUnitFiles", undefined, false));
459
460 return Promise.all(promises).then(() => {
461 const deletions = this.state.unitPaths.filter(path => path.startsWith("/etc/systemd/system"))
462 .map(path => cockpit.file(path, { superuser: "require" }).replace(null));
463
464 // Reload after unit/timer removal
465 return Promise.all(deletions).then(() =>
466 systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "Reload", null)
467 .then(() => cockpit.jump("/system/services#/?type=timer"))
468 );
469 });
470 }
471
472 render() {
473 const active = this.props.unit.ActiveState === "active" || this.props.unit.ActiveState === "activating";
474 const enabled = this.props.unit.UnitFileState === "enabled";
475 const isStatic = this.props.unit.UnitFileState !== "disabled" && !enabled;
476 const failed = this.props.unit.ActiveState === "failed";
477 const masked = this.props.unit.LoadState === "masked";
478 const unit = this.state.unit_properties;
479 const showAction = this.props.permitted || this.props.owner == "user";
480 const isCustom = this.props.unit.FragmentPath.startsWith("/etc/systemd/system") && !masked;
481 const isTimer = (this.unitType === "timer");
482 const isQuadlet = this.props.unit.SourcePath?.includes("/containers/systemd/");
483
484 let status = [];
485
486 if (masked) {
487 status.push(
488 <div key="masked" className="status-masked">
489 <Icon>
490 <BanIcon className="status-icon" />
491 </Icon>
492 <span className="status">{ _("Masked") }</span>
493 <span className="side-note font-xs">{ _("Forbidden from running") }</span>
494 </div>
495 );
496 }
497
498 if (!enabled && !active && !masked && !isStatic) {
499 status.push(
500 <div key="disabled" className="status-disabled">
501 <Icon>
502 <OffIcon className="status-icon" />
503 </Icon>
504 <span className="status">{ _("Disabled") }</span>
505 </div>
506 );
507 }
508
509 if (failed) {
510 status.push(
511 <div key="failed" className="status-failed">
512 <Icon status="danger">
513 <ErrorCircleOIcon className="status-icon" />
514 </Icon>
515 <span className="status">{ _("Failed to start") }</span>
516 { showAction &&
517 <Button variant="secondary" className="action-button" onClick={() => this.unitAction("StartUnit") }>{ _("Start service") }</Button>
518 }
519 </div>
520 );
521 }
522
523 if (!status.length) {
524 if (active) {
525 status.push(
526 <div key="running" className="status-running">
527 <Icon status="success">
528 <OnRunningIcon className="status-icon" />
529 </Icon>
530 <span className="status">{ _("Running") }</span>
531 <span className="side-note font-xs">{ _("Active since ") + timeformat.dateTime(this.props.unit.ActiveEnterTimestamp / 1000) }</span>
532 </div>
533 );
534 } else {
535 status.push(
536 <div key="stopped" className="status-stopped">
537 <Icon>
538 <OffIcon className="status-icon" />
539 </Icon>
540 <span className="status">{ _("Not running") }</span>
541 </div>
542 );
543 }
544 }
545
546 if (isStatic && !masked) {
547 status.unshift(
548 <div key="static" className="status-static">
549 <Icon>
550 <AsleepIcon className="status-icon" />
551 </Icon>
552 <span className="status">{ _("Static") }</span>
553 { this.props.unit.WantedBy && this.props.unit.WantedBy.length > 0 &&
554 <>
555 <span className="side-note font-xs">{ _("Required by ") }</span>
556 <ul className="comma-list">
557 {this.props.unit.WantedBy.map(unit => <li className="font-xs" key={unit}><a href={"#/" + unit}>{unit}</a></li>)}
558 </ul>
559 </>
560 }
561 </div>
562 );
563 }
564
565 if (!showAction && this.props.owner !== 'user') {
566 status.unshift(
567 <div key="readonly" className="status-readonly">
568 <Icon>
569 <UserIcon className="status-icon" />
570 </Icon>
571 <span className="status">{ _("Read-only") }</span>
572 <span className="side-note font-xs">{ _("Requires administration access to edit") }</span>
573 </div>
574 );
575 }
576
577 if (enabled) {
578 status.push(
579 <div key="enabled" className="status-enabled">
580 <Icon status="success">
581 <OkIcon className="status-icon" />
582 </Icon>
583 <span className="status">{ _("Automatically starts") }</span>
584 </div>
585 );
586 }
587
588 if (this.props.unit.NextRunTime || this.props.unit.LastTriggerTime) {
589 status.push(
590 <div className="service-unit-triggers" key="triggers">
591 {this.props.unit.NextRunTime && <div className="service-unit-next-trigger">{cockpit.format("Next run: $0", this.props.unit.NextRunTime)}</div>}
592 {this.props.unit.LastTriggerTime && <div className="service-unit-last-trigger">{cockpit.format("Last trigger: $0", this.props.unit.LastTriggerTime)}</div>}
593 </div>
594 );
595 }
596
597 /* If there is some ongoing action just show spinner */
598 if (this.state.waitsAction || this.state.waitsFileAction) {
599 status = [
600 <div key="updating" className="status-updating">
601 <Icon>
602 <Spinner size="md" className="status-icon" />
603 </Icon>
604 <span className="status">{ _("Updating status...") }</span>
605 </div>
606 ];
607 }
608
609 const tooltipMessage = enabled ? _("Stop and disable") : _("Start and enable");
610 const hasLoadError = this.props.unit.LoadState !== "loaded" && this.props.unit.LoadState !== "masked";
611
612 if (hasLoadError) {
613 const path = "/system/services" + (this.props.owner === "user" ? "#/?owner=user" : ""); // not-covered: OS error
614 const loadError = this.props.unit.LoadError ? this.props.unit.LoadError[1] : null; // not-covered: OS error
615 const title = loadError || _("Failed to load unit"); // not-covered: OS error
616
617 return <EmptyStatePanel
618 icon={ExclamationCircleIcon}
619 title={title}
620 paragraph={this.props.unitId}
621 action={_("View all services")}
622 actionVariant="link"
623 onAction={() => cockpit.jump(path, cockpit.transport.host)}
624 />;
625 }
626
627 // These are relevant for socket and timer activated services
628 const triggerRelationships = [
629 { Name: _("Triggers"), Units: this.props.unit.Triggers },
630 { Name: _("Triggered by"), Units: this.props.unit.TriggeredBy },
631 ];
632
633 const relationships = [
634 { Name: _("Requires"), Units: this.props.unit.Requires },
635 { Name: _("Requisite"), Units: this.props.unit.Requisite },
636 { Name: _("Wants"), Units: this.props.unit.Wants },
637 { Name: _("Binds to"), Units: this.props.unit.BindsTo },
638 { Name: _("Part of"), Units: this.props.unit.PartOf },
639 { Name: _("Required by"), Units: this.props.unit.RequiredBy },
640 { Name: _("Requisite of"), Units: this.props.unit.RequisiteOf },
641 { Name: _("Wanted by"), Units: this.props.unit.WantedBy },
642 { Name: _("Bound by"), Units: this.props.unit.BoundBy },
643 { Name: _("Consists of"), Units: this.props.unit.ConsistsOf },
644 { Name: _("Conflicts"), Units: this.props.unit.Conflicts },
645 { Name: _("Conflicted by"), Units: this.props.unit.ConflictedBy },
646 { Name: _("Before"), Units: this.props.unit.Before },
647 { Name: _("After"), Units: this.props.unit.After },
648 { Name: _("On failure"), Units: this.props.unit.OnFailure },
649 { Name: _("Propagates reload to"), Units: this.props.unit.PropagatesReloadTo },
650 { Name: _("Reload propagated from"), Units: this.props.unit.ReloadPropagatedFrom },
651 { Name: _("Joins namespace of"), Units: this.props.unit.JoinsNamespaceOf }
652 ];
653
654 const relationshipsToList = rels => {
655 return rels.filter(rel => rel.Units && rel.Units.length > 0)
656 .map(rel =>
657 <DescriptionListGroup key={rel.Name}>
658 <DescriptionListTerm>{rel.Name}</DescriptionListTerm>
659 <DescriptionListDescription id={rel.Name.split(" ").join("")}>
660 <ul className="comma-list">
661 {rel.Units.map(unit => <li key={unit}><Button isInline variant="link" component="a" href={"#/" + unit + (this.props.owner === "user" ? "?owner=user" : "")} isDisabled={!this.props.isValid(unit)}>{unit}</Button></li>)}
662 </ul>
663 </DescriptionListDescription>
664 </DescriptionListGroup>
665 );
666 };
667
668 const triggerRelationshipsList = relationshipsToList(triggerRelationships);
669
670 const extraRelationshipsList = relationshipsToList(relationships);
671
672 const conditions = this.props.unit.Conditions;
673 const notMetConditions = [];
674 if (conditions)
675 conditions.forEach(condition => {
676 if (condition[4] < 0)
677 notMetConditions.push(cockpit.format(_("Condition $0=$1 was not met"), condition[0], condition[3]));
678 });
679
680 return (
681 <Card isPlain id="service-details-unit" className="ct-card">
682 { this.state.showDeleteDialog &&
683 <DeleteModal
684 name={this.props.unit.Description}
685 handleCancel={() => this.setState({ showDeleteDialog: false })}
686 handleDelete={this.deleteTimer}
687 reason={<Flex>
688 <p>{_("Deletion will remove the following files:")}</p>
689 <List>
690 {this.state.unitPaths.map(item => <ListItem key={item}>{item}</ListItem>)}
691 </List>
692 </Flex>
693 }
694 />
695 }
696 <CardHeader>
697 <Flex className="service-top-panel" spaceItems={{ default: 'spaceItemsMd' }} alignItems={{ default: 'alignItemsCenter' }}>
698 <CardTitle component="h2" className="service-name">{this.props.unit.Description}</CardTitle>
699 {this.state.isPinned &&
700 <Tooltip content={_("Pinned unit")}>
701 <ThumbtackIcon className='service-thumbtack-icon' />
702 </Tooltip>}
703 { showAction &&
704 <>
705 { !masked && !isStatic &&
706 <Tooltip id="switch-unit-state" content={tooltipMessage} position={TooltipPosition.right}>
707 <Switch isChecked={enabled}
708 aria-label={tooltipMessage}
709 isDisabled={this.state.waitsAction || this.state.waitsFileAction}
710 onChange={this.onOnOffSwitch} />
711 </Tooltip>
712 }
713 <ServiceActions { ...{ active, failed, enabled, masked } } canReload={this.props.unit.CanReload}
714 actionCallback={this.unitAction} fileActionCallback={this.unitFileAction}
715 editActionCallback={isCustom && isTimer && this.state.cockpitManaged ? this.editTimerAction : null}
716 deleteActionCallback={isCustom && isTimer ? this.deleteAction : null}
717 disabled={this.state.waitsAction || this.state.waitsFileAction}
718 isPinned={this.state.isPinned} pinUnitCallback={this.pinUnit} />
719 </>
720 }
721 </Flex>
722 </CardHeader>
723 <CardBody>
724 <Stack hasGutter>
725 <DescriptionList isHorizontal>
726 <DescriptionListGroup>
727 <DescriptionListTerm>{ _("Status") }</DescriptionListTerm>
728 <DescriptionListDescription id="statuses">
729 { status }
730 </DescriptionListDescription>
731 </DescriptionListGroup>
732 <DescriptionListGroup>
733 <DescriptionListTerm>{ _("Path") }</DescriptionListTerm>
734 <DescriptionListDescription id="path">{this.props.unit.FragmentPath}</DescriptionListDescription>
735 </DescriptionListGroup>
736 {unit.MemoryCurrent
737 ? <DescriptionListGroup>
738 <DescriptionListTerm>{ _("Memory") }</DescriptionListTerm>
739 <DescriptionListDescription id="memory">{cockpit.format_bytes(unit.MemoryCurrent)}</DescriptionListDescription>
740 </DescriptionListGroup>
741 : null}
742 {this.props.unit.Listen && this.props.unit.Listen.length && <DescriptionListGroup>
743 <DescriptionListTerm>{ _("Listen") }</DescriptionListTerm>
744 <DescriptionListDescription id="listen">
745 {cockpit.format("$0 ($1)", this.props.unit.Listen[0][1], this.props.unit.Listen[0][0])}
746 </DescriptionListDescription>
747 </DescriptionListGroup>}
748 {isQuadlet && cockpit.manifests?.podman?.capabilities?.includes("service-filtering") && <DescriptionListGroup>
749 <DescriptionListTerm>{ _("Container") }</DescriptionListTerm>
750 <DescriptionListDescription id="container">
751 <Button variant="link" isInline onClick={
752 () => cockpit.jump(`/podman#/?service=${this.props.unit.Id}`)}>
753 {_("View Podman container")}
754 </Button>
755 </DescriptionListDescription>
756 </DescriptionListGroup>}
757 { notMetConditions.length > 0 &&
758 <DescriptionListGroup>
759 <DescriptionListTerm className="failed">{ _("Condition failed") }</DescriptionListTerm>
760 <DescriptionListDescription id="condition">
761 {notMetConditions.map(cond => <div key={cond}>{cond}</div>)}
762 </DescriptionListDescription>
763 </DescriptionListGroup>
764 }
765 {triggerRelationshipsList}
766 </DescriptionList>
767 {extraRelationshipsList.length
768 ? <ExpandableSection id="service-details-show-relationships" toggleText={triggerRelationshipsList.length ? _("Show more relationships") : _("Show relationships")}>
769 <DescriptionList isHorizontal>
770 {extraRelationshipsList}
771 </DescriptionList>
772 </ExpandableSection>
773 : null}
774 </Stack>
775 </CardBody>
776 </Card>
777 );
778 }
779 }
780
781 const DeleteModal = ({ reason, name, handleCancel, handleDelete }) => {
782 const [inProgress, setInProgress] = useState(false);
783 const [dialogError, setDialogError] = useState(undefined);
784 return (
785 <Modal isOpen
786 position="top" variant="medium"
787 onClose={handleCancel}
788 >
789 <ModalHeader title={cockpit.format(_("Confirm deletion of $0"), name)}
790 titleIconVariant="warning"
791 />
792 <ModalBody>
793 <Stack hasGutter>
794 {dialogError && <ModalError dialogError={_("Timer deletion failed")} dialogErrorDetail={dialogError} />}
795 {reason}
796 </Stack>
797 </ModalBody>
798 <ModalFooter>
799 <Button id="delete-timer-modal-btn" variant="danger" isDisabled={inProgress} isLoading={inProgress}
800 onClick={() => { setInProgress(true); handleDelete().catch(exc => { setDialogError(exc.message); setInProgress(false) }) }}
801 >
802 {_("Delete")}
803 </Button>
804 <Button variant="link" isDisabled={inProgress} onClick={handleCancel}>{_("Cancel")}</Button>
805 </ModalFooter>
806 </Modal>
807 );
808 };