| 1 |
/* |
| 2 |
* Copyright (C) 2020 Red Hat, Inc. |
| 3 |
* SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
*/ |
| 5 |
|
| 6 |
import '../lib/patternfly/patternfly-6-cockpit.scss'; |
| 7 |
import 'polyfills'; // once per application |
| 8 |
import 'cockpit-dark-theme'; // once per page |
| 9 |
|
| 10 |
import React, { useState, useEffect } from "react"; |
| 11 |
import { createRoot } from 'react-dom/client'; |
| 12 |
import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js"; |
| 13 |
import { Page, PageSection, } from "@patternfly/react-core/dist/esm/components/Page/index.js"; |
| 14 |
import { Card, CardHeader } from "@patternfly/react-core/dist/esm/components/Card/index.js"; |
| 15 |
import { SearchInput } from "@patternfly/react-core/dist/esm/components/SearchInput/index.js"; |
| 16 |
import { ToggleGroup, ToggleGroupItem } from "@patternfly/react-core/dist/esm/components/ToggleGroup/index.js"; |
| 17 |
import { Toolbar, ToolbarContent, ToolbarFilter, ToolbarItem, ToolbarToggleGroup } from "@patternfly/react-core/dist/esm/components/Toolbar/index.js"; |
| 18 |
import { ExclamationCircleIcon, FilterIcon } from '@patternfly/react-icons'; |
| 19 |
|
| 20 |
import { CheckboxSelect } from "cockpit-components-checkbox-select"; |
| 21 |
import { EmptyStatePanel } from "cockpit-components-empty-state.jsx"; |
| 22 |
import { Service } from "./service.jsx"; |
| 23 |
import { ServiceTabs, service_tabs_suffixes } from "./service-tabs"; |
| 24 |
import { ServicesList } from "./services-list.jsx"; |
| 25 |
import { CreateTimerDialogButton } from "./timer-dialog.jsx"; |
| 26 |
import { page_status } from "notifications"; |
| 27 |
import * as python from "python"; |
| 28 |
import * as timeformat from "timeformat"; |
| 29 |
import cockpit from "cockpit"; |
| 30 |
import { superuser } from 'superuser'; |
| 31 |
import { useEvent, usePageLocation } from "hooks"; |
| 32 |
import { WithDialogs } from "dialogs.jsx"; |
| 33 |
|
| 34 |
import s_bus from "./busnames.js"; |
| 35 |
import "./services.scss"; |
| 36 |
|
| 37 |
const _ = cockpit.gettext; |
| 38 |
|
| 39 |
// As long as we have long-running superuser channels, we need to |
| 40 |
// reload the page when the access level changes. |
| 41 |
// |
| 42 |
superuser.reload_page_on_change(); |
| 43 |
|
| 44 |
export const systemd_client = { |
| 45 |
system: cockpit.dbus(s_bus.BUS_NAME, { bus: "system", superuser: "try" }), |
| 46 |
user: cockpit.dbus(s_bus.BUS_NAME, { bus: "session" }), |
| 47 |
}; |
| 48 |
const timedate_client = cockpit.dbus('org.freedesktop.timedate1'); |
| 49 |
export let clock_realtime_now = 0; // ms since epoch; call updateTime() before using |
| 50 |
let monotonic_timer_base = null; // µs |
| 51 |
|
| 52 |
export const MAX_UINT64 = 2 ** 64 - 1; |
| 53 |
|
| 54 |
function debug() { |
| 55 |
if (window.debugging == "all" || window.debugging?.includes("services")) |
| 56 |
console.debug.apply(console, arguments); |
| 57 |
} |
| 58 |
|
| 59 |
export function updateTime() { |
| 60 |
// To correctly interpret monotonic timers, we need to read CLOCK_MONOTONIC. This cannot be read with shell tools |
| 61 |
python.spawn("import time; print(int(time.clock_gettime(time.CLOCK_REALTIME) * 1000000), int(time.clock_gettime(time.CLOCK_MONOTONIC) * 1000000))", |
| 62 |
null, { err: "message" }) |
| 63 |
.then(output => { |
| 64 |
const [realtime_us, monotonic_us] = output.split(' ').map(t => parseInt(t)); |
| 65 |
clock_realtime_now = realtime_us / 1000; |
| 66 |
monotonic_timer_base = realtime_us - monotonic_us; |
| 67 |
debug("Read clocks with Python; realtime", clock_realtime_now, "monotonic base", monotonic_timer_base); |
| 68 |
}) |
| 69 |
.catch(ex => { |
| 70 |
/* If Python is not available, fall back to reading CLOCK_BOOTTIME from /proc/timer-list. |
| 71 |
* This is readable by root only */ |
| 72 |
console.log("Failed to read clocks with Python, using fallback:", ex.toString()); |
| 73 |
Promise.allSettled([ |
| 74 |
cockpit.spawn(["date", "+%s"]), |
| 75 |
cockpit.file("/proc/timer_list", { superuser: "try" }).read(), |
| 76 |
]) |
| 77 |
.then(([date_result, timer_list_result]) => { |
| 78 |
if (date_result.status === "fulfilled") { |
| 79 |
clock_realtime_now = parseInt(date_result.value) * 1000; |
| 80 |
} else { |
| 81 |
console.warn("Failed to read realtime clock:", date_result.reason.toString()); |
| 82 |
return; |
| 83 |
} |
| 84 |
|
| 85 |
// third line is "now at N nsecs" |
| 86 |
if (timer_list_result.status === "fulfilled") { |
| 87 |
const match = /now at (\d+) nsecs/.exec(timer_list_result.value); |
| 88 |
if (match) |
| 89 |
monotonic_timer_base = clock_realtime_now * 1000 - parseInt(match[1]) / 1000; |
| 90 |
|
| 91 |
debug("Read clocks with fallback; realtime", clock_realtime_now, "monotonic base", monotonic_timer_base); |
| 92 |
} else { |
| 93 |
console.log("Failed to read /proc/timer_list:", timer_list_result.reason.toString()); |
| 94 |
} |
| 95 |
}); |
| 96 |
}); |
| 97 |
} |
| 98 |
|
| 99 |
/* Notes about the systemd D-Bus API |
| 100 |
* |
| 101 |
* - Loading all units, fetching their properties, and listening to JobNew/JobRemoved is |
| 102 |
* expensive, so the services list does not do that. For 90% of what the list shows we |
| 103 |
* only need two calls: ListUnits() for enough information about all units which are in |
| 104 |
* systemd's brain; and ListUnitFiles() to add the inert ones (disabled, stopped, not a |
| 105 |
* dependency of anything). The only exception are timers, where we have to get the |
| 106 |
* properties of the Timers interface to show their last and next run. This information |
| 107 |
* is collected in listUnits(). |
| 108 |
* |
| 109 |
* - To keep up with changes, we listen to two signals: PropertiesChanged (which also gets |
| 110 |
* fired when a unit gets loaded) for run state chanes, and Reloading for file state |
| 111 |
* changes (like enabling/disabling). |
| 112 |
* |
| 113 |
* - When loading an unloaded unit, PropertiesChanged will be fired, but unfortunately in a |
| 114 |
* rather useless way: it does not contain all properties (thus it needs a GetAll), |
| 115 |
* and it usually happens for the Timer interface first (when we don't yet have an ID) and |
| 116 |
* for the Unit interface later; due to that, we track them in two separate dicts. |
| 117 |
* |
| 118 |
* - The unit details view does its own independent API communication and state |
| 119 |
* management. It needs to fetch/interpret a lot of unit properties which are not part |
| 120 |
* of ListUnits(), but it only needs to do that for a single unit. |
| 121 |
* |
| 122 |
* - ListUnitFiles will return unit files that are aliases for other unit files, but |
| 123 |
* ListUnits will not return aliases. |
| 124 |
* |
| 125 |
* - Methods like EnableUnitFiles only change the state of files on disk. A Reload is |
| 126 |
* necessary to update the state of loaded units. |
| 127 |
* |
| 128 |
* - The unit file state as returned by ListUnitFiles is not necessarily the same as the |
| 129 |
* UnitFileState property of a loaded unit. ListUnitFiles reflects the state of the |
| 130 |
* files on disk, while a loaded unit is only updated to that state via an explicit |
| 131 |
* Reload. Thus, be careful to only use the UnitFileState as returned by ListUnitFiles |
| 132 |
* for unloaded units. Loaded units should use the PropertiesChanged value to reflect |
| 133 |
* runtime reality. |
| 134 |
* |
| 135 |
* A few historical notes which don't apply to the current code, but could be useful in |
| 136 |
* the future: |
| 137 |
* |
| 138 |
* |
| 139 |
* - A unit that isn't currently loaded has no object path. If you need one, do |
| 140 |
* LoadUnit(); doing so will emit UnitNew. |
| 141 |
* |
| 142 |
* - One can use an object path for a unit that isn't currently loaded. Doing so will load |
| 143 |
* the unit (and emit UnitNew). |
| 144 |
* |
| 145 |
* - JobNew and JobRemoved signals don't include the object path of the affected units, |
| 146 |
* but we can get those by listening to UnitNew. |
| 147 |
* |
| 148 |
* - There might be UnitNew signals for units that are never returned by ListUnits or |
| 149 |
* ListUnitFiles. These are units that are mentioned in Requires, After, etc or that |
| 150 |
* people try to load via LoadUnit but that don't actually exist. |
| 151 |
* |
| 152 |
* - The "Names" property of a unit only includes those aliases that are currently loaded, |
| 153 |
* not all. To get all possible aliases, one needs to call ListUnitFiles and match |
| 154 |
* units via their object path. |
| 155 |
* |
| 156 |
* - The unit file state of a alias as returned by ListUnitFiles is always the same as the |
| 157 |
* unit file state of the primary unit file. |
| 158 |
* |
| 159 |
* - A Reload will emit UnitRemoved/UnitNew signals for all units, and no |
| 160 |
* PropertiesChanges signal for the properties that have changed because of the reload, |
| 161 |
* such as UnitFileState. |
| 162 |
*/ |
| 163 |
|
| 164 |
class ServicesPageBody extends React.Component { |
| 165 |
constructor(props) { |
| 166 |
super(props); |
| 167 |
this.state = { |
| 168 |
/* State related to the toolbar components */ |
| 169 |
isFullyLoaded: false, |
| 170 |
error: null, |
| 171 |
pinnedUnits: [], |
| 172 |
}; |
| 173 |
|
| 174 |
/* data storage |
| 175 |
* |
| 176 |
* do not keep as state, as that requires too much copying, and it's easy to miss updates due to setState() |
| 177 |
* coalescing; whenever these change, you need to force a state update to re-render |
| 178 |
*/ |
| 179 |
|
| 180 |
/* loaded units: ListUnits()/PropertiesChanged for Unit interface; object path → { |
| 181 |
Id, |
| 182 |
Description, LoadState, ActiveState, |
| 183 |
UnitFileState, // if unit has a file and got a PropertiesChanged |
| 184 |
} */ |
| 185 |
this.units = {}; |
| 186 |
// for <Service unitIsValid > |
| 187 |
this.knownIds = new Set(); |
| 188 |
|
| 189 |
// active timers: object path → { LastTriggerTime, NextRunTime } (formatted strings) |
| 190 |
// lazily initialized when actually showing the Timers tab |
| 191 |
this.timers = null; |
| 192 |
|
| 193 |
/* ListUnitFiles() result; updated with daemon reload |
| 194 |
name/id (e.g. foo.service) → { Id, UnitFileState, ActiveState ("inactive" or empty for aliases) } */ |
| 195 |
this.unit_files = {}; |
| 196 |
|
| 197 |
// other state which should not cause re-renders |
| 198 |
this.seenActiveStates = new Set(); |
| 199 |
this.seenUnitFileStates = new Set(); |
| 200 |
this.reloading = false; |
| 201 |
|
| 202 |
// Possible LoadState values: stub, loaded, not-found, bad-setting, error, merged, masked |
| 203 |
// See: typedef enum UnitLoadStateState https://github.com/systemd/systemd/blob/main/src/basic/unit-def.h |
| 204 |
this.loadState = { |
| 205 |
stub: _("Stub"), |
| 206 |
loaded: "", |
| 207 |
"not-found": _("Not found"), |
| 208 |
"bad-setting": _("Bad setting"), |
| 209 |
error: _("Error"), |
| 210 |
merged: _("Merged"), |
| 211 |
masked: "", // We present the masked from the unitFileState |
| 212 |
}; |
| 213 |
|
| 214 |
// Possible ActiveState values: active, reloading, inactive, failed, activating, deactivating, maintenance |
| 215 |
// See: typedef enum UnitActiveState https://github.com/systemd/systemd/blob/main/src/basic/unit-def.h |
| 216 |
this.activeState = { |
| 217 |
active: _("Running"), |
| 218 |
reloading: _("Reloading"), |
| 219 |
inactive: _("Not running"), |
| 220 |
failed: _("Failed to start"), |
| 221 |
activating: _("Running"), |
| 222 |
deactivating: _("Not running"), |
| 223 |
maintenance: _("Maintenance"), |
| 224 |
}; |
| 225 |
|
| 226 |
// Possible UnitFileState values: enabled, enabled-runtime, linked, linked-runtime, alias, masked, masked-runtime, static, disabled, invalid, indirect, generated, transient, bad |
| 227 |
// See: typedef enum UnitFileState https://github.com/systemd/systemd/blob/main/src/shared/unit-file.h |
| 228 |
this.unitFileState = { |
| 229 |
enabled: _("Enabled"), |
| 230 |
"enabled-runtime": _("Enabled"), |
| 231 |
disabled: _("Disabled"), |
| 232 |
linked: _("Linked"), |
| 233 |
"linked-runtime": _("Linked"), |
| 234 |
alias: _("Alias"), |
| 235 |
masked: _("Masked"), |
| 236 |
"masked-runtime": _("Masked"), |
| 237 |
static: _("Static"), |
| 238 |
invalid: _("Invalid"), |
| 239 |
indirect: _("Indirect"), |
| 240 |
generated: _("Generated"), |
| 241 |
transient: _("Transient"), |
| 242 |
bad: _("Bad"), |
| 243 |
}; |
| 244 |
|
| 245 |
this.listUnits = this.listUnits.bind(this); |
| 246 |
this.loadPinnedUnits = this.loadPinnedUnits.bind(this); |
| 247 |
this.onOptionsChanged = this.onOptionsChanged.bind(this); |
| 248 |
this.compareUnits = this.compareUnits.bind(this); |
| 249 |
this.addTimerPropertiesFull = this.addTimerPropertiesFull.bind(this); |
| 250 |
} |
| 251 |
|
| 252 |
onOptionsChanged(options) { |
| 253 |
const currentOptions = { ...cockpit.location.options, ...options }; |
| 254 |
|
| 255 |
if (!currentOptions.activestate || options.activestate == "[]") |
| 256 |
delete currentOptions.activestate; |
| 257 |
|
| 258 |
if (!currentOptions.filestate || options.filestate == "[]") |
| 259 |
delete currentOptions.filestate; |
| 260 |
|
| 261 |
if (!currentOptions.name) |
| 262 |
delete currentOptions.name; |
| 263 |
|
| 264 |
cockpit.location.replace(cockpit.location.path, currentOptions); |
| 265 |
} |
| 266 |
|
| 267 |
componentDidMount() { |
| 268 |
systemd_client[this.props.owner].wait(() => { |
| 269 |
this.systemd_subscription = systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "Subscribe", null) |
| 270 |
.finally(this.listUnits) |
| 271 |
.catch(error => { |
| 272 |
if (error.name != "org.freedesktop.systemd1.AlreadySubscribed" && |
| 273 |
error.name != "org.freedesktop.DBus.Error.FileExists") |
| 274 |
this.setState({ error: cockpit.format(_("Subscribing to systemd signals failed: $0"), error.toString()) }); |
| 275 |
}); |
| 276 |
}) |
| 277 |
.catch(ex => this.setState({ error: cockpit.format(_("Connecting to dbus failed: $0"), ex.toString()) })); |
| 278 |
|
| 279 |
cockpit.addEventListener("visibilitychange", () => { |
| 280 |
if (!cockpit.hidden) { |
| 281 |
debug("visibilitychange to visible; fully loaded", this.state.isFullyLoaded); |
| 282 |
/* If the page had only been fetched in the background we need to properly initialize the state now |
| 283 |
* else just trigger an re-render since we are receiving signals while running in the background and |
| 284 |
* we update the state but don't re-render |
| 285 |
*/ |
| 286 |
if (!this.state.isFullyLoaded) |
| 287 |
this.listUnits(); |
| 288 |
else |
| 289 |
this.setState({}); |
| 290 |
} else { |
| 291 |
debug("visibilitychange to hidden"); |
| 292 |
} |
| 293 |
}); |
| 294 |
|
| 295 |
/* Start listening to signals for updates |
| 296 |
* - when in the middle of reload mute all signals |
| 297 |
* - We don't need to listen to 'UnitFilesChanged' signal since every time we |
| 298 |
* perform some file operation we do call Reload which issues 'Reloading' signal |
| 299 |
*/ |
| 300 |
systemd_client[this.props.owner].subscribe({ |
| 301 |
interface: s_bus.I_PROPS, |
| 302 |
member: "PropertiesChanged" |
| 303 |
}, async (path, _iface, _signal, [iface, props]) => { |
| 304 |
if (this.props.isLoading || this.reloading) |
| 305 |
return; |
| 306 |
|
| 307 |
// ignore uninteresting unit types |
| 308 |
if (!this.isUnitHandled(path)) |
| 309 |
return; |
| 310 |
|
| 311 |
// ignore when timers did not yet get shown |
| 312 |
if (iface === s_bus.I_TIMER && this.timers !== null) { |
| 313 |
if (!this.timers[path]) |
| 314 |
this.timers[path] = {}; |
| 315 |
this.addTimerProperties(props, this.timers[path]); |
| 316 |
debug("timer PropertiesChanged on", path, JSON.stringify(this.timers[path])); |
| 317 |
return; |
| 318 |
} |
| 319 |
|
| 320 |
// ignore uninteresting interfaces |
| 321 |
if (iface !== s_bus.I_UNIT) |
| 322 |
return; |
| 323 |
|
| 324 |
let unit = this.units[path]; |
| 325 |
|
| 326 |
if (!unit) { |
| 327 |
// this happens when starting an unloaded unit; unfortunately Units props is very incomplete, so we need a GetAll |
| 328 |
debug("unit PropertiesChanged on previously unloaded unit", path); |
| 329 |
try { |
| 330 |
[props] = await systemd_client[this.props.owner].call(path, s_bus.I_PROPS, "GetAll", [s_bus.I_UNIT]); |
| 331 |
} catch (ex) { // not-covered: OS error |
| 332 |
console.warn("GetAll Unit for unknown unit", path, "failed:", ex.toString()); // not-covered: OS error |
| 333 |
return; // not-covered: OS error |
| 334 |
} |
| 335 |
unit = {}; |
| 336 |
this.units[path] = unit; |
| 337 |
} |
| 338 |
|
| 339 |
// unwrap variants |
| 340 |
for (const prop of ["ActiveState", "LoadState", "Description", "Id", "UnitFileState"]) { |
| 341 |
if (props[prop]) |
| 342 |
unit[prop] = props[prop].v; |
| 343 |
} |
| 344 |
this.knownIds.add(unit.Id); |
| 345 |
debug("unit PropertiesChanged on", path, "complete:", JSON.stringify(unit)); |
| 346 |
|
| 347 |
this.processFailedUnits(); |
| 348 |
this.setState({ }); |
| 349 |
}); |
| 350 |
|
| 351 |
// handle transient units |
| 352 |
systemd_client[this.props.owner].subscribe({ interface: s_bus.I_MANAGER, member: "UnitRemoved" }, (_path, _iface, _signal, [_id, objpath]) => { |
| 353 |
// during daemon reload we get tons of these, ignore |
| 354 |
if (this.reloading) |
| 355 |
return; |
| 356 |
|
| 357 |
if (this.units[objpath]?.UnitFileState === 'transient') { |
| 358 |
debug("UnitRemoved of transient", objpath); |
| 359 |
this.knownIds.delete(this.units[objpath]?.Id); |
| 360 |
delete this.units[objpath]; |
| 361 |
this.processFailedUnits(); |
| 362 |
this.setState({ }); |
| 363 |
} |
| 364 |
}); |
| 365 |
|
| 366 |
systemd_client[this.props.owner].subscribe({ interface: s_bus.I_MANAGER, member: "Reloading" }, (_path, _iface, _signal, [reloading]) => { |
| 367 |
this.reloading = reloading; |
| 368 |
debug("Reloading", reloading); |
| 369 |
if (!reloading && !this.props.isLoading) |
| 370 |
this.listUnits(); |
| 371 |
}); |
| 372 |
|
| 373 |
addEventListener('storage', this.loadPinnedUnits); |
| 374 |
this.loadPinnedUnits(); |
| 375 |
|
| 376 |
this.timedated_subscription = timedate_client.subscribe({ |
| 377 |
path_namespace: "/org/freedesktop/timedate1", |
| 378 |
interface: s_bus.I_PROPS, |
| 379 |
member: "PropertiesChanged" |
| 380 |
}, updateTime); |
| 381 |
updateTime(); |
| 382 |
} |
| 383 |
|
| 384 |
shouldComponentUpdate(nextProps, nextState) { |
| 385 |
if (cockpit.hidden) |
| 386 |
return false; |
| 387 |
|
| 388 |
return true; |
| 389 |
} |
| 390 |
|
| 391 |
loadPinnedUnits() { |
| 392 |
try { |
| 393 |
this.setState({ pinnedUnits: JSON.parse(localStorage.getItem('systemd:pinnedUnits')) || [] }); |
| 394 |
} catch (err) { |
| 395 |
console.warn("exception while parsing systemd:pinnedUnits", err); |
| 396 |
this.setState({ pinnedUnits: [] }); |
| 397 |
} |
| 398 |
} |
| 399 |
|
| 400 |
/** |
| 401 |
* Return if the unit ID or path specified by @name is handled |
| 402 |
*/ |
| 403 |
isUnitHandled(name) { |
| 404 |
return service_tabs_suffixes.some(suffix => name.endsWith(suffix)); |
| 405 |
} |
| 406 |
|
| 407 |
/* When the page is running in the background, fetch only information about failed units |
| 408 |
* in order to update the 'Page Status'. */ |
| 409 |
listFailedUnits() { |
| 410 |
return systemd_client[this.props.owner].call(s_bus.O_MANAGER, s_bus.I_MANAGER, "ListUnitsFiltered", [["failed"]]) |
| 411 |
.then(([failed]) => { |
| 412 |
const units = {}; |
| 413 |
failed.forEach(([ |
| 414 |
Id, Description, LoadState, ActiveState, _substate, _followUnit, ObjectPath, |
| 415 |
_is_job_queued, _job_type, _job_path |
| 416 |
]) => { |
| 417 |
if (!this.isUnitHandled(Id)) |
| 418 |
return; |
| 419 |
|
| 420 |
units[ObjectPath] = { Id, Description, LoadState, ActiveState }; |
| 421 |
}); |
| 422 |
|
| 423 |
this.units = units; |
| 424 |
this.processFailedUnits(); |
| 425 |
}) |
| 426 |
.catch(ex => console.warn('ListUnitsFiltered failed: ', ex.toString())); // not-covered: OS error |
| 427 |
} |
| 428 |
|
| 429 |
isTemplate(id) { |
| 430 |
const tp = id.indexOf("@"); |
| 431 |
const sp = id.lastIndexOf("."); |
| 432 |
return (tp != -1 && (tp + 1 == sp || tp + 1 == id.length)); |
| 433 |
} |
| 434 |
|
| 435 |
listUnits() { |
| 436 |
if (cockpit.hidden) |
| 437 |
return this.listFailedUnits(); |
| 438 |
|
| 439 |
// Reinitialize the state variables for the units |
| 440 |
this.props.setIsLoading(true); |
| 441 |
|
| 442 |
const dbus = systemd_client[this.props.owner]; |
| 443 |
const units = {}; |
| 444 |
|
| 445 |
Promise.all([ |
| 446 |
dbus.call(s_bus.O_MANAGER, s_bus.I_MANAGER, "ListUnits", null), |
| 447 |
dbus.call(s_bus.O_MANAGER, s_bus.I_MANAGER, "ListUnitFiles", null) |
| 448 |
]) |
| 449 |
.then(([[unitsResults], [unitFilesResults]]) => { |
| 450 |
this.knownIds = new Set(); |
| 451 |
|
| 452 |
// ListUnits is the primary source of information |
| 453 |
unitsResults.forEach(([ |
| 454 |
Id, Description, LoadState, ActiveState, _substate, _followUnit, ObjectPath, |
| 455 |
_is_job_queued, _job_type, _job_path |
| 456 |
]) => { |
| 457 |
if (!this.isUnitHandled(Id)) |
| 458 |
return; |
| 459 |
|
| 460 |
// We should ignore 'not-found' units when setting the seenActiveStates |
| 461 |
if (LoadState !== 'not-found') |
| 462 |
this.seenActiveStates.add(ActiveState); |
| 463 |
|
| 464 |
units[ObjectPath] = { Id, Description, LoadState, ActiveState }; |
| 465 |
this.knownIds.add(Id); |
| 466 |
}); |
| 467 |
|
| 468 |
// unloaded, but available unit files |
| 469 |
const unit_files = {}; |
| 470 |
unitFilesResults.forEach(([UnitFilePath, UnitFileState]) => { |
| 471 |
const Id = UnitFilePath.split('/').pop(); |
| 472 |
if (!this.isUnitHandled(Id) || this.isTemplate(Id)) |
| 473 |
return; |
| 474 |
|
| 475 |
this.seenUnitFileStates.add(UnitFileState); |
| 476 |
// there is not enough information to link this to the primary unit which declared the alias |
| 477 |
// name; that requires a LoadUnit() + Get("Names") + reverse lookup; the details page has the |
| 478 |
// correct information, so skip the status for aliases |
| 479 |
// for other units, we default to "inactive"; loaded units will override that |
| 480 |
const ActiveState = (UnitFileState === "alias") ? undefined : "inactive"; |
| 481 |
unit_files[Id] = { Id, UnitFileState, ActiveState }; |
| 482 |
}); |
| 483 |
|
| 484 |
this.units = units; |
| 485 |
this.unit_files = unit_files; |
| 486 |
this.processFailedUnits(); |
| 487 |
this.setState({ isFullyLoaded: true }); |
| 488 |
}) |
| 489 |
.catch(ex => this.setState({ error: cockpit.format(_("Listing units failed: $0"), ex.toString()) })) // not-covered: OS error |
| 490 |
.finally(() => this.props.setIsLoading(false)); |
| 491 |
} |
| 492 |
|
| 493 |
loadTimers() { |
| 494 |
const dbus = systemd_client[this.props.owner]; |
| 495 |
const promises = []; |
| 496 |
this.timers = {}; |
| 497 |
debug("Loading all timers"); |
| 498 |
|
| 499 |
Object.entries(this.units).forEach(([path, unit]) => { |
| 500 |
if (unit.Id.endsWith(".timer")) { |
| 501 |
promises.push(dbus.call(path, s_bus.I_PROPS, "GetAll", [s_bus.I_TIMER]) |
| 502 |
.then(([props]) => { |
| 503 |
this.timers[path] = {}; |
| 504 |
this.addTimerPropertiesFull(props, this.timers[path]); |
| 505 |
}) |
| 506 |
.catch(ex => console.warn("Loading timer information for", path, "failed:", ex.toString()))); // not-covered: OS error |
| 507 |
} |
| 508 |
}); |
| 509 |
Promise.allSettled(promises).then(() => this.setState({})); |
| 510 |
} |
| 511 |
|
| 512 |
/** |
| 513 |
* Sort units by alphabetically - failed units go on the top of the list |
| 514 |
*/ |
| 515 |
compareUnits(unit_a_t, unit_b_t) { |
| 516 |
const unit_a = unit_a_t[1]; |
| 517 |
const unit_b = unit_b_t[1]; |
| 518 |
const failed_a = unit_a.HasFailed ? 1 : 0; |
| 519 |
const failed_b = unit_b.HasFailed ? 1 : 0; |
| 520 |
const pinned_a = this.state.pinnedUnits.includes(unit_a.Id) ? 1 : 0; |
| 521 |
const pinned_b = this.state.pinnedUnits.includes(unit_b.Id) ? 1 : 0; |
| 522 |
|
| 523 |
if (!unit_a || !unit_b) |
| 524 |
return 0; |
| 525 |
|
| 526 |
if (failed_a != failed_b) |
| 527 |
return failed_b - failed_a; |
| 528 |
else if (pinned_a != pinned_b) |
| 529 |
return pinned_b - pinned_a; |
| 530 |
else |
| 531 |
return unit_a_t[0].localeCompare(unit_b_t[0]); |
| 532 |
} |
| 533 |
|
| 534 |
addTimerProperties(timer_props, unit) { |
| 535 |
const last_trigger_usec = timer_props.LastTriggerUSec.v; |
| 536 |
// systemd puts -1 into an unsigned int type for the various *USec* properties |
| 537 |
// JS rounds these to a float which is > MAX_UINT64, but the comparison works |
| 538 |
if (last_trigger_usec > 0 && last_trigger_usec < MAX_UINT64) |
| 539 |
unit.LastTriggerTime = timeformat.dateTime(last_trigger_usec / 1000); |
| 540 |
else |
| 541 |
unit.LastTriggerTime = _("unknown"); |
| 542 |
|
| 543 |
const next_realtime = timer_props.NextElapseUSecRealtime?.v; |
| 544 |
const next_monotonic = timer_props.NextElapseUSecMonotonic?.v; |
| 545 |
let next_run_time = null; |
| 546 |
if (next_realtime > 0 && next_realtime < MAX_UINT64) |
| 547 |
next_run_time = next_realtime; |
| 548 |
else if (next_monotonic > 0 && next_monotonic < MAX_UINT64 && monotonic_timer_base !== null) |
| 549 |
next_run_time = next_monotonic + monotonic_timer_base; |
| 550 |
|
| 551 |
unit.NextRunTime = next_run_time ? timeformat.dateTime(next_run_time / 1000) : _("unknown"); |
| 552 |
} |
| 553 |
|
| 554 |
addTimerPropertiesFull(timer_props, unit) { |
| 555 |
this.addTimerProperties(timer_props, unit); |
| 556 |
|
| 557 |
unit.TimersCalendar = timer_props.TimersCalendar.v; |
| 558 |
unit.TimersMonotonic = timer_props.TimersMonotonic.v; |
| 559 |
} |
| 560 |
|
| 561 |
/* Add some computed properties into a unit object - does not call setState */ |
| 562 |
updateComputedProperties(unit) { |
| 563 |
unit.HasFailed = unit.ActiveState == "failed" || ( |
| 564 |
unit.LoadState && unit.LoadState !== "loaded" && unit.LoadState !== "masked"); |
| 565 |
|
| 566 |
unit.CombinedState = this.activeState[unit.ActiveState] || unit.ActiveState; |
| 567 |
if (unit.LoadState && unit.LoadState !== "loaded" && unit.LoadState !== "masked") |
| 568 |
unit.CombinedState = cockpit.format("$0 ($1)", unit.CombinedState, this.loadState[unit.LoadState]); |
| 569 |
|
| 570 |
unit.AutomaticStartup = this.unitFileState[unit.UnitFileState] || unit.UnitFileState; |
| 571 |
|
| 572 |
unit.IsPinned = this.state.pinnedUnits.includes(unit.Id); |
| 573 |
} |
| 574 |
|
| 575 |
processFailedUnits() { |
| 576 |
const failed = new Set(); |
| 577 |
const tabErrors = { }; |
| 578 |
|
| 579 |
Object.values(this.units).forEach(u => { |
| 580 |
if (u.ActiveState == "failed" && u.LoadState != "not-found") { |
| 581 |
const suffix = u.Id.substring(u.Id.lastIndexOf('.') + 1); |
| 582 |
if (service_tabs_suffixes.includes(suffix)) { |
| 583 |
tabErrors[suffix] = true; |
| 584 |
failed.add(u.Id); |
| 585 |
} |
| 586 |
} |
| 587 |
}); |
| 588 |
this.props.setTabErrors(tabErrors); |
| 589 |
|
| 590 |
if (failed.size > 0) { |
| 591 |
page_status.set_own({ |
| 592 |
type: "error", |
| 593 |
title: cockpit.format(cockpit.ngettext("$0 service has failed", |
| 594 |
"$0 services have failed", |
| 595 |
failed.size), failed.size), |
| 596 |
details: [...failed] |
| 597 |
}); |
| 598 |
} else { |
| 599 |
page_status.set_own(null); |
| 600 |
} |
| 601 |
} |
| 602 |
|
| 603 |
// compute filtered and sorted list of [Id, unit] |
| 604 |
computeSelectedUnits() { |
| 605 |
const unitType = '.' + this.props.activeTab; |
| 606 |
const options = cockpit.location.options; |
| 607 |
const currentTextFilter = decodeURIComponent(options.name || '').toLowerCase(); |
| 608 |
const filters = { |
| 609 |
activeState: JSON.parse(options.activestate || '[]'), |
| 610 |
fileState: JSON.parse(options.filestate || '[]') |
| 611 |
}; |
| 612 |
const selectedUnits = []; |
| 613 |
const ids = new Set(); |
| 614 |
|
| 615 |
[...Object.entries(this.units), ...Object.entries(this.unit_files)].forEach(([idx, unit]) => { |
| 616 |
if (!unit.Id?.endsWith(unitType)) |
| 617 |
return; |
| 618 |
|
| 619 |
if (unit.LoadState === "not-found") |
| 620 |
return; |
| 621 |
|
| 622 |
// avoid showing unloaded units when there is a loaded one |
| 623 |
if (ids.has(unit.Id)) |
| 624 |
return; |
| 625 |
ids.add(unit.Id); |
| 626 |
|
| 627 |
const UnitFileState = unit.UnitFileState ?? this.unit_files[unit.Id]?.UnitFileState; |
| 628 |
|
| 629 |
if (currentTextFilter && !((unit.Description && unit.Description.toLowerCase().includes(currentTextFilter)) || |
| 630 |
unit.Id.toLowerCase().includes(currentTextFilter))) |
| 631 |
return; |
| 632 |
|
| 633 |
if (filters.fileState.length && this.unitFileState[UnitFileState] && |
| 634 |
!filters.fileState.includes(this.unitFileState[UnitFileState])) |
| 635 |
return; |
| 636 |
|
| 637 |
if (filters.activeState.length && this.activeState[unit.ActiveState] && |
| 638 |
!filters.activeState.includes(this.activeState[unit.ActiveState])) |
| 639 |
return; |
| 640 |
|
| 641 |
const augmentedUnit = { ...unit, UnitFileState, ...this.timers?.[idx] }; |
| 642 |
this.updateComputedProperties(augmentedUnit); |
| 643 |
selectedUnits.push([unit.Id, augmentedUnit]); |
| 644 |
}); |
| 645 |
|
| 646 |
selectedUnits.sort(this.compareUnits); |
| 647 |
|
| 648 |
// lazy-load timers |
| 649 |
if (this.props.activeTab === 'timer' && this.timers === null) |
| 650 |
this.loadTimers(); |
| 651 |
|
| 652 |
return selectedUnits; |
| 653 |
} |
| 654 |
|
| 655 |
render() { |
| 656 |
if (this.state.error) |
| 657 |
return <EmptyStatePanel title={_("Loading of units failed")} icon={ExclamationCircleIcon} paragraph={this.state.error} />; |
| 658 |
|
| 659 |
/* Navigation: unit details page with a path, service list without; |
| 660 |
* the details page does its own loading, we don't need to wait for isFullyLoaded */ |
| 661 |
const path = cockpit.location.path; |
| 662 |
if (path.length == 1) { |
| 663 |
const unit_id = path[0]; |
| 664 |
|
| 665 |
return <Service unitIsValid={unitId => this.unit_files[unitId] || this.knownIds.has(unitId) } |
| 666 |
owner={this.props.owner} |
| 667 |
key={unit_id} |
| 668 |
unitId={unit_id} |
| 669 |
dbusClient={systemd_client[this.props.owner]} |
| 670 |
addTimerProperties={this.addTimerPropertiesFull} |
| 671 |
pinnedUnits={this.state.pinnedUnits} |
| 672 |
/>; |
| 673 |
} |
| 674 |
|
| 675 |
if (!this.state.isFullyLoaded) |
| 676 |
return <EmptyStatePanel loading title={_("Loading...")} paragraph={_("Listing units")} />; |
| 677 |
|
| 678 |
const fileStateDropdownOptions = [ |
| 679 |
{ value: 'enabled', label: _("Enabled") }, |
| 680 |
{ value: 'disabled', label: _("Disabled") }, |
| 681 |
{ value: 'static', label: _("Static") }, |
| 682 |
]; |
| 683 |
this.seenUnitFileStates.forEach(unitFileState => { |
| 684 |
const baseState = unitFileState.split('-runtime')[0]; |
| 685 |
if (!['enabled', 'disabled', 'static'].includes(baseState)) { |
| 686 |
const label = this.unitFileState[unitFileState]; |
| 687 |
if (!fileStateDropdownOptions.some(o => o.label === label)) |
| 688 |
fileStateDropdownOptions.push({ value: baseState, label }); |
| 689 |
} |
| 690 |
}); |
| 691 |
const activeStateDropdownOptions = [ |
| 692 |
{ value: 'active', label: _("Running") }, |
| 693 |
{ value: 'inactive', label: _("Not running") }, |
| 694 |
]; |
| 695 |
this.seenActiveStates.forEach(activeState => { |
| 696 |
if (!['active', 'activating', 'inactive', 'deactivating'].includes(activeState)) { |
| 697 |
activeStateDropdownOptions.push({ value: activeState, label: this.activeState[activeState] }); |
| 698 |
} |
| 699 |
}); |
| 700 |
const activeTab = this.props.activeTab; |
| 701 |
|
| 702 |
const onClearAllFilters = () => { |
| 703 |
this.onOptionsChanged({ |
| 704 |
name: '', |
| 705 |
activestate: '[]', |
| 706 |
filestate: '[]', |
| 707 |
}); |
| 708 |
}; |
| 709 |
|
| 710 |
return ( |
| 711 |
<PageSection hasBodyWrapper={false}> |
| 712 |
<Card isPlain isCompact> |
| 713 |
<CardHeader id='services-card-header'> |
| 714 |
<ServicesPageFilters activeStateDropdownOptions={activeStateDropdownOptions} |
| 715 |
fileStateDropdownOptions={fileStateDropdownOptions} |
| 716 |
onClearAllFilters={onClearAllFilters} |
| 717 |
loadingUnits={this.props.isLoading} |
| 718 |
options={cockpit.location.options} |
| 719 |
onOptionsChanged={this.onOptionsChanged} |
| 720 |
/> |
| 721 |
</CardHeader> |
| 722 |
<ServicesList key={cockpit.format("$0-list", activeTab)} |
| 723 |
isTimer={activeTab == 'timer'} |
| 724 |
onClearAllFilters={onClearAllFilters} |
| 725 |
units={this.computeSelectedUnits()} /> |
| 726 |
</Card> |
| 727 |
</PageSection> |
| 728 |
); |
| 729 |
} |
| 730 |
} |
| 731 |
|
| 732 |
const ServicesPageFilters = ({ |
| 733 |
activeStateDropdownOptions, |
| 734 |
fileStateDropdownOptions, |
| 735 |
loadingUnits, |
| 736 |
options, |
| 737 |
onOptionsChanged, |
| 738 |
onClearAllFilters, |
| 739 |
}) => { |
| 740 |
const { activestate, filestate, name } = options; |
| 741 |
|
| 742 |
const currentTextFilter = decodeURIComponent(name || ""); |
| 743 |
const setCurrentTextFilter = val => { |
| 744 |
onOptionsChanged({ name: encodeURIComponent(val) }); |
| 745 |
}; |
| 746 |
|
| 747 |
const filters = { |
| 748 |
activeState: JSON.parse(activestate || '[]'), |
| 749 |
fileState: JSON.parse(filestate || '[]'), |
| 750 |
}; |
| 751 |
|
| 752 |
const setFilters = val => { |
| 753 |
onOptionsChanged({ |
| 754 |
activestate: JSON.stringify(val.activeState), |
| 755 |
filestate: JSON.stringify(val.fileState), |
| 756 |
}); |
| 757 |
}; |
| 758 |
|
| 759 |
const onSelect = (type, checked, selection) => { |
| 760 |
setFilters({ ...filters, [type]: checked ? [...filters[type], selection] : filters[type].filter(value => value !== selection) }); |
| 761 |
}; |
| 762 |
|
| 763 |
const onActiveStateSelect = (selection, checked) => { |
| 764 |
onSelect('activeState', checked, selection); |
| 765 |
}; |
| 766 |
|
| 767 |
const onFileStateSelect = (selection, checked) => { |
| 768 |
onSelect('fileState', checked, selection); |
| 769 |
}; |
| 770 |
|
| 771 |
const getFilterLabelKey = (typeLabel) => { |
| 772 |
if (typeLabel == 'Active state') |
| 773 |
return 'activeState'; |
| 774 |
else if (typeLabel == 'File state') |
| 775 |
return 'fileState'; |
| 776 |
}; |
| 777 |
|
| 778 |
const onDeleteChip = (typeLabel = '', id = '') => { |
| 779 |
const type = getFilterLabelKey(typeLabel); |
| 780 |
|
| 781 |
if (type) { |
| 782 |
setFilters({ ...filters, [type]: filters[type].filter(s => s !== id) }); |
| 783 |
} else { |
| 784 |
setFilters({ |
| 785 |
activeState: [], |
| 786 |
fileState: [] |
| 787 |
}); |
| 788 |
} |
| 789 |
}; |
| 790 |
|
| 791 |
const onDeleteChipGroup = (typeLabel) => { |
| 792 |
const type = getFilterLabelKey(typeLabel); |
| 793 |
|
| 794 |
if (type) |
| 795 |
setFilters({ ...filters, [type]: [] }); |
| 796 |
else |
| 797 |
setFilters({ |
| 798 |
activeState: [], |
| 799 |
fileState: [] |
| 800 |
}); |
| 801 |
}; |
| 802 |
|
| 803 |
const onTextFilterChanged = textFilter => { |
| 804 |
setCurrentTextFilter(textFilter); |
| 805 |
}; |
| 806 |
|
| 807 |
const toolbarItems = |
| 808 |
<ToolbarToggleGroup toggleIcon={<><span className="pf-v6-c-button__icon pf-m-start"><FilterIcon /></span>{_("Toggle filters")}</>} breakpoint="sm" |
| 809 |
variant="filter-group"> |
| 810 |
<ToolbarItem> |
| 811 |
<SearchInput id="services-text-filter" |
| 812 |
className="services-text-filter" |
| 813 |
placeholder={_("Filter by name or description")} |
| 814 |
value={currentTextFilter} |
| 815 |
onChange={(_, val) => onTextFilterChanged(val)} |
| 816 |
onClear={() => onTextFilterChanged('')} /> |
| 817 |
</ToolbarItem> |
| 818 |
<ToolbarFilter labels={filters.activeState} |
| 819 |
deleteLabel={onDeleteChip} |
| 820 |
deleteLabelGroup={onDeleteChipGroup} |
| 821 |
categoryName={_("Active state")}> |
| 822 |
<CheckboxSelect |
| 823 |
toggleProps={{ |
| 824 |
id: "services-dropdown-active-state", |
| 825 |
"aria-label": _("Active state") |
| 826 |
}} |
| 827 |
toggleContent={_("Active state")} |
| 828 |
onSelect={onActiveStateSelect} |
| 829 |
selected={filters.activeState} |
| 830 |
options={activeStateDropdownOptions.map(option => { |
| 831 |
return { |
| 832 |
value: option.label, // sic |
| 833 |
content: option.label, |
| 834 |
"data-label": option.label, |
| 835 |
}; |
| 836 |
})} /> |
| 837 |
</ToolbarFilter> |
| 838 |
<ToolbarFilter labels={filters.fileState} |
| 839 |
deleteLabel={onDeleteChip} |
| 840 |
deleteLabelGroup={onDeleteChipGroup} |
| 841 |
categoryName={_("File state")}> |
| 842 |
<CheckboxSelect |
| 843 |
toggleProps={{ |
| 844 |
id: "services-dropdown-file-state", |
| 845 |
"aria-label": _("File state") |
| 846 |
}} |
| 847 |
toggleContent={_("File state")} |
| 848 |
onSelect={onFileStateSelect} |
| 849 |
selected={filters.fileState} |
| 850 |
options={fileStateDropdownOptions.map(option => { |
| 851 |
return { |
| 852 |
value: option.label, // sic |
| 853 |
content: option.label, |
| 854 |
"data-label": option.label, |
| 855 |
}; |
| 856 |
})} /> |
| 857 |
</ToolbarFilter> |
| 858 |
</ToolbarToggleGroup>; |
| 859 |
|
| 860 |
return ( |
| 861 |
<Toolbar |
| 862 |
data-loading={loadingUnits} |
| 863 |
clearAllFilters={onClearAllFilters} |
| 864 |
className="pf-m-sticky-top ct-compact services-toolbar" |
| 865 |
id="services-toolbar" |
| 866 |
numberOfFiltersText={n => cockpit.format(_("$0 filters applied"), n)}> |
| 867 |
<ToolbarContent>{toolbarItems}</ToolbarContent> |
| 868 |
</Toolbar> |
| 869 |
); |
| 870 |
}; |
| 871 |
|
| 872 |
const ServicesPage = () => { |
| 873 |
const [tabErrors, setTabErrors] = useState({}); |
| 874 |
const [loggedUser, setLoggedUser] = useState(); |
| 875 |
const [isLoading, setIsLoading] = useState(false); |
| 876 |
|
| 877 |
useEffect(() => { |
| 878 |
cockpit.user() |
| 879 |
.then(user => setLoggedUser(user.name)) |
| 880 |
.catch(ex => console.warn(ex.message)); |
| 881 |
}, []); |
| 882 |
|
| 883 |
/* Listen for permission changes for "Create timer" button */ |
| 884 |
useEvent(superuser, "changed"); |
| 885 |
// trigger re-renders when location changes (e.g. through changing filters) |
| 886 |
usePageLocation(); |
| 887 |
|
| 888 |
const options = cockpit.location.options; |
| 889 |
const activeTab = options.type || 'service'; |
| 890 |
const owner = options.owner || 'system'; |
| 891 |
const setOwner = (owner) => cockpit.location.go(cockpit.location.path, { ...cockpit.location.options, owner }); |
| 892 |
|
| 893 |
if (owner !== 'system' && owner !== 'user') { |
| 894 |
console.warn("not a valid location: " + JSON.stringify(cockpit.location)); |
| 895 |
cockpit.location = ''; |
| 896 |
return; |
| 897 |
} |
| 898 |
|
| 899 |
return ( |
| 900 |
<WithDialogs> |
| 901 |
<Page className='pf-m-no-sidebar'> |
| 902 |
{cockpit.location.path.length == 0 && |
| 903 |
<PageSection hasBodyWrapper={false} className="services-header"> |
| 904 |
<Flex> |
| 905 |
<ServiceTabs activeTab={activeTab} |
| 906 |
tabErrors={tabErrors} |
| 907 |
onChange={activeTab => { |
| 908 |
cockpit.location.go(cockpit.location.path, { ...cockpit.location.options, type: activeTab }); |
| 909 |
}} /> |
| 910 |
<FlexItem align={{ default: 'alignRight' }}> |
| 911 |
{loggedUser && loggedUser !== 'root' && <ToggleGroup> |
| 912 |
<ToggleGroupItem isSelected={owner == "system"} |
| 913 |
buttonId="system" |
| 914 |
text={_("System")} |
| 915 |
onChange={() => setOwner("system")} /> |
| 916 |
<ToggleGroupItem isSelected={owner == "user"} |
| 917 |
buttonId="user" |
| 918 |
text={_("User")} |
| 919 |
onChange={() => setOwner("user")} /> |
| 920 |
</ToggleGroup>} |
| 921 |
</FlexItem> |
| 922 |
{activeTab == "timer" && owner == "system" && superuser.allowed && <CreateTimerDialogButton isLoading={isLoading} owner={owner} />} |
| 923 |
</Flex> |
| 924 |
</PageSection>} |
| 925 |
<ServicesPageBody |
| 926 |
key={owner} |
| 927 |
activeTab={activeTab} |
| 928 |
owner={owner} |
| 929 |
privileged={superuser.allowed} |
| 930 |
setTabErrors={setTabErrors} |
| 931 |
isLoading={isLoading} |
| 932 |
setIsLoading={setIsLoading} |
| 933 |
/> |
| 934 |
</Page> |
| 935 |
</WithDialogs> |
| 936 |
); |
| 937 |
}; |
| 938 |
|
| 939 |
function init() { |
| 940 |
const root = createRoot(document.getElementById('services')); |
| 941 |
root.render(<ServicesPage />); |
| 942 |
} |
| 943 |
|
| 944 |
document.addEventListener("DOMContentLoaded", init); |