LCOV - code coverage report
Current view: top level - pkg/sosreport - sosreport.jsx Coverage Total Hit
Test: cockpit Lines: 86.4 % 418 361
Test Date: 2026-07-13 10:00:01

            Line data    Source code
       1              : /*
       2              :  * Copyright (C) 2021 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";
       8              : import 'cockpit-dark-theme'; // once per page
       9              : 
      10            5 : import React, { useState } from "react";
      11            5 : import { createRoot } from 'react-dom/client';
      12              : import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
      13              : import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
      14              : import { CodeBlockCode } from "@patternfly/react-core/dist/esm/components/CodeBlock/index.js";
      15              : import {
      16              :     Modal, ModalBody, ModalFooter, ModalHeader
      17              : } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
      18              : import { Card, CardBody, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
      19              : import { Page, PageSection, } from "@patternfly/react-core/dist/esm/components/Page/index.js";
      20              : import { Flex } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
      21              : import { Label, LabelGroup } from "@patternfly/react-core/dist/esm/components/Label/index.js";
      22              : import { DropdownItem } from '@patternfly/react-core/dist/esm/components/Dropdown/index.js';
      23              : import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
      24              : import { InputGroup } from "@patternfly/react-core/dist/esm/components/InputGroup/index.js";
      25              : import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
      26              : import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
      27              : import { EyeIcon, EyeSlashIcon } from '@patternfly/react-icons';
      28              : 
      29              : import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
      30              : import { ListingTable } from "cockpit-components-table.jsx";
      31              : import { basename as path_basename } from "cockpit-path";
      32              : 
      33            5 : import cockpit from "cockpit";
      34              : import { useObject, useEvent } from "hooks";
      35              : import { superuser } from "superuser";
      36              : import * as python from "python";
      37              : import { FsInfoClient } from "cockpit/fsinfo";
      38              : 
      39              : import { SuperuserButton } from "superuser-dialogs";
      40              : 
      41              : import { fmt_to_fragments } from "utils.jsx";
      42              : import * as timeformat from "timeformat";
      43              : import { WithDialogs, useDialogs } from "dialogs.jsx";
      44              : import { FormHelper } from "cockpit-components-form-helper";
      45              : import { KebabDropdown } from "cockpit-components-dropdown";
      46              : 
      47              : import get_report_dir_py from "./get_report_dir.py";
      48              : 
      49              : import './sosreport.scss';
      50              : 
      51            5 : const _ = cockpit.gettext;
      52              : 
      53            5 : function sosLister() {
      54            5 :     const self = {
      55            5 :         ready: false,
      56            5 :         problem: null,
      57            5 :         reports: {}
      58            5 :     };
      59              : 
      60            5 :     cockpit.event_target(self);
      61              : 
      62            4 :     function emit_changed() {
      63            4 :         self.dispatchEvent("changed");
      64            4 :     }
      65              : 
      66            4 :     function parse_report_name(name, date) {
      67            4 :         const archive_rx = /^(secured-)?sosreport-(.*)\.tar\.[^.]+(\.gpg)?$/;
      68            4 :         const m = name.match(archive_rx);
      69            3 :         if (m) {
      70            3 :             let name = m[2];
      71            3 :             let obfuscated = false;
      72            2 :             if (name.endsWith("-obfuscated")) {
      73            2 :                 obfuscated = true;
      74            2 :                 name = name.replace(/-obfuscated$/, "");
      75            2 :             }
      76              : 
      77            3 :             return {
      78            3 :                 name,
      79            3 :                 encrypted: !!m[1],
      80            3 :                 obfuscated,
      81            3 :                 date,
      82            3 :             };
      83            3 :         }
      84            4 :     }
      85              : 
      86            5 :     let fsinfo = null;
      87              : 
      88            5 :     async function restart() {
      89            5 :         if (superuser.allowed === null)
      90            5 :             return;
      91              : 
      92            5 :         if (fsinfo)
      93            2 :             fsinfo.close();
      94            5 :         self.ready = false;
      95            5 :         self.problem = null;
      96              : 
      97            4 :         const report_dir = (await python.spawn(get_report_dir_py)).trim();
      98              : 
      99            4 :         fsinfo = new FsInfoClient(report_dir, ["entries", "mtime", "type"], { superuser: "require" });
     100            4 :         fsinfo.on("change", state => {
     101            4 :             if (state.loading)
     102            4 :                 return;
     103            0 :             if (state.error) { // Should Not Happen™, realistic errors come through close event
     104            0 :                 console.warn("Failed to watch for sosreports:", state.error);
     105            0 :                 self.problem = state.error.message ?? state.error.problem;
     106            0 :                 emit_changed();
     107            0 :                 return;
     108            0 :             }
     109            4 :             const entries = state.info?.entries;
     110            4 :             const reports = { };
     111            4 :             for (const name in entries) {
     112            4 :                 if (entries[name].type === "reg") {
     113            4 :                     const report = parse_report_name(name, entries[name].mtime);
     114            4 :                     if (report)
     115            3 :                         reports[report_dir + '/' + name] = report;
     116            4 :                 }
     117            4 :             }
     118            4 :             self.reports = reports;
     119            4 :             self.ready = true;
     120            4 :             emit_changed();
     121            4 :         });
     122              : 
     123            2 :         fsinfo.on("close", ex => {
     124            2 :             self.problem = ex.problem;
     125            2 :             self.ready = true;
     126            2 :             emit_changed();
     127            2 :         });
     128            5 :     }
     129              : 
     130            0 :     self.close = () => {
     131            0 :         superuser.removeEventListener("changed", restart);
     132            0 :         if (fsinfo)
     133            0 :             fsinfo.close();
     134            0 :     };
     135              : 
     136            5 :     restart();
     137            5 :     superuser.addEventListener("changed", restart);
     138            5 :     return self;
     139            5 : }
     140              : 
     141            4 : function sosCreate(args, setProgress, setError, setErrorDetail, options) {
     142            4 :     let output = "";
     143            4 :     let plugins_count = 0;
     144            4 :     const progress_regex = /Running ([0-9]+)\/([0-9]+):/; // Only for sos < 3.6
     145            4 :     const finishing_regex = /Finishing plugins.*\[Running: (.*)\]/;
     146            4 :     const starting_regex = /Starting ([0-9]+)\/([0-9]+).*\[Running: (.*)\]/;
     147              : 
     148              :     // TODO - Use a real API instead of scraping stdout once such an API exists
     149            4 :     const task = cockpit.spawn(["sos", "report", "--batch"].concat(args),
     150            4 :                                { superuser: "require", err: "out", pty: true, ...options });
     151              : 
     152            3 :     task.stream(text => {
     153            3 :         let p = 0;
     154            3 :         let m;
     155              : 
     156            3 :         output += text;
     157            3 :         const lines = output.split("\n");
     158            3 :         for (let i = lines.length - 1; i >= 0; i--) {
     159            3 :             if ((m = starting_regex.exec(lines[i]))) {
     160            3 :                 plugins_count = parseInt(m[2], 10);
     161            3 :                 p = ((parseInt(m[1], 10) - m[3].split(" ").length) / plugins_count) * 100;
     162            3 :                 break;
     163            0 :             } else if ((m = finishing_regex.exec(lines[i]))) {
     164            0 :                 if (!plugins_count)
     165            0 :                     p = 100;
     166              :                 else
     167            0 :                     p = ((plugins_count - m[1].split(" ").length) / plugins_count) * 100;
     168            0 :                 break;
     169            0 :             } else if ((m = progress_regex.exec(lines[i]))) {
     170            0 :                 p = (parseInt(m[1], 10) / parseInt(m[2], 10)) * 100;
     171            0 :                 break;
     172            0 :             }
     173            3 :         }
     174              : 
     175            3 :         setProgress(p);
     176            3 :     });
     177              : 
     178            3 :     task.catch(error => {
     179              :         // easier investigation of failures, errors in pty mode may be hard to see
     180            3 :         if (error.problem !== 'cancelled')
     181            2 :             console.error("Failed to call sos report:", JSON.stringify(error));
     182            2 :         setError(error.toString() || _("sos report failed"));
     183            3 :         setErrorDetail(output);
     184            3 :     });
     185              : 
     186            4 :     return task;
     187            4 : }
     188              : 
     189            2 : function sosDownload(path) {
     190            2 :     const basename = path_basename(path);
     191            2 :     const query = window.btoa(JSON.stringify({
     192            2 :         host: cockpit.transport.host,
     193            2 :         payload: "fsread1",
     194            2 :         binary: "raw",
     195            2 :         path,
     196            2 :         superuser: "require",
     197            2 :         max_read_size: -1,
     198            2 :         external: {
     199            2 :             "content-disposition": 'attachment; filename="' + basename + '"',
     200            2 :             "content-type": "application/x-xz, application/octet-stream"
     201            2 :         }
     202            2 :     }));
     203            2 :     const prefix = (new URL(cockpit.transport.uri("channel/" + cockpit.transport.csrf_token))).pathname;
     204            2 :     const url = prefix + '?' + query;
     205            2 :     return new Promise((resolve, reject) => {
     206              :         // We download via a hidden iframe to get better control over the error cases
     207            2 :         const iframe = document.createElement("iframe");
     208            2 :         iframe.setAttribute("src", url);
     209            2 :         iframe.setAttribute("hidden", "hidden");
     210            0 :         iframe.addEventListener("load", () => {
     211            0 :             const title = iframe.contentDocument.title;
     212            0 :             if (title) {
     213            0 :                 reject(title);
     214            0 :             } else {
     215            0 :                 resolve();
     216            0 :             }
     217            0 :         });
     218            2 :         document.body.appendChild(iframe);
     219            2 :     });
     220            2 : }
     221              : 
     222            2 : function sosRemove(path) {
     223              :     // there are various potential extra files; not all of them are expected to exist,
     224              :     // the file API tolerates removing nonexisting files
     225            2 :     const paths = [
     226            2 :         path,
     227            2 :         path + ".asc",
     228            2 :         path + ".gpg",
     229            2 :         path + ".md5",
     230            2 :         path + ".sha256",
     231            2 :     ];
     232            2 :     return Promise.all(paths.map(p => cockpit.file(p, { superuser: "require" }).replace(null)));
     233            2 : }
     234              : 
     235            4 : const SOSDialog = () => {
     236            4 :     const Dialogs = useDialogs();
     237            4 :     const [label, setLabel] = useState("");
     238            4 :     const [passphrase, setPassphrase] = useState("");
     239            4 :     const [showPassphrase, setShowPassphrase] = useState(false);
     240            4 :     const [obfuscate, setObfuscate] = useState(false);
     241            4 :     const [verbose, setVerbose] = useState(false);
     242            4 :     const [task, setTask] = useState(null);
     243            4 :     const [progress, setProgress] = useState(null);
     244            4 :     const [error, setError] = useState(null);
     245            4 :     const [errorDetail, setErrorDetail] = useState(null);
     246              : 
     247            4 :     function run() {
     248            4 :         setError(null);
     249            4 :         setProgress(null);
     250              : 
     251            4 :         const args = [];
     252            4 :         const options = {};
     253              : 
     254            3 :         if (label) {
     255            3 :             args.push("--label");
     256            3 :             args.push(label);
     257            3 :         }
     258              : 
     259            2 :         if (passphrase) {
     260            2 :             args.push("--encrypt");
     261            2 :             options.environ = ["SOSENCRYPTPASS=" + passphrase];
     262            2 :         }
     263              : 
     264            2 :         if (obfuscate) {
     265            2 :             args.push("--clean");
     266            2 :         }
     267              : 
     268            1 :         if (verbose) {
     269            1 :             args.push("-v");
     270            1 :         }
     271              : 
     272            0 :         const task = sosCreate(args, setProgress, err => { if (err === "cancelled") Dialogs.close(); else setError(err); },
     273            4 :                                setErrorDetail, options);
     274            4 :         setTask(task);
     275            4 :         task.then(Dialogs.close);
     276            4 :         task.finally(() => setTask(null));
     277            4 :     }
     278              : 
     279            4 :     const actions = [];
     280            4 :     actions.push(<Button key="run" isLoading={!!task} isDisabled={!!task} onClick={run}>
     281            4 :         {_("Run report")}
     282            4 :     </Button>);
     283            4 :     if (task)
     284            1 :         actions.push(<Button key="stop" variant="secondary" onClick={() => task.close("cancelled")}>
     285            4 :             {_("Stop report")}
     286            4 :         </Button>);
     287              :     else
     288            4 :         actions.push(<Button key="cancel" variant="link" onClick={Dialogs.close}>
     289            4 :             {_("Cancel")}
     290            4 :         </Button>);
     291              : 
     292            4 :     return <Modal id="sos-dialog"
     293            4 :                   position="top"
     294            4 :                   variant="medium"
     295            4 :                   isOpen
     296            4 :                   onClose={Dialogs.close}>
     297            4 :         <ModalHeader title={ _("Run new report") } />
     298            4 :         <ModalBody>
     299            4 :             { error
     300            2 :                 ? <>
     301            2 :                     <Alert variant="warning" isInline title={error}>
     302            2 :                         <CodeBlockCode>{errorDetail}</CodeBlockCode>
     303            2 :                     </Alert>
     304            2 :                     <br />
     305            2 :                 </>
     306            4 :                 : null }
     307            4 :             <p>{ _("SOS reporting collects system information to help with diagnosing problems.") }</p>
     308            4 :             <p>{ _("This information is stored only on the system.") }</p>
     309            4 :             <br />
     310            4 :             <Form isHorizontal>
     311            4 :                 <FormGroup label={_("Report label")}>
     312            3 :                     <TextInput id="sos-dialog-ti-1" value={label} onChange={(_event, value) => setLabel(value)} />
     313            4 :                 </FormGroup>
     314            4 :                 <FormGroup label={_("Encryption passphrase")}>
     315            4 :                     <InputGroup>
     316            0 :                         <TextInput type={showPassphrase ? "text" : "password"} value={passphrase} onChange={(_event, value) => setPassphrase(value)}
     317            4 :                                    id="sos-dialog-ti-2" autoComplete="new-password" />
     318            0 :                         <Button variant="control" onClick={() => setShowPassphrase(!showPassphrase)}>
     319            0 :                             { showPassphrase ? <EyeSlashIcon /> : <EyeIcon /> }
     320            4 :                         </Button>
     321            4 :                     </InputGroup>
     322            4 :                     <FormHelper helperText={_("Leave empty to skip encryption")} />
     323            4 :                 </FormGroup>
     324            4 :                 <FormGroup label={_("Options")} hasNoPaddingTop>
     325            4 :                     <Checkbox label={_("Obfuscate network addresses, hostnames, and usernames")}
     326            2 :                               id="sos-dialog-cb-1" isChecked={obfuscate} onChange={(_, o) => setObfuscate(o)} />
     327            4 :                     <Checkbox label={_("Use verbose logging")}
     328            1 :                               id="sos-dialog-cb-2" isChecked={verbose} onChange={(_, v) => setVerbose(v)} />
     329            4 :                 </FormGroup>
     330            4 :             </Form>
     331            4 :         </ModalBody>
     332            4 :         <ModalFooter>
     333            4 :             {actions}
     334            3 :             {progress ? <span>{cockpit.format(_("Progress: $0"), progress.toFixed() + "%")}</span> : null}
     335            4 :         </ModalFooter>
     336            4 :     </Modal>;
     337            4 : };
     338              : 
     339            2 : const SOSRemoveDialog = ({ path }) => {
     340            2 :     const Dialogs = useDialogs();
     341            2 :     const [task, setTask] = useState(null);
     342            2 :     const [error, setError] = useState(null);
     343              : 
     344            2 :     function remove() {
     345            2 :         setError(null);
     346            2 :         setTask(sosRemove(path)
     347            2 :                 .then(Dialogs.close)
     348            0 :                 .catch(err => {
     349            0 :                     setTask(null);
     350            0 :                     setError(err.toString());
     351            0 :                 }));
     352            2 :     }
     353              : 
     354            2 :     return (
     355            2 :         <Modal id="sos-remove-dialog"
     356            2 :                position="top"
     357            2 :                variant="medium"
     358            2 :                isOpen
     359            2 :                onClose={Dialogs.close}>
     360            2 :             <ModalHeader title={_("Delete report permanently?")} titleIconVariant="warning" />
     361            2 :             <ModalBody>
     362            0 :                 { error && <><Alert variant="warning" isInline title={error} /><br /></> }
     363            2 :                 <p>{fmt_to_fragments(_("The file $0 will be deleted."), <b>{path}</b>)}</p>
     364            2 :             </ModalBody>
     365            2 :             <ModalFooter>
     366            2 :                 <Button key="apply"
     367            2 :                         variant="danger"
     368            2 :                         onClick={remove}
     369            2 :                         isLoading={!!task}
     370            2 :                         isDisabled={!!task}>
     371            2 :                     {_("Delete")}
     372            2 :                 </Button>
     373            2 :                 <Button key="cancel"
     374            2 :                         onClick={Dialogs.close}
     375            2 :                         isDisabled={!!task}
     376            2 :                         variant="link">
     377            2 :                     {_("Cancel")}
     378            2 :                 </Button>
     379            2 :             </ModalFooter>
     380            2 :         </Modal>);
     381            2 : };
     382              : 
     383            0 : const SOSErrorDialog = ({ error }) => {
     384            0 :     const Dialogs = useDialogs();
     385              : 
     386            0 :     return (
     387            0 :         <Modal id="sos-error-dialog"
     388            0 :                position="top"
     389            0 :                variant="medium"
     390            0 :                isOpen
     391            0 :                onClose={Dialogs.close}>
     392            0 :             <ModalHeader title={ _("Error") } />
     393            0 :             <ModalBody>
     394            0 :                 <p>{error}</p>
     395            0 :             </ModalBody>
     396            0 :         </Modal>);
     397            0 : };
     398              : 
     399            5 : const SOSBody = () => {
     400            5 :     const Dialogs = useDialogs();
     401            0 :     const lister = useObject(sosLister, obj => obj.close, []);
     402            5 :     useEvent(lister, "changed");
     403              : 
     404            5 :     const superuser_proxy = useObject(() => cockpit.dbus(null, { bus: "internal" }).proxy("cockpit.Superuser",
     405            5 :                                                                                           "/superuser"),
     406            0 :                                       obj => obj.close(),
     407            5 :                                       []);
     408            5 :     useEvent(superuser_proxy, "changed");
     409              : 
     410            5 :     if (!lister.ready)
     411            5 :         return <EmptyStatePanel loading />;
     412              : 
     413            2 :     if (lister.problem) {
     414            2 :         if (lister.problem === "access-denied")
     415            2 :             return (
     416            2 :                 <EmptyStatePanel
     417            2 :                     title={_("Administrative access required")}
     418            2 :                     paragraph={_("Administrative access is required to create and access reports.")}
     419            0 :                     action={<SuperuserButton />} />);
     420              :         else
     421            0 :             return <EmptyStatePanel title={lister.problem} />;
     422            2 :     }
     423              : 
     424            4 :     function run_report() {
     425            4 :         Dialogs.show(<SOSDialog />);
     426            4 :     }
     427              : 
     428            3 :     function make_report_row(path) {
     429            3 :         const report = lister.reports[path];
     430              : 
     431            2 :         function download() {
     432            0 :             sosDownload(path).catch(err => Dialogs.show(<SOSErrorDialog error={err.toString()} />));
     433            2 :         }
     434              : 
     435            2 :         function remove() {
     436            2 :             Dialogs.show(<SOSRemoveDialog path={path} />);
     437            2 :         }
     438              : 
     439            3 :         const labels = [];
     440            3 :         if (report.encrypted)
     441            2 :             labels.push(<Label key="enc" color="orange">
     442            2 :                 {_("Encrypted")}
     443            2 :             </Label>);
     444            3 :         if (report.obfuscated)
     445            2 :             labels.push(<Label key="obf" color="grey">
     446            2 :                 {_("Obfuscated")}
     447            2 :             </Label>);
     448              : 
     449            3 :         const action = (
     450            3 :             <Button variant="secondary" className="show-only-when-wide"
     451            3 :                     onClick={download}>
     452            3 :                 {_("Download")}
     453            3 :             </Button>);
     454            3 :         const menu = <KebabDropdown dropdownItems={[
     455            3 :             <DropdownItem key="download"
     456            3 :                           className="show-only-when-narrow"
     457            3 :                           onClick={download}>
     458            3 :                 {_("Download")}
     459            3 :             </DropdownItem>,
     460            3 :             <DropdownItem key="remove"
     461            3 :                           onClick={remove}>
     462            3 :                 {_("Delete")}
     463            3 :             </DropdownItem>
     464            3 :         ]} />;
     465              : 
     466            3 :         return {
     467            3 :             props: { key: path },
     468            3 :             columns: [
     469            3 :                 report.name,
     470            3 :                 timeformat.distanceToNow(new Date(report.date * 1000)),
     471            3 :                 { title: <LabelGroup>{labels}</LabelGroup> },
     472            3 :                 {
     473            3 :                     title: <>{action}{menu}</>,
     474            3 :                     props: { className: "pf-v6-c-table__action table-row-action" }
     475            3 :                 },
     476            3 :             ]
     477            3 :         };
     478            3 :     }
     479              : 
     480            4 :     return (
     481            4 :         <PageSection hasBodyWrapper={false}>
     482            4 :             <Card isPlain className="ct-card">
     483            4 :                 <CardHeader actions={{
     484            4 :                     actions: <Button id="create-button" variant="primary" onClick={run_report}>
     485            4 :                         {_("Run report")}
     486            4 :                     </Button>,
     487            4 :                 }}>
     488            4 :                     <CardTitle component="h2">{_("Reports")}</CardTitle>
     489            4 :                 </CardHeader>
     490            4 :                 <CardBody className="contains-list">
     491            4 :                     <ListingTable emptyCaption={_("No system reports.")}
     492            4 :                                   columns={ [
     493            4 :                                       { title: _("Report") },
     494            4 :                                       { title: _("Created") },
     495            4 :                                       { title: _("Attributes") },
     496            4 :                                   ] }
     497            4 :                                   rows={Object
     498            4 :                                           .keys(lister.reports)
     499            0 :                                           .sort((a, b) => lister.reports[b].date - lister.reports[a].date)
     500            4 :                                           .map(make_report_row)} />
     501            4 :                 </CardBody>
     502            4 :             </Card>
     503            4 :         </PageSection>);
     504            5 : };
     505              : 
     506            5 : const SOSPage = () => {
     507            5 :     return (
     508            5 :         <WithDialogs>
     509            5 :             <Page className="pf-m-no-sidebar">
     510            5 :                 <PageSection hasBodyWrapper={false} padding={{ default: "padding" }}>
     511            5 :                     <Flex alignItems={{ default: 'alignItemsCenter' }}>
     512            5 :                         <h2 className="pf-v6-u-font-size-3xl">{_("System diagnostics")}</h2>
     513            5 :                     </Flex>
     514            5 :                 </PageSection>
     515            5 :                 <SOSBody />
     516            5 :             </Page>
     517            5 :         </WithDialogs>);
     518            5 : };
     519              : 
     520            5 : document.addEventListener("DOMContentLoaded", () => {
     521            5 :     cockpit.translate();
     522            5 :     const root = createRoot(document.getElementById('app'));
     523            5 :     root.render(<SOSPage />);
     524            5 : });
        

Generated by: LCOV version 2.0-1