/*
* Copyright (C) 2017 Red Hat, Inc.
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
import '../lib/patternfly/patternfly-6-cockpit.scss';
import 'polyfills'; // once per application
import 'cockpit-dark-theme'; // once per page
import cockpit from "cockpit";
import React from "react";
import { createRoot } from 'react-dom/client';
import { Badge } from "@patternfly/react-core/dist/esm/components/Badge/index.js";
import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
import { CodeBlock, CodeBlockCode } from "@patternfly/react-core/dist/esm/components/CodeBlock/index.js";
import { Gallery } from "@patternfly/react-core/dist/esm/layouts/Gallery/index.js";
import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
import { Tooltip } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
import { Card, CardBody, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
import { ExpandableSection } from "@patternfly/react-core/dist/esm/components/ExpandableSection/index.js";
import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
import { Grid, GridItem } from "@patternfly/react-core/dist/esm/layouts/Grid/index.js";
import { LabelGroup } from "@patternfly/react-core/dist/esm/components/Label/index.js";
import { Page, PageSection, } from "@patternfly/react-core/dist/esm/components/Page/index.js";
import { Progress, ProgressSize } from "@patternfly/react-core/dist/esm/components/Progress/index.js";
import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
import { Stack, StackItem } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
import { Content, ContentVariants } from "@patternfly/react-core/dist/esm/components/Content/index.js";
import {
BugIcon,
CheckIcon,
EnhancementIcon,
ExclamationCircleIcon,
ExclamationTriangleIcon,
RebootingIcon,
RedoIcon,
ProcessAutomationIcon,
SecurityIcon,
} from "@patternfly/react-icons";
import { TableText } from "@patternfly/react-table";
import { Remarkable } from "remarkable";
import { AutoUpdates, getBackend } from "./autoupdates.jsx";
import { KpatchSettings, KpatchStatus } from "./kpatch";
import { History, PackageList } from "./history";
import { RestartServicesDialog } from './restartservices-dialog';
import { TwoColumnContent, TwoColumnTitle } from "./two-column";
import { page_status } from "notifications";
import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
import { ListingTable } from 'cockpit-components-table.jsx';
import { ShutdownModal } from 'cockpit-components-shutdown.jsx';
import { WithDialogs } from "dialogs.jsx";
import { superuser } from 'superuser';
import * as PK from "packagekit.js";
import * as python from "python.js";
import * as timeformat from "timeformat";
import { debug, watchRedHatSubscription } from './utils';
import { read_os_release } from "os-release.js";
import callTracerScript from './callTracer.py';
import "./updates.scss";
import { Truncate } from '@patternfly/react-core/dist/esm/components/Truncate/index.js';
import { Severity } from '_internal/packagemanager-abstract';
import { getPackageManager } from 'packagemanager';
import { Icon } from '@patternfly/react-core/dist/esm/components/Icon/index.js';
const _ = cockpit.gettext;
// "available" heading is built dynamically
const STATE_HEADINGS = {};
const PK_STATUS_STRINGS = {};
const PK_STATUS_LOG_STRINGS = {};
const UPDATES = {
ALL: 0,
SECURITY: 1,
KPATCHES: 2,
};
function init() {
STATE_HEADINGS.loading = _("Loading available updates, please wait...");
STATE_HEADINGS.locked = _("Some other program is currently using the package manager, please wait...");
STATE_HEADINGS.refreshing = _("Refreshing package information");
STATE_HEADINGS.uptodate = _("System is up to date");
STATE_HEADINGS.applying = _("Applying updates");
STATE_HEADINGS.updateError = _("Applying updates failed");
STATE_HEADINGS.loadError = _("Loading available updates failed");
PK_STATUS_STRINGS[PK.Enum.STATUS_DOWNLOAD] = _("Downloading");
PK_STATUS_STRINGS[PK.Enum.STATUS_INSTALL] = _("Installing");
PK_STATUS_STRINGS[PK.Enum.STATUS_UPDATE] = _("Updating");
PK_STATUS_STRINGS[PK.Enum.STATUS_CLEANUP] = _("Setting up");
PK_STATUS_STRINGS[PK.Enum.STATUS_SIGCHECK] = _("Verifying");
PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_DOWNLOAD] = _("Downloaded");
PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_INSTALL] = _("Installed");
PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_UPDATE] = _("Updated");
PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_CLEANUP] = _("Set up");
PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_SIGCHECK] = _("Verified");
}
function deduplicate(list) {
return [...new Set(list)].sort();
}
// Insert comma strings in between elements of the list. Unlike list.join(",")
// this does not stringify the elements, which we need to keep as JSX objects.
function insertCommas(list) {
if (list.length <= 1)
return list;
return list.reduce((prev, cur) => [prev, ", ", cur]);
}
// Fedora changelogs are a wild mix of enumerations or not, headings, etc.
// Remove that formatting to avoid an untidy updates overview list
function cleanupChangelogLine(text) {
if (!text)
return text;
// enumerations
text = text.replace(/^[-* ]*/, "");
// headings
text = text.replace(/^=+\s+/, "").replace(/=+\s*$/, "");
return text.trim();
}
// Replace cockpit-wsinstance-https@[long_id] with a shorter string
function shortenCockpitWsInstance(list) {
return list.map(item => item.startsWith('cockpit-wsinstance-https') ? 'cockpit-wsinstance-https@.' : item);
}
function count_security_updates(updates) {
let num_security = 0;
for (const u of updates)
if (u.severity === Severity.CRITICAL)
++num_security;
return num_security;
}
function isKpatchPackage(name) {
return name.startsWith("kpatch-patch");
}
function count_kpatch_updates(updates) {
let num_kpatches = 0;
for (const u of updates)
if (isKpatchPackage(u.name))
++num_kpatches;
return num_kpatches;
}
function find_highest_severity(updates) {
let max = Severity.LOW;
for (const u of updates)
if (u.severity > max)
max = u.severity;
return max;
}
/**
* Get appropriate icon for an update severity
*
* info: An Severity level
* secSeverity: If given, further classification of the severity of Severity.CRITICAL from the vendor_urls;
* e. g. "critical", see https://access.redhat.com/security/updates/classification
* Returns: Icon JSX object
*
*/
function getSeverityIcon(info, secSeverity) {
let classes = "severity-icon";
if (secSeverity)
classes += " severity-" + secSeverity;
if (info == Severity.CRITICAL)
return ;
else if (info >= Severity.IMPORTANT)
return ;
else
return ;
}
function getPageStatusSeverityIcon(severity) {
if (severity == Severity.CRITICAL)
return "security";
else if (severity >= Severity.IMPORTANT)
return "bug";
else
return "enhancement";
}
function getSeverityURL(urls) {
if (urls.length === 0)
return null;
// in ascending severity
const knownLevels = ["low", "moderate", "important", "critical"];
let highestIndex = -1;
let highestURL = null;
// search URLs for highest valid severity; by all means we expect an update to have at most one, but for paranoia..
urls.forEach(value => {
if (value.startsWith("https://access.redhat.com/security/updates/classification/#")) {
const i = knownLevels.indexOf(value.slice(value.indexOf("#") + 1));
if (i > highestIndex) {
highestIndex = i;
highestURL = value;
}
}
});
return highestURL;
}
function isSafeUrl(href) {
try {
const url = new URL(href);
return ["https:", "http:"].includes(url.protocol);
} catch {
return false;
}
}
// Overrides the link_open function to apply our required HTML attributes
function customRemarkable() {
const remarkable = new Remarkable();
remarkable.renderer.rules.link_open = function(tokens, idx) {
try {
const url = tokens[idx].href;
if (!isSafeUrl(url))
return "";
const a = document.createElement("a");
a.setAttribute("href", url);
a.rel = "noopener noreferrer";
a.target = "_blank";
return a.outerHTML.replace(" ", "");
} catch {
return "";
}
};
return remarkable;
}
function updateItem(remarkable, info, pkgNames, key) {
const bug_urls = (info.bug_urls || []).filter(isSafeUrl);
const cve_urls = (info.cve_urls || []).filter(isSafeUrl);
const vendor_urls = (info.vendor_urls || []).filter(isSafeUrl);
let bugs = null;
if (bug_urls.length > 0) {
// we assume a bug URL ends with a number; if not, show the complete URL
bugs = insertCommas(bug_urls.map(url => (
{url.match(/[0-9]+$/) || url}
)
));
}
let cves = null;
if (cve_urls.length > 0) {
cves = insertCommas(cve_urls.map(url => (
{url.match(/[^/=]+$/)}
)
));
}
let errata = null;
if (vendor_urls.length > 0) {
errata = insertCommas(vendor_urls.filter(url => url.indexOf("/errata/") > 0).map(url => (
{url.match(/[^/=]+$/)}
)
));
if (!errata.length)
errata = null; // simpler testing below
}
let secSeverityURL = getSeverityURL(vendor_urls);
const secSeverity = secSeverityURL ? secSeverityURL.slice(secSeverityURL.indexOf("#") + 1) : null;
const icon = getSeverityIcon(info.severity, secSeverity);
let type;
if (info.severity === Severity.CRITICAL) {
if (secSeverityURL)
secSeverityURL = {secSeverity} ;
type = (
{icon}
{ cve_urls.length > 0 && cve_urls.length}
);
} else {
const tip = (info.severity >= Severity.IMPORTANT) ? _("bug fix") : _("enhancement");
type = (
{icon}
{ bug_urls.length > 0 && bug_urls.length }
);
}
const pkgList = pkgNames.map((n, index) => (
{n.name + (index !== (pkgNames.length - 1) ? ", " : "")}
)
);
const pkgs = pkgList;
const pkgsTruncated = pkgList.slice(0, 4);
if (pkgList.length > 4)
pkgsTruncated.push(… );
if (pkgNames.some(pkg => isKpatchPackage(pkg.name)))
pkgsTruncated.push(
{" "}{_("patches")}
);
let descriptionFirstLine = (info.description || "").trim();
if (descriptionFirstLine.indexOf("\n") >= 0)
descriptionFirstLine = descriptionFirstLine.slice(0, descriptionFirstLine.indexOf("\n"));
descriptionFirstLine = cleanupChangelogLine(descriptionFirstLine);
let description;
if (info.markdown) {
descriptionFirstLine = ;
description =
;
} else {
description = {info.description}
;
}
const expandedContent = (
{_("Packages")}
{pkgs}
{ cves
?
{_("CVE")}
{cves}
: null }
{ secSeverityURL
?
{_("Severity")}
{secSeverityURL}
: null }
{ errata
?
{_("Errata")}
{errata}
: null }
{ bugs
?
{_("Bugs")}
{bugs}
: null }
{description}
);
return {
columns: [
{ title: pkgsTruncated },
{ title: {info.version} , props: { className: "version" } },
{ title: {type} , props: { className: "type" } },
{ title: descriptionFirstLine, props: { className: "changelog" } },
],
props: {
key,
className: info.severity === Severity.CRITICAL ? ["error"] : [],
},
hasPadding: true,
expandedContent,
};
}
const UpdatesList = ({ updates }) => {
const remarkable = customRemarkable();
const combined_updates = [];
// PackageKit doesn"t expose source package names, so group packages with the same version and changelog
// create a reverse version+changes → [id] map on iteration
const sameUpdate = {};
const packageNames = {};
for (const u of updates) {
// did we already see the same version and description? then merge
const hash = u.version + u.description;
const seenId = sameUpdate[hash];
if (seenId) {
packageNames[seenId].push({ name: u.name, arch: u.arch, summary: u.summary });
} else {
// this is a new update
sameUpdate[hash] = u.id;
packageNames[u.id] = [{ name: u.name, arch: u.arch, summary: u.summary }];
combined_updates.push(u);
}
}
// sort security first
combined_updates.sort((a, b) => {
if (a.severity === Severity.CRITICAL && b.severity !== Severity.CRITICAL)
return -1;
if (a.severity !== Severity.CRITICAL && b.severity === Severity.CRITICAL)
return 1;
return a.name.localeCompare(b.name);
});
return (
updateItem(remarkable, update, packageNames[update.id].sort((a, b) => a.name > b.name), update.id))} />
);
};
const formatPackageId = packageId => {
const pfields = packageId.split(";");
return pfields[0] + " " + pfields[1] + " (" + pfields[2] + ")";
};
// actions is a chronological list of { status, packageId } events that happen during applying updates
// status: see PK_STATUS_* at https://github.com/PackageKit/PackageKit/blob/main/lib/packagekit-glib2/pk-enum.h
const ApplyUpdates = ({ transactionProps, actions, onCancel, rebootAfter, setRebootAfter }) => {
const remain = transactionProps.RemainingTime
? timeformat.distanceToNow(new Date().valueOf() + transactionProps.RemainingTime * 1000)
: null;
let percentage = transactionProps.Percentage || 0;
// PackageKit sets this to 101 initially
if (percentage > 100)
percentage = 0;
// scroll update log to the bottom, if it already is (almost) at the bottom
const log = document.getElementById("update-log");
if (log) {
if (log.scrollHeight - log.clientHeight <= log.scrollTop + 2)
log.scrollTop = log.scrollHeight;
}
const cancelButton = transactionProps.AllowCancel
? {_("Cancel")}
: null;
if (actions.length === 0 && percentage === 0) {
return ;
}
const lastAction = actions[actions.length - 1];
// when resuming an upgrade, we did not get any Package signal yet; fall back to LastPackage
const curPackage = formatPackageId(lastAction?.packageId || transactionProps.LastPackage || "");
return (
{PK_STATUS_STRINGS[lastAction?.status] || PK_STATUS_STRINGS[PK.Enum.STATUS_UPDATE]}
{cancelButton}
{
// always scroll down on expansion
const log = document.getElementById("update-log");
log.scrollTop = log.scrollHeight;
}}>
{ actions.slice(0, -1).map((action, i) => (
{PK_STATUS_LOG_STRINGS[action.status] || PK_STATUS_LOG_STRINGS[PK.Enum.STATUS_UPDATE]}
{formatPackageId(action.packageId)}
)) }
);
};
const UpdateSuccess = ({ onIgnore, openServiceRestartDialog, openRebootDialog, restart, manual, reboot, checkRestartAvailable, history }) => {
if (!checkRestartAvailable) {
/* tracer is not available any more in RHEL 10; as a special case, if only kpatch and kernel were
* updated, don't reboot (as that's their whole raison d'être) */
const pkgs = Object.keys(history[0]?.packages ?? {});
const only_kpatch = pkgs.filter(p => p.startsWith("kpatch")).length > 0 &&
pkgs.filter(p => !p.startsWith("kernel") && !p.startsWith("kpatch")).length == 0;
const paragraph = only_kpatch ? null : _("Updated packages may require a reboot to take effect.");
const actions = only_kpatch
? {_("Continue")}
: <>
{_("Reboot system...")}
{_("Ignore")}
>;
return (<>
{ history[0]?.packages &&
}
>);
}
const entries = [];
if (reboot.length > 0) {
entries.push({
columns: [
{
title: }
str={cockpit.format(cockpit.ngettext("$0 package needs a system reboot",
"$0 packages need a system reboot",
reboot.length),
reboot.length)} />
},
],
props: { key: "reboot", id: "reboot-row" },
hasPadding: true,
expandedContent: ,
});
}
if (restart.length > 0) {
entries.push({
columns: [
{
title: }
str={cockpit.format(cockpit.ngettext("$0 service needs to be restarted",
"$0 services need to be restarted",
restart.length),
restart.length)} />
},
],
props: { key: "service", id: "service-row" },
hasPadding: true,
expandedContent: ,
});
}
if (manual.length > 0) {
entries.push({
columns: [
{
title: }
str={_("Some software needs to be restarted manually")} />
}
],
props: { key: "manual", id: "manual-row" },
hasPadding: true,
expandedContent: ,
});
}
const showReboot = reboot.length > 0 || manual.length > 0;
return (<>
{ entries.length > 0 && }
{ showReboot && {_("Reboot system...")} }
{ restart.length > 0 && {_("Restart services...")} }
{ reboot.length > 0 || restart.length > 0 || manual.length > 0
? {_("Ignore")}
: {_("Continue")} }
>
} />
{ history[0]?.packages &&
}
>);
};
const UpdatesStatus = ({ updates, highestSeverity, timeSinceRefresh, restartPackages, onValueChanged }) => {
const numUpdates = updates.length;
const numSecurity = count_security_updates(updates);
const numRestartServices = restartPackages.daemons.length;
const numManualSoftware = restartPackages.manual.length;
const numRebootPackages = restartPackages.reboot.length;
let lastChecked;
// PackageKit returns G_MAXUINT if the db was never checked.
if (timeSinceRefresh !== null && timeSinceRefresh !== 2 ** 32 - 1)
lastChecked = cockpit.format(_("Last checked: $0"), timeformat.distanceToNow(new Date().valueOf() - timeSinceRefresh * 1000));
const notifications = [];
if (numUpdates > 0) {
if (numUpdates == numSecurity) {
const stateStr = cockpit.ngettext("$0 security fix available", "$0 security fixes available", numSecurity);
notifications.push({
id: "security-updates-available",
stateStr: cockpit.format(stateStr, numSecurity),
icon: getSeverityIcon(highestSeverity),
secondary: {lastChecked}
});
} else {
let stateStr = cockpit.ngettext("$0 update available", "$0 updates available", numUpdates);
if (numSecurity > 0)
stateStr += cockpit.ngettext(", including $1 security fix", ", including $1 security fixes", numSecurity);
notifications.push({
id: "updates-available",
stateStr: cockpit.format(stateStr, numUpdates, numSecurity),
icon: getSeverityIcon(highestSeverity),
secondary: {lastChecked}
});
}
} else if (!numRestartServices && !numRebootPackages && !numManualSoftware) {
notifications.push({
id: "system-up-to-date",
stateStr: STATE_HEADINGS.uptodate,
icon: ,
secondary: {lastChecked}
});
}
if (numRebootPackages > 0) {
const stateStr = cockpit.ngettext("$0 package needs a system reboot", "$0 packages need a system reboot", numRebootPackages);
notifications.push({
id: "packages-need-reboot",
stateStr: cockpit.format(stateStr, numRebootPackages),
icon: ,
secondary: onValueChanged("showRebootSystemDialog", true)}>
{_("Reboot system...")}
});
}
if (numRestartServices > 0) {
const stateStr = cockpit.ngettext("$0 service needs to be restarted", "$0 services need to be restarted", numRestartServices);
notifications.push({
id: "services-need-restart",
stateStr: cockpit.format(stateStr, numRestartServices),
icon: ,
secondary: onValueChanged("showRestartServicesDialog", true)}>
{_("Restart services...")}
});
}
if (numManualSoftware > 0) {
notifications.push({
id: "processes-need-restart",
stateStr: _("Some software needs to be restarted manually"),
icon: ,
secondary: {restartPackages.manual.join(", ")}
});
}
return (
{ notifications.map(notification => (
{notification.icon}
{notification.stateStr}
{ notification.secondary }
))}
);
};
class CardsPage extends React.Component {
constructor() {
super();
this.state = {
autoupdates_backend: undefined,
};
}
componentDidMount() {
getBackend(this.props.backend).then(b => { this.setState({ autoupdates_backend: b }) });
}
render() {
const cardContents = [];
let settingsContent = null;
const statusContent =
;
if (this.state.autoupdates_backend) {
settingsContent =
{cockpit.info.os_release && cockpit.info.os_release?.ID === "rhel" &&
}
;
}
cardContents.push({
id: "status",
className: settingsContent !== null ? "ct-card-info" : "",
title: _("Status"),
actions: (
} variant="secondary" onClick={this.props.handleRefresh} />
),
body: statusContent,
});
if (settingsContent !== null) {
cardContents.push({
id: "settings",
className: "ct-card-info",
title: _("Settings"),
body: settingsContent,
});
}
if (this.props.state === "available") { // automatic updates are not tracked by PackageKit, hide history when they are enabled
cardContents.push({
id: "available-updates",
title: _("Available updates"),
actions: (
{this.props.cockpitUpdate &&
{_("Danger alert:")}
{_("Web Console will restart")}
{_("More info...")}
}
{this.props.applyKpatches}
{this.props.applySecurity}
{this.props.applyAll}
),
containsList: true,
body:
});
}
if ((!this.state.autoupdates_backend || !this.state.autoupdates_backend.enabled) && this.props.history.length > 0) { // automatic updates are not tracked by PackageKit, hide history when they are enabled
cardContents.push({
id: "update-history",
title: _("Update history"),
containsList: true,
body:
});
}
return cardContents.map(card => {
return (
{card.title}
{card.body}
);
});
}
}
class OsUpdates extends React.Component {
constructor() {
super();
this.state = {
state: "loading",
errorMessages: [],
updates: [],
timeSinceRefresh: null,
loadPercent: null,
cockpitUpdate: false,
haveOsRepo: null,
applyTransaction: null,
applyTransactionProps: {},
applyActions: [],
history: [],
unregistered: false,
privileged: false,
autoUpdatesEnabled: undefined,
restartPackages: { daemons: [], manual: [], reboot: [] },
checkRestartAvailable: false,
checkRestartRunning: false,
showRestartServicesDialog: false,
showRebootSystemDialog: false,
backend: "",
rebootAfterSuccess: false,
packageManager: null,
};
this.handleLoadError = this.handleLoadError.bind(this);
this.handleRefresh = this.handleRefresh.bind(this);
this.loadUpdates = this.loadUpdates.bind(this);
this.onValueChanged = this.onValueChanged.bind(this);
this.checkNeedsRestart = this.checkNeedsRestart.bind(this);
}
onValueChanged(key, value) {
this.setState({ [key]: value });
}
async componentDidMount() {
this._mounted = true;
this.checkNeedsRestart();
superuser.addEventListener("changed", this.handleSuperUserChange);
// HACK: force usage of PackageKit backend
const packageManager = await getPackageManager(true);
const backend = await packageManager.get_backend();
this.setState({ packageManager, backend });
// check if there is an upgrade in progress already; if so, switch to "applying" state right away
PK.call("/org/freedesktop/PackageKit", "org.freedesktop.PackageKit", "GetTransactionList", [])
.then(([transactions]) => {
if (!this._mounted)
return;
const promises = transactions.map(transactionPath => PK.call(
transactionPath, "org.freedesktop.DBus.Properties", "Get", [PK.transactionInterface, "Role"]));
Promise.all(promises)
.then(roles => {
// any transaction with UPDATE_PACKAGES role?
for (let idx = 0; idx < roles.length; ++idx) {
if (roles[idx][0].v === PK.Enum.ROLE_UPDATE_PACKAGES) {
this.watchUpdates(transactions[idx]);
return;
}
}
// no running updates found, proceed to showing available updates
this.initialLoadOrRefresh();
})
.catch(ex => {
console.warn("GetTransactionList: failed to read PackageKit transaction roles:", ex.message);
// be robust, try to continue with loading updates anyway
this.initialLoadOrRefresh();
});
})
.catch(this.handleLoadError);
}
componentWillUnmount() {
this._mounted = false;
superuser.removeEventListener("changed", this.handleSuperUserChange);
}
handleSuperUserChange = () => {
this.setState({ privileged: superuser.allowed });
// get out of error state when switching from unprivileged to privileged
if (superuser.allowed && this.state.state.indexOf("Error") >= 0)
this.loadUpdates();
};
checkNeedsRestart() {
this.setState({ checkRestartRunning: true });
return python.spawn(callTracerScript, undefined, { err: "message", superuser: "require" })
.then(output => {
debug("tracer succeeded, output:", output);
const restartPackages = JSON.parse(output);
// Filter out duplicates
restartPackages.reboot = deduplicate(shortenCockpitWsInstance(restartPackages.reboot));
restartPackages.daemons = deduplicate(shortenCockpitWsInstance(restartPackages.daemons));
restartPackages.manual = deduplicate(shortenCockpitWsInstance(restartPackages.manual));
debug("tracer parsed restartPackages:", JSON.stringify(restartPackages));
this.setState({ checkRestartAvailable: true, checkRestartRunning: false, restartPackages });
})
.catch((exception, data) => {
// tracer not installed or supported (like on Arch)? then fall back to dnf needs-restarting
if (exception.message?.includes("ModuleNotFoundError") ||
exception.message?.includes("UnsupportedDistribution")) {
debug('tracer not installed:', JSON.stringify(exception), "trying dnf needs-restarting");
return this.checkDnfNeedsRestarting();
}
// log the error except for some common cases: polkit does not allow it
if (exception.problem !== "access-denied" &&
// or unprivileged session
exception.problem !== "authentication-failed" &&
// or the session goes away while checking
exception.problem !== "terminated")
console.error(`Tracer failed: "${JSON.stringify(exception)}", data: "${JSON.stringify(data)}"`);
else
debug('tracer failed for uninteresting reason:', JSON.stringify(exception));
// When tracer fails, act like it's not available (demand reboot after every update)
this.setState({
checkRestartAvailable: false,
checkRestartRunning: false,
restartPackages: { reboot: [], daemons: [], manual: [] },
});
});
}
checkDnfNeedsRestarting() {
const restartPackages = { reboot: [], daemons: [], manual: [] };
// needs-restarting has no machine-readable API: https://issues.redhat.com/browse/RHEL-56139
// dnf5 needs-restarting also has no machine-readable API: https://github.com/rpm-software-management/dnf5/issues/2341
// --exclude-services was added much later, so check that first
return cockpit.spawn(["dnf", "needs-restarting", "--exclude-services"], { err: "message", superuser: "require" })
.then(outManual => {
debug("dnf needs-restarting --exclude-services succeeded:", outManual);
// format: "pid : argv", e.g. "1234 : mydaemon 3600"
outManual.trim()
.split("\n")
// HACK: https://issues.redhat.com/browse/RHEL-84657
.filter(line => line.match(/^\d+ : /))
.forEach(line => !line || restartPackages.manual.push(line));
return Promise.allSettled([
cockpit.spawn(["dnf", "needs-restarting", "--services"], { err: "message", superuser: "require" }),
// we can't get stdout for a failing process, thus needs script
cockpit.script("! dnf needs-restarting --reboothint", undefined, { err: "message", superuser: "require" }),
])
.then(([serviceResult, rebootResult]) => {
// --services format: one unit name per line
if (serviceResult.status == 'fulfilled') {
debug("dnf needs-restarting --services succeeded:", serviceResult.value);
serviceResult.value.trim()
.split("\n")
// HACK: https://issues.redhat.com/browse/RHEL-84657
.filter(line => line.endsWith(".service"))
.forEach(line => restartPackages.daemons.push(line));
} else {
console.error("dnf needs-restarting --services failed:", JSON.stringify(serviceResult.reason));
}
// --reboothint format: " * kernel-rt" plus header/footer; exit nonzero iff reboot required, inverted above
if (rebootResult.status == 'fulfilled') {
debug("dnf needs-restarting --reboothint exited nonzero, wants reboot:", rebootResult.value);
rebootResult.value.split("\n").forEach(line => {
if (line.startsWith(" * "))
restartPackages.reboot.push(line.substring(4));
});
} else {
debug("dnf needs-restarting --reboothint exited zero, no reboot");
}
debug("dnf needs-restarting parsed packages:", JSON.stringify(restartPackages));
this.setState({ checkRestartAvailable: true, checkRestartRunning: false, restartPackages });
});
})
.catch(ex => {
// log the error except for some common cases: no dnf
if (ex.problem !== "not-found" &&
// plugin does not support --exclude-services
!ex.message.includes("usage:") &&
// polkit does not allow it
ex.problem !== "access-denied" &&
// or unprivileged session
ex.problem !== "authentication-failed" &&
// or the session goes away while checking
ex.problem !== "terminated")
console.error("dnf needs-restarting failed:", ex.toString());
// act like it's not available (demand reboot after every update)
this.setState({ checkRestartAvailable: false, checkRestartRunning: false, restartPackages });
});
}
handleLoadError(ex) {
console.warn("loading available updates failed:", JSON.stringify(ex));
if (!this._mounted)
return;
if (ex.problem === "not-found" || ex.name?.includes("DBus.Error.ServiceUnknown"))
ex = _("PackageKit is not installed");
this.setState(prevState => ({ errorMessages: [...prevState.errorMessages, ex.detail || ex.message || ex], state: "loadError" }));
}
loadUpdates() {
let cockpitUpdate = false;
this.setState({ state: "loading" });
// check if there is an available version of coreutils; this is a heuristics for unregistered RHEL
// systems to see if they need a subscription to get "proper" OS updates
this.state.packageManager.is_available(["coreutils"])
.then((have_coreutils) => this.setState({ haveOsRepo: have_coreutils }),
ex => console.warn("Resolving coreutils failed:", JSON.stringify(ex)))
.then(() => this.state.packageManager.get_updates(true, null).then(updates => {
debug("GetUpdates result:", updates);
if (updates.length) {
for (const update of updates) {
if (update.name === 'cockpit-ws') {
cockpitUpdate = true;
// Arch Linux has no cockpit-ws package
} else if (update.name === 'cockpit' && this.state.backend === "alpm") {
cockpitUpdate = true;
}
}
this.setState({ updates, cockpitUpdate, state: "available" });
} else {
this.setState({ updates: [], state: "uptodate" });
}
this.loadHistory();
}))
.catch(this.handleLoadError);
}
async loadHistory() {
try {
const history = await this.state.packageManager.get_history();
this.setState({ history });
} catch (exc) {
console.warn("Failed to load old transactions (history):", exc);
}
}
initialLoadOrRefresh() {
watchRedHatSubscription(registered => this.setState({ unregistered: !registered }));
cockpit.addEventListener("visibilitychange", () => {
if (!cockpit.hidden)
this.loadOrRefresh(false);
});
if (!cockpit.hidden)
this.loadOrRefresh(true);
else
this.loadUpdates();
}
async loadOrRefresh(always_load) {
try {
const seconds = await this.state.packageManager.get_last_refresh_time();
this.setState({ timeSinceRefresh: seconds });
// automatically trigger refresh for ≥ 1 day or if never refreshed
if (seconds >= 24 * 3600 || seconds < 0)
this.handleRefresh();
else if (always_load)
this.loadUpdates();
} catch (exc) {
this.handleLoadError(exc);
}
}
watchUpdates(transactionPath) {
this.setState({ state: "applying", applyTransaction: transactionPath, applyTransactionProps: {}, applyActions: [] });
return PK.watchTransaction(transactionPath,
{
ErrorCode: (code, details) => this.setState(prevState => ({ errorMessages: [...prevState.errorMessages, details] })),
Finished: exit => {
this.setState({ applyTransaction: null, applyTransactionProps: {}, applyActions: [] });
if (exit === PK.Enum.EXIT_SUCCESS) {
this.setState({ state: "loading", loadPercent: null });
this.loadHistory().then(() => {
if (this.state.checkRestartAvailable) {
this.checkNeedsRestart()
.finally(() => this.setState({ state: "updateSuccess" }));
} else {
this.setState({ state: "updateSuccess", loadPercent: null });
}
});
} else if (exit === PK.Enum.EXIT_CANCELLED) {
if (this.state.checkRestartAvailable) {
this.setState({ state: "loading", loadPercent: null });
this.checkNeedsRestart();
}
this.loadUpdates();
} else {
// normally we get FAILED here with ErrorCodes; handle unexpected errors to allow for some debugging
if (exit !== PK.Enum.EXIT_FAILED)
this.setState(prevState => ({ errorMessages: [...prevState.errorMessages, cockpit.format(_("PackageKit reported error code $0"), exit)] }));
this.setState({ state: "updateError" });
}
},
// not working/being used in at least Fedora
RequireRestart: (type, packageId) => console.log("update RequireRestart", type, packageId),
Package: (status, packageId) => this.setState(old =>
({ applyActions: [...old.applyActions, { status, packageId }] })
),
},
notify => this.setState(old =>
({ applyTransactionProps: { ...old.applyTransactionProps, ...notify } })
)
)
.catch(ex => {
this.setState(prevState => ({ errorMessages: [...prevState.errorMessages, ex], state: "updateError" }));
});
}
applyUpdates(type) {
let updates = [...this.state.updates];
if (type === UPDATES.SECURITY)
updates = updates.filter(update => update.severity === Severity.CRITICAL);
if (type === UPDATES.KPATCHES) {
updates = updates.filter(update => isKpatchPackage(update.name));
}
PK.transaction()
.then(transactionPath => {
this.watchUpdates(transactionPath)
.then(() => {
PK.update_packages(updates, null, transactionPath)
.catch(ex => {
// We get more useful error messages through ErrorCode or "PackageKit has crashed", so only
// show this if we don't have anything else
this.setState(prevState => ({
errorMessages: prevState.errorMessages.length === 0 ? [ex.message] : prevState.errorMessages,
state: "updateError",
}));
});
});
})
.catch(ex => {
this.setState(prevState => ({ errorMessages: [...prevState.errorMessages, ex.message], state: "updateError" }));
});
}
renderContent() {
let applySecurity;
let applyKpatches;
let applyAll;
/* On unregistered RHEL systems we need some heuristics: If the "main" OS repos (which provide coreutils) require
* a subscription, then point this out and don't show available updates, even if there are some auxiliary
* repositories enabled which don't require subscriptions. But there are a lot of cases (cloud repos, nightly internal
* repos) which don't need a subscription, there it would just be confusing */
if (this.state.unregistered && this.state.haveOsRepo === false) {
page_status.set_own({
type: "warning",
title: _("Not registered"),
details: {
link: "subscriptions",
}
});
return cockpit.jump("/subscriptions", cockpit.transport.host) }
/>;
}
switch (this.state.state) {
case "loading":
case "refreshing":
case "locked":
page_status.set_own({
type: null,
title: _("Checking for package updates..."),
details: {
link: false,
pficon: "spinner",
}
});
if (this.state.loadPercent)
return ;
else
return ;
case "available":
{
const num_updates = this.state.updates.length;
const num_security_updates = count_security_updates(this.state.updates);
const num_kpatches = count_kpatch_updates(this.state.updates);
const highest_severity = find_highest_severity(this.state.updates);
applyAll = (
this.applyUpdates(UPDATES.ALL) }>
{ num_updates == num_security_updates
? _("Install security updates")
: _("Install all updates") }
);
if (num_security_updates > 0 && num_updates > num_security_updates) {
applySecurity = (
this.applyUpdates(UPDATES.SECURITY) }>
{_("Install security updates")}
);
}
if (num_kpatches > 0) {
applyKpatches = (
this.applyUpdates(UPDATES.KPATCHES) }>
{_("Install kpatch updates")}
);
}
let text;
if (highest_severity == Severity.CRITICAL)
text = _("Security updates available");
else if (highest_severity >= Severity.IMPORTANT)
text = _("Bug fix updates available");
else if (highest_severity >= Severity.LOW)
text = _("Enhancement updates available");
else
text = _("Updates available");
page_status.set_own({
type: num_security_updates > 0 ? "warning" : "info",
title: text,
details: {
pficon: getPageStatusSeverityIcon(highest_severity)
}
});
return (
<>
{ this.state.showRestartServicesDialog &&
this.setState({ showRestartServicesDialog: false })}
state={this.state.state}
checkNeedsRestart={this.checkNeedsRestart}
onValueChanged={delta => this.setState(delta)}
loadUpdates={this.loadUpdates} />
}
{ this.state.showRebootSystemDialog &&
this.setState({ showRebootSystemDialog: false })} />
}
>
);
}
case "loadError":
case "updateError":
page_status.set_own({
type: "error",
title: STATE_HEADINGS[this.state.state],
});
return (
{_("Please resolve the issue and reload this page.")}
}
/>
{this.state.errorMessages
.filter((m, index) => index == 0 || m != this.state.errorMessages[index - 1])
.map(m => {m} )}
);
case "applying":
page_status.set_own(null);
return PK.call(this.state.applyTransaction, PK.transactionInterface, "Cancel", []) }
rebootAfter={this.state.rebootAfterSuccess}
setRebootAfter={ (_event, enabled) => this.setState({ rebootAfterSuccess: enabled }) }
/>;
case "updateSuccess": {
if (this.state.rebootAfterSuccess) {
this.setState({ state: "restart" });
cockpit.spawn(["shutdown", "--reboot", "now"], { superuser: "require" });
return null;
}
let warningTitle;
if (!this.state.checkRestartAvailable) {
warningTitle = _("Reboot recommended");
} else {
if (this.state.restartPackages.reboot.length > 0)
warningTitle = cockpit.ngettext("A package needs a system reboot for the updates to take effect:",
"Some packages need a system reboot for the updates to take effect:",
this.state.restartPackages.reboot.length);
else if (this.state.restartPackages.daemons.length > 0)
warningTitle = cockpit.ngettext("A service needs to be restarted for the updates to take effect:",
"Some services need to be restarted for the updates to take effect:",
this.state.restartPackages.daemons.length);
else if (this.state.restartPackages.manual.length > 0)
warningTitle = _("Some software needs to be restarted manually");
}
if (warningTitle) {
page_status.set_own({
type: "warning",
title: warningTitle
});
}
return (
<>
this.setState({ showRestartServicesDialog: true })}
openRebootDialog={() => this.setState({ showRebootSystemDialog: true })}
restart={this.state.restartPackages.daemons}
manual={this.state.restartPackages.manual}
reboot={this.state.restartPackages.reboot}
checkRestartAvailable={this.state.checkRestartAvailable}
history={this.state.history} />
{ this.state.showRebootSystemDialog &&
this.setState({ showRebootSystemDialog: false })} />
}
{ this.state.showRestartServicesDialog &&
this.setState({ showRestartServicesDialog: false })}
state={this.state.state}
checkNeedsRestart={this.checkNeedsRestart}
onValueChanged={delta => this.setState(delta)}
loadUpdates={this.loadUpdates} />
}
>
);
}
case "restart":
page_status.set_own(null);
return ;
case "uptodate":
{
page_status.set_own({
title: STATE_HEADINGS[this.state.state],
details: {
link: false,
pficon: "check",
}
});
return (
{ this.state.showRestartServicesDialog &&
this.setState({ showRestartServicesDialog: false })}
state={this.state.state}
checkNeedsRestart={this.checkNeedsRestart}
onValueChanged={delta => this.setState(delta)}
loadUpdates={this.loadUpdates} />
}
{ this.state.showRebootSystemDialog &&
this.setState({ showRebootSystemDialog: false })} />
}
);
}
default:
page_status.set_own(null);
return null;
}
}
handleRefresh() {
this.setState({ state: "refreshing", loadPercent: null });
this.state.packageManager.refresh(true, data => this.setState({ loadPercent: data.percentage }))
.then(() => {
if (this._mounted === false)
return;
this.setState({ timeSinceRefresh: 0 });
this.loadUpdates();
})
.catch(this.handleLoadError);
}
render() {
let content = this.renderContent();
if (!["available", "uptodate"].includes(this.state.state))
content = {content} ;
return (
{content}
);
}
}
document.addEventListener("DOMContentLoaded", async () => {
init();
try {
await cockpit.init();
} catch (exp) {
/* Remove this when every beiboot scenario has Cockpit 336 */
if (exp.problem === 'not-supported') {
const os_release = await read_os_release();
cockpit.info.os_release = os_release;
}
}
const root = createRoot(document.getElementById('app'));
root.render( );
});