Debian Codegraph @

pkg/systemd/logs.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 'cockpit-dark-theme'; // once per page
8
9 import cockpit from "cockpit";
10 import React, { useState, useEffect } from 'react';
11 import { createRoot } from 'react-dom/client';
12
13 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
14 import { ClipboardCopy } from "@patternfly/react-core/dist/esm/components/ClipboardCopy/index.js";
15 import { Page, PageSection, } from "@patternfly/react-core/dist/esm/components/Page/index.js";
16 import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
17 import { SearchInput } from "@patternfly/react-core/dist/esm/components/SearchInput/index.js";
18 import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
19 import { Toolbar, ToolbarContent, ToolbarGroup, ToolbarItem, ToolbarToggleGroup } from "@patternfly/react-core/dist/esm/components/Toolbar/index.js";
20 import {
21 ExternalLinkSquareAltIcon,
22 FilterIcon,
23 HelpIcon,
24 } from '@patternfly/react-icons';
25
26 import { SimpleSelect } from "cockpit-components-simple-select";
27 import { TypeaheadSelect } from "cockpit-components-typeahead-select";
28
29 import {
30 checkJournalctlGrep,
31 getGrepFiltersFromOptions,
32 getOptionsFromTextInput,
33 } from "./logsHelpers.js";
34 import { JournalBox } from "./logsJournal.jsx";
35 import { LogEntry } from "./logDetails.jsx";
36
37 import { usePageLocation } from "hooks";
38
39 import "./logs.scss";
40
41 const _ = cockpit.gettext;
42
43 const timeFilterOptions = [
44 { key: 1, value: { key: "boot", value: 0 }, content: _("Current boot") },
45 { key: 2, value: { key: "boot", value: "-1" }, content: _("Previous boot") },
46 { key: 3, value: { key: "since", value: "-24hours", default: true }, content: _("Last 24 hours") },
47 { key: 4, value: { key: "since", value: "-7days" }, content: _("Last 7 days") },
48 ];
49
50 const journalPrioOptions = [
51 { value: "emerg", content: _("Only emergency") },
52 { value: "alert", content: _("Alert and above") },
53 { value: "crit", content: _("Critical and above") },
54 { value: "err", content: _("Error and above") },
55 { value: "warning", content: _("Warning and above") },
56 { value: "notice", content: _("Notice and above") },
57 { value: "info", content: _("Info and above") },
58 { value: "debug", content: _("Debug and above") },
59 ];
60
61 const getPrioFilterOption = options => {
62 // `prio` is a legacy name. Accept it, but don't generate it
63 return options.priority || options.prio;
64 };
65
66 const getTimeFilterOption = options => {
67 function find_key(key, value) {
68 return timeFilterOptions.find(o => o.value.key == key && o.value.value == value)?.value;
69 }
70 if (options.boot)
71 return find_key('boot', options.boot);
72 else if (options.since)
73 return find_key('since', options.since);
74 return timeFilterOptions.find(option => 'default' in option.value)?.value; // Use the default key
75 };
76
77 export const LogsPage = () => {
78 const { path, options } = usePageLocation();
79 let follow = !(options.follow && options.follow === "false");
80
81 if (options.boot && options.boot !== "0") // Don't follow if specific boot is picked
82 follow = false;
83
84 // If priority not specified use err
85 if (!options.priority && !options.prio)
86 options.priority = 'err';
87
88 const full_grep = getGrepFiltersFromOptions({ options })[0];
89
90 /* Initial state */
91 const [currentIdentifiers, setCurrentIdentifiers] = useState([]);
92 const [dataFollowing, setDataFollowing] = useState(follow);
93 const [filteredQuery, setFilteredQuery] = useState(undefined);
94 const [journalPrio, setJournalPrio] = useState(getPrioFilterOption(options));
95 const [identifiersFilter, setIdentifiersFilter] = useState(options.tag || "all");
96 const [showTextSearch, setShowTextSearch] = useState(false);
97 const [textFilter, setTextFilter] = useState(full_grep);
98 const [timeFilter, setTimeFilter] = useState(getTimeFilterOption(options));
99 const [updateIdentifiersList, setUpdateIdentifiersList] = useState(true);
100
101 useEffect(() => {
102 checkJournalctlGrep(setShowTextSearch);
103
104 function onNavigate() {
105 const { options, path } = cockpit.location;
106 const full_grep = getGrepFiltersFromOptions({ options })[0];
107
108 if (path.length == 1) return;
109
110 setJournalPrio(getPrioFilterOption(options));
111 setIdentifiersFilter(options.tag || "all");
112 setTextFilter(full_grep);
113 setTimeFilter(getTimeFilterOption(options));
114 }
115
116 cockpit.addEventListener("locationchanged", onNavigate);
117 return () => cockpit.removeEventListener("locationchanged", onNavigate);
118 }, []);
119
120 if (path.length == 1) {
121 return <LogEntry />;
122 } else if (path.length > 1) { /* redirect */
123 console.warn("not a journal location: " + path);
124 cockpit.location = '';
125 }
126
127 const updateUrl = (options) => {
128 cockpit.location.go([], options);
129 };
130
131 const onJournalPrioChange = (value) => {
132 setUpdateIdentifiersList(true);
133
134 updateUrl(Object.assign(options, { priority: value }));
135 };
136
137 const onIdentifiersFilterChange = (value) => {
138 setUpdateIdentifiersList(false);
139
140 if (value == "all") {
141 delete options.tag;
142 updateUrl(Object.assign(options));
143 } else {
144 updateUrl(Object.assign(options, { tag: value }));
145 }
146 };
147
148 const onTextFilterChange = (value) => {
149 setUpdateIdentifiersList(true);
150
151 updateUrl(Object.assign(getOptionsFromTextInput(value)));
152 };
153
154 const onTimeFilterChange = (newTimeFilter) => {
155 setUpdateIdentifiersList(true);
156
157 if (newTimeFilter.key == 'boot' && newTimeFilter.value !== "0") // Don't follow if specific boot is picked
158 setDataFollowing(false);
159 else if (options.boot && options.boot !== "0" && newTimeFilter.key !== "boot") // Start following is specific boot is removed
160 setDataFollowing(true);
161
162 // Remove all parameters which can be set up using filters
163 delete options.boot;
164 delete options.since;
165
166 cockpit.location.go([], Object.assign(options, { [newTimeFilter.key]: newTimeFilter.value }));
167 };
168
169 return (
170 <Page className='pf-m-no-sidebar'>
171 <PageSection hasBodyWrapper={false} id="journal" className="journal-filters">
172 <Toolbar hasNoPadding>
173 <ToolbarContent>
174 <ToolbarToggleGroup className="pf-v6-u-flex-wrap pf-v6-u-flex-grow-1 pf-v6-u-align-items-flex-start" toggleIcon={<><span className="pf-v6-c-button__icon pf-m-start"><FilterIcon /></span>{_("Toggle filters")}</>} breakpoint="lg">
175 <ToolbarGroup>
176 <ToolbarItem>
177 <SimpleSelect
178 toggleProps={{ id: "logs-predefined-filters" }}
179 placeholder={_("Time")}
180 onSelect={onTimeFilterChange}
181 options={timeFilterOptions}
182 selected={timeFilter} />
183 </ToolbarItem>
184
185 <ToolbarItem variant="label">
186 {_("Priority")}
187 </ToolbarItem>
188 <ToolbarItem>
189 <SimpleSelect
190 toggleProps={{ id: "journal-prio-menu" }}
191 placeholder={_("Priority")}
192 onSelect={onJournalPrioChange}
193 options={journalPrioOptions}
194 selected={journalPrio} />
195 </ToolbarItem>
196
197 <ToolbarItem variant="label">
198 {_("Identifier")}
199 </ToolbarItem>
200 <ToolbarItem id="journal-identifier-menu" className="journal-filters-identifier-menu">
201 <IdentifiersFilter currentIdentifiers={currentIdentifiers}
202 onIdentifiersFilterChange={onIdentifiersFilterChange}
203 identifiersFilter={identifiersFilter} />
204 </ToolbarItem>
205 </ToolbarGroup>
206
207 <ToolbarGroup>
208 {showTextSearch &&
209 <>
210 <ToolbarItem variant="label">
211 {_("Filters")}
212 </ToolbarItem>
213 <ToolbarItem className="text-search">
214 <TextFilter id="journal-grep"
215 className="journal-filters-grep"
216 key={textFilter}
217 textFilter={textFilter}
218 onTextFilterChange={onTextFilterChange}
219 filteredQuery={filteredQuery} />
220 </ToolbarItem>
221 </>}
222 <ToolbarItem variant="separator" />
223
224 <ToolbarItem>
225 <Button id="journal-follow"
226 variant="secondary"
227 isDisabled={options.boot && options.boot !== "0"}
228 onClick={() => {
229 // Reset time filter if following mode is now selected but we are on a specific boot
230 if (!dataFollowing && timeFilter && timeFilter.key == "boot" && timeFilter.value !== "0") {
231 setTimeFilter(undefined);
232 }
233
234 setDataFollowing(!dataFollowing);
235 }
236 }
237 data-following={dataFollowing}>
238 {dataFollowing ? _("Pause") : _("Resume")}
239 </Button>
240 </ToolbarItem>
241 </ToolbarGroup>
242 </ToolbarToggleGroup>
243 </ToolbarContent>
244 </Toolbar>
245
246 </PageSection>
247 <PageSection hasBodyWrapper={false}
248 id="journal-box"
249 className="journal-filters-box">
250 <JournalBox dataFollowing={dataFollowing}
251 defaultSince={timeFilter ? timeFilter.value : getTimeFilterOption({}).value}
252 currentIdentifiers={currentIdentifiers}
253 setCurrentIdentifiers={setCurrentIdentifiers}
254 setFilteredQuery={setFilteredQuery}
255 updateIdentifiersList={updateIdentifiersList}
256 setUpdateIdentifiersList={setUpdateIdentifiersList} />
257 </PageSection>
258 </Page>
259 );
260 };
261
262 const IdentifiersFilter = ({ identifiersFilter, onIdentifiersFilterChange, currentIdentifiers }) => {
263 let identifiersArray;
264 if (currentIdentifiers !== undefined) {
265 identifiersArray = [
266 { value: "all", content: _("All") }
267 ];
268 if (currentIdentifiers.length > 0) {
269 identifiersArray.push({ decorator: "divider", key: "divider" });
270 }
271 identifiersArray = identifiersArray.concat(
272 currentIdentifiers
273 .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
274 .map(unit => ({ value: unit, content: unit }))
275 );
276 } else {
277 identifiersArray = [
278 { value: identifiersFilter, content: identifiersFilter, isDisabled: true }
279 ];
280 }
281
282 return (
283 <TypeaheadSelect selectOptions={identifiersArray}
284 isScrollable
285 selected={identifiersFilter}
286 selectedIsTrusted
287 onSelect={(e, selection) => { onIdentifiersFilterChange(selection) }}
288 onClearSelection={identifiersFilter != "all" && (() => { onIdentifiersFilterChange("all") })}
289 />
290 );
291 };
292
293 const TextFilter = ({ textFilter, onTextFilterChange, filteredQuery }) => {
294 const [unsubmittedTextFilter, setUnsubmittedTextFilter] = useState(textFilter);
295 const sinceUntilBody = _("Date specifications should be of the format YYYY-MM-DD hh:mm:ss. Alternatively the strings 'yesterday', 'today', 'tomorrow' are understood. 'now' refers to the current time. Finally, relative times may be specified, prefixed with '-' or '+'");
296
297 const sinceLabel = (
298 <>
299 {_("Since")}
300 <Popover headerContent={_("Start showing entries on or newer than the specified date.")}
301 bodyContent={sinceUntilBody}>
302 <Button icon={<HelpIcon />} className="log-text-filter-popover-button" variant="plain" />
303 </Popover>
304 </>
305 );
306
307 const untilLabel = (
308 <>
309 {_("Until")}
310 <Popover headerContent={_("Start showing entries on or older than the specified date.")}
311 bodyContent={sinceUntilBody}>
312 <Button icon={<HelpIcon />} className="log-text-filter-popover-button" variant="plain" />
313 </Popover>
314 </>
315 );
316
317 const bootLabel = (
318 <>
319 {_("Boot")}
320 <Popover headerContent={_("Show messages from a specific boot.")}
321 bodyContent={_("This will add a match for '_BOOT_ID='. If not specified the logs for the current boot will be shown. If the boot ID is omitted, a positive offset will look up the boots starting from the beginning of the journal, and an equal-or-less-than zero offset will look up boots starting from the end of the journal. Thus, 1 means the first boot found in the journal in chronological order, 2 the second and so on; while -0 is the last boot, -1 the boot before last, and so on.")}>
322 <Button icon={<HelpIcon />} className="log-text-filter-popover-button" variant="plain" />
323 </Popover>
324 </>
325 );
326
327 const serviceLabel = (
328 <>
329 {_("Unit")}
330 <Popover headerContent={_("Show messages for the specified systemd unit.")}
331 bodyContent={_("This will add match for '_SYSTEMD_UNIT=', 'COREDUMP_UNIT=' and 'UNIT=' to find all possible messages for the given unit. Can contain more units separated by comma.")}>
332 <Button icon={<HelpIcon />} className="log-text-filter-popover-button" variant="plain" />
333 </Popover>
334 </>
335 );
336
337 const freeTextLabel = (
338 <>
339 {_("Free-form search")}
340 <Popover headerContent={_("Show messages containing given string.")}
341 bodyContent={_("Any text string in the logs messages can be filtered. The string can also be in the form of a regular expression. Also supports filtering by message log fields. These are space separated values, in form FIELD=VALUE, where value can be comma separated list of possible values.")}>
342 <Button icon={<HelpIcon />} className="log-text-filter-popover-button" variant="plain" />
343 </Popover>
344 </>
345 );
346
347 const searchInputAttributes = [
348 { attr: "since", display: sinceLabel },
349 { attr: "until", display: untilLabel },
350 { attr: "boot", display: bootLabel },
351 { attr: "unit", display: serviceLabel },
352 { attr: "priority" }, // Hide this with CSS
353 { attr: "tag" }, // Hide this with CSS
354 ];
355
356 return (
357 <SearchInput attributes={searchInputAttributes}
358 hasWordsAttrLabel={freeTextLabel}
359 advancedSearchDelimiter=":"
360 id="journal-grep"
361 onClear={() => { onTextFilterChange(""); setUnsubmittedTextFilter("") }}
362 placeholder={_("Type to filter")}
363 value={unsubmittedTextFilter}
364 onChange={(_, val) => setUnsubmittedTextFilter(val)}
365 resetButtonLabel={_("Reset")}
366 submitSearchButtonLabel={_("Search")}
367 formAdditionalItems={<Stack hasGutter>
368 <Button variant="link" component="a" isInline
369 href="https://www.freedesktop.org/software/systemd/man/latest/journalctl.html"
370 icon={<ExternalLinkSquareAltIcon />} iconPosition="right"
371 target="blank" rel="noopener noreferrer">
372 {_("journalctl manpage")}
373 </Button>
374 <ClipboardCopy clickTip={_("Successfully copied to clipboard")}
375 isReadOnly
376 hoverTip={_("Copy to clipboard")}
377 id="journal-cmd-copy"
378 isCode>
379 {filteredQuery}
380 </ClipboardCopy>
381 </Stack>}
382 onSearch={() => onTextFilterChange(unsubmittedTextFilter)} />
383 );
384 };
385
386 function init() {
387 const root = createRoot(document.getElementById('logs'));
388 root.render(<LogsPage />);
389 }
390
391 document.addEventListener("DOMContentLoaded", init);