-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
logsJournal.jsx
343 lines (307 loc) · 13.9 KB
/
logsJournal.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
* This file is part of Cockpit.
*
* Copyright (C) 2020 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <https://www.gnu.org/licenses/>.
*/
import cockpit from "cockpit";
import { journal } from "journal";
import { superuser } from "superuser";
import React from 'react';
import { Alert, AlertActionCloseButton } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
import { JournalOutput } from "cockpit-components-logs-panel.jsx";
import { ExclamationCircleIcon } from '@patternfly/react-icons';
import { getGrepFiltersFromOptions, getFilteredQuery } from "./logsHelpers.js";
// We open a couple of long-running channels with { superuser: "try" },
// so we need to reload the page if the access level changes.
superuser.reload_page_on_change();
const _ = cockpit.gettext;
// Stop stream when entries > QUERY_MORE after clicking 'Load earlier entries' button
const QUERY_MORE = 1000;
// Stop stream when entries > QUERY_COUNT
const QUERY_COUNT = 5000;
export class JournalBox extends React.Component {
constructor(props) {
super(props);
this.state = {
cursor: undefined,
loading: true,
logs: [],
streamFinished: false,
didntReachStart: true,
};
this.appendEntries = this.appendEntries.bind(this);
this.followingProcs = [];
this.loadServiceFilters = this.loadServiceFilters.bind(this);
this.prependEntries = this.prependEntries.bind(this);
this.procs = [];
this.updateQuery = this.updateQuery.bind(this);
this.queryError = this.queryError.bind(this);
this.options = cockpit.location.options;
}
componentDidMount() {
cockpit.addEventListener("locationchanged", this.updateQuery);
this.updateQuery();
}
componentDidUpdate(prevProps) {
if (prevProps.dataFollowing != this.props.dataFollowing) {
if (this.props.dataFollowing) {
const cursor = document.querySelector(".cockpit-logline");
if (cursor)
this.follow(cursor.getAttribute("data-cursor"));
else
this.follow();
} else {
this.stopFollowing();
}
}
}
updateQuery() {
this.stop();
this.options = cockpit.location.options;
this.match = getGrepFiltersFromOptions({ options: this.options })[1];
const { dataFollowing, defaultSince, updateIdentifiersList, setFilteredQuery } = this.props;
const { priority, grep, boot, since, until } = this.options;
let last = dataFollowing ? null : 1;
let count = 0;
let oldest = null;
const all = boot === undefined && since === undefined && until === undefined;
this.out = new JournalOutput(this.options);
this.renderer = journal.renderer(this.out);
const tags_match = [];
this.match.forEach(field => {
if (!field.startsWith("SYSLOG_IDENTIFIER"))
tags_match.push(field);
});
const journalctlOptions = {
boot,
follow: false, /* follow: Show only the most recent journal entries, and continuously print new entries as they are appended to the journal. */
grep,
priority,
reverse: true, /* reverse: Reverse output so that the newest entries are displayed first */
since: since || defaultSince,
until
};
setFilteredQuery(getFilteredQuery({ match: this.match, options: journalctlOptions }));
if (updateIdentifiersList)
this.loadServiceFilters(tags_match, journalctlOptions);
this.setState({ loading: true, didntReachStart: false, streamFinished: false, logs: [] });
const promise = journal.journalctl(this.match, journalctlOptions)
.fail(this.queryError)
.stream(entries => {
if (!last) {
last = entries[0].__CURSOR;
this.follow(last);
}
count += entries.length;
this.appendEntries(entries);
oldest = entries[entries.length - 1].__CURSOR;
if (count >= QUERY_COUNT) {
this.setState({ didntReachStart: true, cursor: oldest });
promise.stop();
}
})
.done(() => {
this.setState({ streamFinished: true });
if (!last && !promise.stopped) {
const journalctlOptions = {
boot,
count: 0,
follow: true,
grep,
priority,
since,
until,
};
this.followingProcs.push(journal.journalctl(this.match, journalctlOptions)
.fail(this.queryError)
.stream(entries => {
this.prependEntries(entries);
}));
}
if (!all)
this.setState({ didntReachStart: true, cursor: oldest });
})
.always(() => this.setState({ loading: false }));
this.procs.push(promise);
}
queryError(error) {
this.setState({ error: cockpit.message(error) });
}
prependEntries(entries) {
for (let i = 0; i < entries.length; i++) {
const serviceTag = entries[i].SYSLOG_IDENTIFIER;
this.renderer.prepend(entries[i]);
// Only update if the service is not yet known
if (serviceTag && !this.props.currentIdentifiers.includes(serviceTag))
// Due to asynchronous nature it needs to be checked whether this
// identifier is not yet defined. The previous check could be omitted
// and only this one used but let's try to trigger as few updates as possible
this.props.setCurrentIdentifiers(identifiers => {
if (!identifiers.includes(serviceTag))
return [...identifiers, serviceTag];
return identifiers;
});
}
this.renderer.prepend_flush();
this.setState({ logs: this.out.logs, loading: false });
}
appendEntries(entries) {
for (let i = 0; i < entries.length; i++)
this.renderer.append(entries[i]);
this.renderer.append_flush();
this.setState({ logs: this.out.logs, loading: false });
}
follow(cursor) {
const { priority, until, grep } = this.options;
const journalctlOptions = {
count: 0,
cursor: cursor || null,
follow: true,
grep,
priority,
until,
};
this.followingProcs.push(journal.journalctl(this.match, journalctlOptions)
.fail(this.queryError)
.stream(entries => {
if (entries[0].__CURSOR == cursor)
entries.shift();
this.prependEntries(entries);
}));
}
loadServiceFilters(match, options) {
// Ideally this would use `--output cat --output-fields SYSLOG_IDENTIFIER` and do
// without `sh -ec`, grep, sort, replaceAll and all of those ugly stuff
// For that we however need newer systemd that includes https://github.com/systemd/systemd/issues/13937
const currentServices = new Set();
const service_options = Object.assign({ output: "verbose" }, options);
let cmd = journal.build_cmd(match, service_options);
cmd = cmd.map(i => i.replaceAll(" ", "\\ ")).join(" ");
cmd = "set -o pipefail; " + cmd + " | grep SYSLOG_IDENTIFIER= | sort -u";
cockpit.spawn(["/bin/bash", "-ec", cmd], { superuser: "try", err: "message" })
.then(entries => {
entries.split("\n").forEach(entry => {
if (entry)
currentServices.add(entry.substring(entry.indexOf('=') + 1));
});
})
.catch(e => {
// grep returns `1` when nothing to match, but in that case message is empty
if (e.message)
console.log("Failed to load services:", e.message);
})
.finally(() => {
this.props.setCurrentIdentifiers(Array.from(currentServices));
});
}
stop() {
this.procs.forEach(proc => proc.stop());
this.followingProcs.forEach(proc => proc.stop());
}
stopFollowing() {
this.followingProcs.forEach(proc => proc.stop());
}
render() {
const { priority, grep } = this.options;
const noLogs = !this.state.logs.length;
let error = null;
if (this.state.error)
error = (
<Alert variant="danger"
isInline
actionClose={<AlertActionCloseButton onClose={() => this.setState({ error: undefined })} />}
title={_("Failed to fetch logs")}>
{this.state.error}
</Alert>
);
if (!this.state.logs.length && this.state.loading)
return (
<>
{error}
<EmptyStatePanel loading title={_("Loading...")} />
</>
);
/* Journalctl command stream finished and there are not more entries to query */
if (!this.state.logs.length && !this.state.didntReachStart && this.state.streamFinished) {
return (
<div id="start-box" className="journal-start">
{error}
<EmptyStatePanel action={_("Clear all filters")}
icon={ExclamationCircleIcon}
actionVariant="link"
onAction={() => cockpit.location.go('/')}
paragraph={_("Can not find any logs using the current combination of filters.")}
title={_("No logs found")}
/>
</div>
);
}
const loadEarlier = (
/* Show 'Load earlier entries' button if we didn't reach start yet */
this.state.didntReachStart
? <EmptyStatePanel action={_("Load earlier entries")}
icon={noLogs ? ExclamationCircleIcon : undefined}
isActionInProgress={this.state.loading}
onAction={() => {
let count = 0;
this.setState({ loading: true });
const journalctlOptions = {
cursor: this.state.cursor,
follow: false,
grep,
priority,
reverse: true,
};
this.setState({ didntReachStart: false });
const promise = journal.journalctl(this.match, journalctlOptions)
.fail(this.queryError)
.stream(entries => {
if (entries[0].__CURSOR == this.state.cursor)
entries.shift();
count += entries.length;
this.appendEntries(entries);
if (count >= QUERY_MORE) {
const stopped = entries[entries.length - 1].__CURSOR;
this.setState({ didntReachStart: true, cursor: stopped, loading: false });
promise.stop();
}
})
.done(() => {
this.setState({ streamFinished: true, loading: false });
});
this.procs.push(promise);
}}
paragraph={noLogs ? _("You may try to load older entries.") : ""}
title={noLogs ? _("No logs found") : ""}
loading={this.state.loading} />
: null
);
return (
<>
{error}
{this.state.logs.length
? <div id="journal-logs" className="panel panel-default cockpit-log-panel" role="table">
{this.state.logs}
</div>
: null}
<div id="start-box" className="journal-start">
{loadEarlier}
</div>
</>
);
}
}