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 5 : restart();
131 5 : superuser.addEventListener("changed", restart);
132 5 : return self;
133 5 : }
134 :
135 4 : function sosCreate(args, setProgress, setError, setErrorDetail) {
136 4 : let output = "";
137 4 : let plugins_count = 0;
138 4 : const progress_regex = /Running ([0-9]+)\/([0-9]+):/; // Only for sos < 3.6
139 4 : const finishing_regex = /Finishing plugins.*\[Running: (.*)\]/;
140 4 : const starting_regex = /Starting ([0-9]+)\/([0-9]+).*\[Running: (.*)\]/;
141 :
142 : // TODO - Use a real API instead of scraping stdout once such an API exists
143 4 : const task = cockpit.spawn(["sos", "report", "--batch"].concat(args),
144 4 : { superuser: "require", err: "out", pty: true });
145 :
146 3 : task.stream(text => {
147 3 : let p = 0;
148 3 : let m;
149 :
150 3 : output += text;
151 3 : const lines = output.split("\n");
152 3 : for (let i = lines.length - 1; i >= 0; i--) {
153 3 : if ((m = starting_regex.exec(lines[i]))) {
154 3 : plugins_count = parseInt(m[2], 10);
155 3 : p = ((parseInt(m[1], 10) - m[3].split(" ").length) / plugins_count) * 100;
156 3 : break;
157 0 : } else if ((m = finishing_regex.exec(lines[i]))) {
158 0 : if (!plugins_count)
159 0 : p = 100;
160 : else
161 0 : p = ((plugins_count - m[1].split(" ").length) / plugins_count) * 100;
162 0 : break;
163 0 : } else if ((m = progress_regex.exec(lines[i]))) {
164 0 : p = (parseInt(m[1], 10) / parseInt(m[2], 10)) * 100;
165 0 : break;
166 0 : }
167 3 : }
168 :
169 3 : setProgress(p);
170 3 : });
171 :
172 3 : task.catch(error => {
173 : // easier investigation of failures, errors in pty mode may be hard to see
174 3 : if (error.problem !== 'cancelled')
175 2 : console.error("Failed to call sos report:", JSON.stringify(error));
176 2 : setError(error.toString() || _("sos report failed"));
177 3 : setErrorDetail(output);
178 3 : });
179 :
180 4 : return task;
181 4 : }
182 :
183 2 : function sosDownload(path) {
184 2 : const basename = path_basename(path);
185 2 : const query = window.btoa(JSON.stringify({
186 2 : host: cockpit.transport.host,
187 2 : payload: "fsread1",
188 2 : binary: "raw",
189 2 : path,
190 2 : superuser: "require",
191 2 : max_read_size: -1,
192 2 : external: {
193 2 : "content-disposition": 'attachment; filename="' + basename + '"',
194 2 : "content-type": "application/x-xz, application/octet-stream"
195 2 : }
196 2 : }));
197 2 : const prefix = (new URL(cockpit.transport.uri("channel/" + cockpit.transport.csrf_token))).pathname;
198 2 : const url = prefix + '?' + query;
199 2 : return new Promise((resolve, reject) => {
200 : // We download via a hidden iframe to get better control over the error cases
201 2 : const iframe = document.createElement("iframe");
202 2 : iframe.setAttribute("src", url);
203 2 : iframe.setAttribute("hidden", "hidden");
204 0 : iframe.addEventListener("load", () => {
205 0 : const title = iframe.contentDocument.title;
206 0 : if (title) {
207 0 : reject(title);
208 0 : } else {
209 0 : resolve();
210 0 : }
211 0 : });
212 2 : document.body.appendChild(iframe);
213 2 : });
214 2 : }
215 :
216 2 : function sosRemove(path) {
217 : // there are various potential extra files; not all of them are expected to exist,
218 : // the file API tolerates removing nonexisting files
219 2 : const paths = [
220 2 : path,
221 2 : path + ".asc",
222 2 : path + ".gpg",
223 2 : path + ".md5",
224 2 : path + ".sha256",
225 2 : ];
226 2 : return Promise.all(paths.map(p => cockpit.file(p, { superuser: "require" }).replace(null)));
227 2 : }
228 :
229 4 : const SOSDialog = () => {
230 4 : const Dialogs = useDialogs();
231 4 : const [label, setLabel] = useState("");
232 4 : const [passphrase, setPassphrase] = useState("");
233 4 : const [showPassphrase, setShowPassphrase] = useState(false);
234 4 : const [obfuscate, setObfuscate] = useState(false);
235 4 : const [verbose, setVerbose] = useState(false);
236 4 : const [task, setTask] = useState(null);
237 4 : const [progress, setProgress] = useState(null);
238 4 : const [error, setError] = useState(null);
239 4 : const [errorDetail, setErrorDetail] = useState(null);
240 :
241 4 : function run() {
242 4 : setError(null);
243 4 : setProgress(null);
244 :
245 4 : const args = [];
246 :
247 3 : if (label) {
248 3 : args.push("--label");
249 3 : args.push(label);
250 3 : }
251 :
252 2 : if (passphrase) {
253 2 : args.push("--encrypt-pass");
254 2 : args.push(passphrase);
255 2 : }
256 :
257 2 : if (obfuscate) {
258 2 : args.push("--clean");
259 2 : }
260 :
261 1 : if (verbose) {
262 1 : args.push("-v");
263 1 : }
264 :
265 0 : const task = sosCreate(args, setProgress, err => { if (err == "cancelled") Dialogs.close(); else setError(err); },
266 4 : setErrorDetail);
267 4 : setTask(task);
268 4 : task.then(Dialogs.close);
269 4 : task.finally(() => setTask(null));
270 4 : }
271 :
272 4 : const actions = [];
273 4 : actions.push(<Button key="run" isLoading={!!task} isDisabled={!!task} onClick={run}>
274 4 : {_("Run report")}
275 4 : </Button>);
276 4 : if (task)
277 1 : actions.push(<Button key="stop" variant="secondary" onClick={() => task.close("cancelled")}>
278 4 : {_("Stop report")}
279 4 : </Button>);
280 : else
281 4 : actions.push(<Button key="cancel" variant="link" onClick={Dialogs.close}>
282 4 : {_("Cancel")}
283 4 : </Button>);
284 :
285 4 : return <Modal id="sos-dialog"
286 4 : position="top"
287 4 : variant="medium"
288 4 : isOpen
289 4 : onClose={Dialogs.close}>
290 4 : <ModalHeader title={ _("Run new report") } />
291 4 : <ModalBody>
292 4 : { error
293 2 : ? <>
294 2 : <Alert variant="warning" isInline title={error}>
295 2 : <CodeBlockCode>{errorDetail}</CodeBlockCode>
296 2 : </Alert>
297 2 : <br />
298 2 : </>
299 4 : : null }
300 4 : <p>{ _("SOS reporting collects system information to help with diagnosing problems.") }</p>
301 4 : <p>{ _("This information is stored only on the system.") }</p>
302 4 : <br />
303 4 : <Form isHorizontal>
304 4 : <FormGroup label={_("Report label")}>
305 3 : <TextInput id="sos-dialog-ti-1" value={label} onChange={(_event, value) => setLabel(value)} />
306 4 : </FormGroup>
307 4 : <FormGroup label={_("Encryption passphrase")}>
308 4 : <InputGroup>
309 0 : <TextInput type={showPassphrase ? "text" : "password"} value={passphrase} onChange={(_event, value) => setPassphrase(value)}
310 4 : id="sos-dialog-ti-2" autoComplete="new-password" />
311 0 : <Button variant="control" onClick={() => setShowPassphrase(!showPassphrase)}>
312 0 : { showPassphrase ? <EyeSlashIcon /> : <EyeIcon /> }
313 4 : </Button>
314 4 : </InputGroup>
315 4 : <FormHelper helperText={_("Leave empty to skip encryption")} />
316 4 : </FormGroup>
317 4 : <FormGroup label={_("Options")} hasNoPaddingTop>
318 4 : <Checkbox label={_("Obfuscate network addresses, hostnames, and usernames")}
319 2 : id="sos-dialog-cb-1" isChecked={obfuscate} onChange={(_, o) => setObfuscate(o)} />
320 4 : <Checkbox label={_("Use verbose logging")}
321 1 : id="sos-dialog-cb-2" isChecked={verbose} onChange={(_, v) => setVerbose(v)} />
322 4 : </FormGroup>
323 4 : </Form>
324 4 : </ModalBody>
325 4 : <ModalFooter>
326 4 : {actions}
327 3 : {progress ? <span>{cockpit.format(_("Progress: $0"), progress.toFixed() + "%")}</span> : null}
328 4 : </ModalFooter>
329 4 : </Modal>;
330 4 : };
331 :
332 2 : const SOSRemoveDialog = ({ path }) => {
333 2 : const Dialogs = useDialogs();
334 2 : const [task, setTask] = useState(null);
335 2 : const [error, setError] = useState(null);
336 :
337 2 : function remove() {
338 2 : setError(null);
339 2 : setTask(sosRemove(path)
340 2 : .then(Dialogs.close)
341 0 : .catch(err => {
342 0 : setTask(null);
343 0 : setError(err.toString());
344 0 : }));
345 2 : }
346 :
347 2 : return (
348 2 : <Modal id="sos-remove-dialog"
349 2 : position="top"
350 2 : variant="medium"
351 2 : isOpen
352 2 : onClose={Dialogs.close}>
353 2 : <ModalHeader title={_("Delete report permanently?")} titleIconVariant="warning" />
354 2 : <ModalBody>
355 0 : { error && <><Alert variant="warning" isInline title={error} /><br /></> }
356 2 : <p>{fmt_to_fragments(_("The file $0 will be deleted."), <b>{path}</b>)}</p>
357 2 : </ModalBody>
358 2 : <ModalFooter>
359 2 : <Button key="apply"
360 2 : variant="danger"
361 2 : onClick={remove}
362 2 : isLoading={!!task}
363 2 : isDisabled={!!task}>
364 2 : {_("Delete")}
365 2 : </Button>
366 2 : <Button key="cancel"
367 2 : onClick={Dialogs.close}
368 2 : isDisabled={!!task}
369 2 : variant="link">
370 2 : {_("Cancel")}
371 2 : </Button>
372 2 : </ModalFooter>
373 2 : </Modal>);
374 2 : };
375 :
376 0 : const SOSErrorDialog = ({ error }) => {
377 0 : const Dialogs = useDialogs();
378 :
379 0 : return (
380 0 : <Modal id="sos-error-dialog"
381 0 : position="top"
382 0 : variant="medium"
383 0 : isOpen
384 0 : onClose={Dialogs.close}>
385 0 : <ModalHeader title={ _("Error") } />
386 0 : <ModalBody>
387 0 : <p>{error}</p>
388 0 : </ModalBody>
389 0 : </Modal>);
390 0 : };
391 :
392 2 : const MenuItem = ({ onClick, onlyNarrow, children }) => (
393 2 : <DropdownItem className={onlyNarrow ? "show-only-when-narrow" : null}
394 2 : onKeyDown={onClick}
395 2 : onClick={onClick}>
396 2 : {children}
397 2 : </DropdownItem>
398 : );
399 :
400 5 : const SOSBody = () => {
401 5 : const Dialogs = useDialogs();
402 0 : const lister = useObject(sosLister, obj => obj.close, []);
403 5 : useEvent(lister, "changed");
404 :
405 5 : const superuser_proxy = useObject(() => cockpit.dbus(null, { bus: "internal" }).proxy("cockpit.Superuser",
406 5 : "/superuser"),
407 0 : obj => obj.close(),
408 5 : []);
409 5 : useEvent(superuser_proxy, "changed");
410 :
411 5 : if (!lister.ready)
412 5 : return <EmptyStatePanel loading />;
413 :
414 2 : if (lister.problem) {
415 2 : if (lister.problem == "access-denied")
416 2 : return (
417 2 : <EmptyStatePanel
418 2 : title={_("Administrative access required")}
419 2 : paragraph={_("Administrative access is required to create and access reports.")}
420 0 : action={<SuperuserButton />} />);
421 : else
422 0 : return <EmptyStatePanel title={lister.problem} />;
423 2 : }
424 :
425 4 : function run_report() {
426 4 : Dialogs.show(<SOSDialog />);
427 4 : }
428 :
429 3 : function make_report_row(path) {
430 3 : const report = lister.reports[path];
431 :
432 2 : function download() {
433 0 : sosDownload(path).catch(err => Dialogs.show(<SOSErrorDialog error={err.toString()} />));
434 2 : }
435 :
436 2 : function remove() {
437 2 : Dialogs.show(<SOSRemoveDialog path={path} />);
438 2 : }
439 :
440 3 : const labels = [];
441 3 : if (report.encrypted)
442 2 : labels.push(<Label key="enc" color="orange">
443 2 : {_("Encrypted")}
444 2 : </Label>);
445 3 : if (report.obfuscated)
446 2 : labels.push(<Label key="obf" color="grey">
447 2 : {_("Obfuscated")}
448 2 : </Label>);
449 :
450 3 : const action = (
451 3 : <Button variant="secondary" className="show-only-when-wide"
452 3 : onClick={download}>
453 3 : {_("Download")}
454 3 : </Button>);
455 3 : const menu = <KebabDropdown dropdownItems={[
456 3 : <MenuItem key="download"
457 3 : onlyNarrow
458 3 : onClick={download}>
459 3 : {_("Download")}
460 3 : </MenuItem>,
461 3 : <MenuItem key="remove"
462 3 : onClick={remove}>
463 3 : {_("Delete")}
464 3 : </MenuItem>
465 3 : ]} />;
466 :
467 3 : return {
468 3 : props: { key: path },
469 3 : columns: [
470 3 : report.name,
471 3 : timeformat.distanceToNow(new Date(report.date * 1000)),
472 3 : { title: <LabelGroup>{labels}</LabelGroup> },
473 3 : {
474 3 : title: <>{action}{menu}</>,
475 3 : props: { className: "pf-v6-c-table__action table-row-action" }
476 3 : },
477 3 : ]
478 3 : };
479 3 : }
480 :
481 4 : return (
482 4 : <PageSection hasBodyWrapper={false}>
483 4 : <Card isPlain className="ct-card">
484 4 : <CardHeader actions={{
485 4 : actions: <Button id="create-button" variant="primary" onClick={run_report}>
486 4 : {_("Run report")}
487 4 : </Button>,
488 4 : }}>
489 4 : <CardTitle component="h2">{_("Reports")}</CardTitle>
490 4 : </CardHeader>
491 4 : <CardBody className="contains-list">
492 4 : <ListingTable emptyCaption={_("No system reports.")}
493 4 : columns={ [
494 4 : { title: _("Report") },
495 4 : { title: _("Created") },
496 4 : { title: _("Attributes") },
497 4 : ] }
498 4 : rows={Object
499 4 : .keys(lister.reports)
500 0 : .sort((a, b) => lister.reports[b].date - lister.reports[a].date)
501 4 : .map(make_report_row)} />
502 4 : </CardBody>
503 4 : </Card>
504 4 : </PageSection>);
505 5 : };
506 :
507 5 : const SOSPage = () => {
508 5 : return (
509 5 : <WithDialogs>
510 5 : <Page className="pf-m-no-sidebar">
511 5 : <PageSection hasBodyWrapper={false} padding={{ default: "padding" }}>
512 5 : <Flex alignItems={{ default: 'alignItemsCenter' }}>
513 5 : <h2 className="pf-v6-u-font-size-3xl">{_("System diagnostics")}</h2>
514 5 : </Flex>
515 5 : </PageSection>
516 5 : <SOSBody />
517 5 : </Page>
518 5 : </WithDialogs>);
519 5 : };
520 :
521 5 : document.addEventListener("DOMContentLoaded", () => {
522 5 : cockpit.translate();
523 5 : const root = createRoot(document.getElementById('app'));
524 5 : root.render(<SOSPage />);
525 5 : });
|