Debian Codegraph @

pkg/sosreport/sosreport.jsx

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