Debian Codegraph @

pkg/metrics/metrics.jsx

raw
1 /*
2 * Copyright (C) 2017 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React, { useState, createRef } from 'react';
7
8 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
9 import { Breadcrumb, BreadcrumbItem } from "@patternfly/react-core/dist/esm/components/Breadcrumb/index.js";
10 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
11 import { Card, CardBody, CardHeader, CardTitle } from "@patternfly/react-core/dist/esm/components/Card/index.js";
12 import { Gallery } from "@patternfly/react-core/dist/esm/layouts/Gallery/index.js";
13 import { DescriptionList, DescriptionListDescription, DescriptionListGroup, DescriptionListTerm } from "@patternfly/react-core/dist/esm/components/DescriptionList/index.js";
14 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
15 import { Grid, GridItem } from "@patternfly/react-core/dist/esm/layouts/Grid/index.js";
16 import { Icon } from "@patternfly/react-core/dist/esm/components/Icon/index.js";
17 import {
18 Modal, ModalBody, ModalFooter, ModalHeader
19 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
20 import { Page, PageGroup, PageSection, PageBreadcrumb } from "@patternfly/react-core/dist/esm/components/Page/index.js";
21 import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
22 import { Progress, ProgressVariant } from "@patternfly/react-core/dist/esm/components/Progress/index.js";
23 import { Stack, StackItem } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
24 import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
25 import { Content, ContentVariants } from "@patternfly/react-core/dist/esm/components/Content/index.js";
26 import { Tooltip } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
27 import { Table, Thead, Td, Th, Tr, Tbody, TableGridBreakpoint, TableVariant, TableText } from '@patternfly/react-table';
28 import {
29 AngleRightIcon, AngleDownIcon, ExclamationTriangleIcon, ExclamationCircleIcon, CogIcon, ExternalLinkAltIcon,
30 ResourcesFullIcon, ResourcesAlmostFullIcon, ResourcesAlmostEmptyIcon
31 } from '@patternfly/react-icons';
32
33 import cockpit from 'cockpit';
34 import * as machine_info from "../lib/machine-info.js";
35 import * as service from "service";
36 import * as timeformat from "timeformat";
37 import { superuser } from "superuser";
38 import { journal } from "journal";
39 import { read_os_release } from "os-release";
40 import { get_manifest_config_matchlist } from "utils";
41 import { useObject, useEvent, useInit } from "hooks.js";
42 import { WithDialogs, useDialogs } from "dialogs.jsx";
43
44 import { SimpleSelect } from "cockpit-components-simple-select.jsx";
45 import { CheckboxSelect } from "cockpit-components-checkbox-select.jsx";
46 import { EmptyStatePanel } from "../lib/cockpit-components-empty-state.jsx";
47 import { JournalOutput } from "cockpit-components-logs-panel.jsx";
48 import { install_dialog } from "cockpit-components-install-dialog.jsx";
49 import { ModalError } from "cockpit-components-inline-notification.jsx";
50 import { FirewalldRequest } from "cockpit-components-firewalld-request.jsx";
51
52 import "./metrics.scss";
53 import "journal.css";
54 import { getPackageManager } from 'packagemanager.js';
55
56 const MSEC_PER_H = 3600000;
57 const INTERVAL = 5000;
58 const SAMPLES_PER_H = MSEC_PER_H / INTERVAL;
59 const SAMPLES_PER_MIN = SAMPLES_PER_H / 60;
60 const SVG_YMAX = (SAMPLES_PER_MIN - 1);
61 const LOAD_HOURS = 12;
62 const _ = cockpit.gettext;
63
64 // format Date as YYYY-MM-DD HH:mm:ss UTC which is human friendly and systemd compatible
65 const formatUTC_ISO = t => `${t.getUTCFullYear()}-${t.getUTCMonth() + 1}-${t.getUTCDate()} ${t.getUTCHours()}:${t.getUTCMinutes()}:${t.getUTCSeconds()} UTC`;
66
67 // podman's containers cgroup
68 const podmanCgroupRe = /libpod-(?<containerid>[a-z|0-9]{64})\.scope$/;
69 // cgroup userid
70 const useridCgroupRe = /user-(?<userid>\d+).slice/;
71
72 // keep track of maximum values for unbounded data, so that we can normalize it properly
73 // pre-init them to avoid inflating noise
74 let scaleSatCPU = 4;
75 let scaleUseDisks = 10000; // KB/s
76 let scaleUseNetwork = 100000; // B/s
77
78 let numCpu = 1;
79 let memTotal; // bytes
80 let swapTotal; // bytes, can be undefined
81
82 const machine_info_promise = machine_info.cpu_ram_info();
83 machine_info_promise.then(info => {
84 numCpu = info.cpus;
85 memTotal = info.memory;
86 swapTotal = info.swap;
87 });
88
89 // round up to the nearest number that has all zeroes except for the first digit
90 // avoids over-aggressive scaling, but needs scaling more often
91 const scaleForValue = x => {
92 const scale = Math.pow(10, Math.floor(Math.log10(x)));
93 // this can be tweaked towards "less rescaling" with an additional scalar, like "x * 1.5 / scale"
94 return Math.ceil(x / scale) * scale;
95 };
96
97 const RESOURCES = {
98 use_cpu: {
99 name: _("CPU usage"),
100 event_description: _("CPU"),
101 // all in msec/s
102 normalize: ([nice, user, sys]) => (nice + user + sys) / 1000 / numCpu,
103 format: ([nice, user, sys]) => `${_("nice")}: ${Math.round(nice / 10)}%, ${_("user")}: ${Math.round(user / 10)}%, ${_("sys")}: ${Math.round(sys / 10)}%`,
104 },
105 sat_cpu: {
106 name: _("Load"),
107 event_description: _("Load"),
108 // unitless, unbounded, dynamic scaling for normalization
109 normalize: load => Math.min(load, scaleSatCPU) / scaleSatCPU,
110 format: load => cockpit.format_number(load),
111 },
112 use_memory: {
113 name: _("Memory usage"),
114 event_description: _("Memory"),
115 // assume used == total - available
116 normalize: ([totalKiB, availKiB]) => 1 - (availKiB / totalKiB),
117 format: ([totalKiB, availKiB]) => `${cockpit.format_bytes((totalKiB - availKiB) * 1024)} / ${cockpit.format_bytes(totalKiB * 1024)}`,
118 },
119 sat_memory: {
120 name: _("Swap out"),
121 event_description: _("Swap"),
122 // page/s, unbounded, and mostly 0; just categorize into "nothing" (most of the time),
123 // "a little" (< 1000 pages), and "a lot" (> 1000 pages)
124 normalize: swapout => swapout > 1000 ? 1 : (swapout > 1 ? 0.3 : 0),
125 format: swapout => cockpit.format(cockpit.ngettext("$0 page", "$0 pages", Math.floor(swapout)), Math.floor(swapout)),
126 },
127 use_disks: {
128 name: _("Disk I/O"),
129 event_description: _("Disk I/O"),
130 // KiB/s, unbounded, dynamic scaling for normalization
131 normalize: KiBps => KiBps / scaleUseDisks,
132 format: KiBps => cockpit.format_bytes_per_sec(KiBps * 1024),
133 },
134 use_network: {
135 name: _("Network I/O"),
136 event_description: _("Network I/O"),
137 // B/s, unbounded, dynamic scaling for normalization
138 normalize: bps => bps / scaleUseNetwork,
139 format: bps => cockpit.format_bytes_per_sec(bps),
140 },
141 };
142
143 const CURRENT_METRICS = [
144 { name: "cpu.basic.user", derive: "rate" },
145 { name: "cpu.basic.system", derive: "rate" },
146 { name: "cpu.basic.nice", derive: "rate" },
147 { name: "memory.used" },
148 { name: "memory.swap-used" },
149 { name: "disk.all.read", units: "bytes", derive: "rate" },
150 { name: "disk.all.written", units: "bytes", derive: "rate" },
151 { name: "network.interface.rx", units: "bytes", derive: "rate" },
152 { name: "network.interface.tx", units: "bytes", derive: "rate" },
153 { name: "cgroup.cpu.usage", derive: "rate" },
154 { name: "cgroup.memory.usage" },
155 { name: "cpu.core.user", derive: "rate" },
156 { name: "cpu.core.system", derive: "rate" },
157 { name: "cpu.core.nice", derive: "rate" },
158 { name: "disk.dev.read", units: "bytes", derive: "rate" },
159 { name: "disk.dev.written", units: "bytes", derive: "rate" },
160 { name: "mount.total", units: "bytes" },
161 { name: "mount.used", units: "bytes" },
162 ];
163
164 const CPU_TEMPERATURE_METRICS = [
165 { name: "cpu.temperature" },
166 ];
167
168 const PRIVILEGED_METRICS = [
169 { name: "disk.cgroup.read", units: "bytes", derive: "rate" },
170 { name: "disk.cgroup.written", units: "bytes", derive: "rate" },
171 ];
172
173 const HISTORY_METRICS = [
174 // CPU utilization
175 { name: "kernel.all.cpu.nice", derive: "rate" },
176 { name: "kernel.all.cpu.user", derive: "rate" },
177 { name: "kernel.all.cpu.sys", derive: "rate" },
178
179 // CPU saturation
180 { name: "kernel.all.load" },
181
182 // memory utilization (unit: KiB)
183 { name: "mem.physmem" },
184 // mem.util.used is useless, it includes cache (unit: KiB)
185 { name: "mem.util.available" },
186
187 // memory saturation
188 { name: "swap.pagesout", derive: "rate" },
189
190 // disk utilization; despite the name, the unit is in KiB! (pminfo -d -F disk.all.total_bytes)
191 { name: "disk.all.total_bytes", derive: "rate" },
192
193 // network utilization
194 { name: "network.interface.total.bytes", derive: "rate" },
195 ];
196
197 function debug() {
198 if (window.debugging == "all" || window.debugging?.includes("metrics"))
199 console.debug.apply(console, arguments);
200 }
201
202 // metrics channel samples are compressed, see
203 // https://github.com/cockpit-project/cockpit/blob/main/doc/protocol.md#payload-metrics1
204 // samples is the compressed metrics channel value, state the last valid values (initialize once to empty array)
205 function decompress_samples(samples, state) {
206 samples.forEach((sample, i) => {
207 if (sample instanceof Array) {
208 if (!state[i]) // uninitialized, create empty array
209 state[i] = [];
210 sample.forEach((inst, k) => {
211 if (typeof inst === 'number')
212 state[i][k] = inst;
213 });
214 } else if (typeof sample === 'number') {
215 state[i] = sample;
216 }
217 });
218 }
219
220 function make_rows(rows, rowProps, columnLabels) {
221 return rows.map((columns, rowIndex) =>
222 <Tr key={"row-" + rowIndex} {...rowProps?.(columns)}>
223 {columns.map((column, columnIndex) =>
224 <Td data-label={columnLabels?.[columnIndex]} key={"column-" + columnIndex}>
225 {column}
226 </Td>
227 )}
228 </Tr>
229 );
230 }
231
232 async function get_pcp_packages() {
233 const os_release = await read_os_release();
234 const pcp_packages = ["pcp"];
235
236 // PCP contains the Python module on Arch Linux, for all other distro's it is split up.
237 if (os_release.ID !== "arch") {
238 pcp_packages.push("python3-pcp");
239 }
240
241 return pcp_packages;
242 }
243
244 class CurrentMetrics extends React.Component {
245 constructor(props) {
246 super(props);
247
248 this.metrics_channel = null;
249 this.temperature_channel = null;
250 this.privileged_channel = null;
251 this.samples = [];
252 this.temperatureSamples = [];
253 this.privilegedSamples = [];
254 this.netInterfacesNames = [];
255 this.cgroupCPUNames = [];
256 this.cgroupMemoryNames = [];
257 this.cgroupDiskNames = [];
258 this.disksNames = [];
259 this.cpuTemperature = null;
260 this.cpuTemperatureColors = {
261 textColor: "",
262 iconColor: "",
263 icon: null,
264 };
265
266 this.state = {
267 userid: null,
268 memUsed: 0, // bytes
269 swapUsed: null, // bytes
270 cpuUsed: 0, // percentage
271 cpuCoresUsed: [], // [ percentage ]
272 loadAvg: null, // [ 1min, 5min, 15min ]
273 disksRead: 0, // B/s
274 disksWritten: 0, // B/s
275 mounts: [], // [{ target (string), use (percent), avail (bytes) }]
276 netInterfacesRx: [],
277 netInterfacesTx: [],
278 topServicesCPU: [], // [ { name, percent } ]
279 topServicesMemory: [], // [ { name, bytes } ]
280 topServicesDiskIO: [], // [ [ name, read, write ] ]
281 podNameMapping: {}, // { uid -> containerid -> name }
282 };
283
284 this.onVisibilityChange = this.onVisibilityChange.bind(this);
285 this.onMetricsUpdate = this.onMetricsUpdate.bind(this);
286 this.onTemperatureUpdate = this.onTemperatureUpdate.bind(this);
287 this.onPrivilegedMetricsUpdate = this.onPrivilegedMetricsUpdate.bind(this);
288 this.updateLoad = this.updateLoad.bind(this);
289
290 cockpit.addEventListener("visibilitychange", this.onVisibilityChange);
291 this.onVisibilityChange();
292
293 // there is no internal metrics channel for load yet; see https://github.com/cockpit-project/cockpit/pull/14510
294 this.updateLoad();
295 }
296
297 componentDidMount() {
298 superuser.addEventListener("changed", () => this.setState({ podNameMapping: {} }));
299 cockpit.user().then(user => this.setState({ userid: user.id }));
300 }
301
302 onVisibilityChange() {
303 if (cockpit.hidden && this.temperature_channel !== null) {
304 this.temperature_channel.removeEventListener("message", this.onTemperatureUpdate);
305 this.temperature_channel.close();
306 this.temperature_channel = null;
307 }
308
309 if (cockpit.hidden && this.privileged_channel !== null) {
310 this.privileged_channel.removeEventListener("message", this.onPrivilegedMetricsUpdate);
311 this.privileged_channel.close();
312 this.privileged_channel = null;
313 }
314
315 if (cockpit.hidden && this.metrics_channel !== null) {
316 this.metrics_channel.removeEventListener("message", this.onMetricsUpdate);
317 this.metrics_channel.close();
318 this.metrics_channel = null;
319 return;
320 }
321
322 if (!cockpit.hidden && (this.temperature_channel === null)) {
323 this.temperature_channel = cockpit.channel({ payload: "metrics1", source: "internal", interval: INTERVAL, metrics: CPU_TEMPERATURE_METRICS });
324 this.temperature_channel.addEventListener("close", (ev, error) => console.warn("CPU temperature metric closed:", error));
325 this.temperature_channel.addEventListener("message", this.onTemperatureUpdate);
326 }
327
328 // requires sudo access in order to sample every cgroup
329 // limited access only allows sampling of current user's cgroups
330 if (!cockpit.hidden && (this.privileged_channel === null)) {
331 this.privileged_channel = cockpit.channel({ superuser: "try", payload: "metrics1", source: "internal", interval: INTERVAL, metrics: PRIVILEGED_METRICS });
332 this.privileged_channel.addEventListener("message", this.onPrivilegedMetricsUpdate);
333 }
334
335 if (!cockpit.hidden && this.metrics_channel === null) {
336 this.metrics_channel = cockpit.channel({ payload: "metrics1", source: "internal", interval: INTERVAL, metrics: CURRENT_METRICS });
337 this.metrics_channel.addEventListener("message", this.onMetricsUpdate);
338 }
339 }
340
341 updateLoad() {
342 cockpit.file("/proc/loadavg").read()
343 .then(content => {
344 // format: three load averages, then process counters; e.g.: 0.67 1.00 0.78 2/725 87151
345 this.setState({ loadAvg: content.split(' ').slice(0, 3) });
346 // update it again regularly
347 window.setTimeout(this.updateLoad, 5000);
348 })
349 .catch(ex => {
350 console.warn("Failed to read /proc/loadavg:", ex.toString());
351 this.setState({ loadAvg: null });
352 });
353 }
354
355 onTemperatureUpdate(event, message) {
356 debug("current CPU temperature message", message);
357 const data = JSON.parse(message);
358
359 if (!Array.isArray(data)) {
360 return;
361 }
362
363 data.forEach(temperatureSamples => decompress_samples(temperatureSamples, this.temperatureSamples));
364
365 if (this.temperatureSamples[0].length > 0) {
366 this.cpuTemperature = Math.round(Math.max(...this.temperatureSamples[0]));
367 } else {
368 // close the channel when bridge couldn't sample temperature
369 this.temperature_channel.close("No samples received");
370 return;
371 }
372
373 if (this.cpuTemperature <= 80) {
374 this.cpuTemperatureColors.textColor = "";
375 this.cpuTemperatureColors.iconColor = "";
376 this.cpuTemperatureColors.icon = null;
377 } else if (this.cpuTemperature < 95) {
378 this.cpuTemperatureColors.textColor = "text-color-warning";
379 this.cpuTemperatureColors.iconColor = "icon-color-warning";
380 this.cpuTemperatureColors.icon = <ExclamationTriangleIcon />;
381 } else {
382 this.cpuTemperatureColors.textColor = "text-color-critical";
383 this.cpuTemperatureColors.iconColor = "icon-color-critical";
384 this.cpuTemperatureColors.icon = <ExclamationCircleIcon />;
385 }
386 }
387
388 onMetricsUpdate(event, message) {
389 debug("current metrics message", message);
390 const data = JSON.parse(message);
391
392 // reset state on meta messages
393 if (!Array.isArray(data)) {
394 this.samples = [];
395 console.assert(data.metrics[7].name === 'network.interface.rx');
396 this.netInterfacesNames = data.metrics[7].instances.slice();
397 console.assert(data.metrics[9].name === 'cgroup.cpu.usage');
398 this.cgroupCPUNames = data.metrics[9].instances.slice();
399 this.cgroupMemoryNames = data.metrics[10].instances.slice();
400 console.assert(data.metrics[14].name === 'disk.dev.read');
401 this.disksNames = data.metrics[14].instances.slice();
402 console.assert(data.metrics[16].name === 'mount.total');
403 this.mountPoints = data.metrics[16].instances.slice();
404 debug("metrics message was meta, new net instance names", JSON.stringify(this.netInterfacesNames));
405 return;
406 }
407
408 data.forEach(samples => decompress_samples(samples, this.samples));
409
410 const newState = {};
411 // CPU metrics are in ms/s; divide by 10 to get percentage
412 if (typeof this.samples[0] === 'number') {
413 const cpu = Math.round((this.samples[0] + this.samples[1] + this.samples[2]) / 10 / numCpu);
414 newState.cpuUsed = cpu;
415 }
416
417 newState.memUsed = this.samples[3];
418 newState.swapUsed = this.samples[4];
419
420 if (typeof this.samples[5] === 'number')
421 newState.disksRead = this.samples[5];
422 if (typeof this.samples[6] === 'number')
423 newState.disksWritten = this.samples[6];
424
425 newState.netInterfacesRx = this.samples[7];
426 newState.netInterfacesTx = this.samples[8];
427
428 // Collect CPU cores
429 newState.cpuCoresUsed = [];
430 if (this.samples[11] && this.samples[11].length == this.samples[12].length && this.samples[12].length == this.samples[13].length) {
431 for (let i = 0; i < this.samples[11].length; i++) {
432 // CPU cores metrics are in ms/s; divide by 10 to get percentage
433 newState.cpuCoresUsed[i] = Math.round((this.samples[11][i] + this.samples[12][i] + this.samples[13][i]) / 10);
434 }
435 }
436
437 // return [ { [key, value, is_user, is_container, userid | cgroup] } ] list of the biggest n values
438 const n_biggest = (names, values, n) => {
439 const merged = [];
440 names.forEach((k, i) => {
441 const v = values[i];
442 // filter out invalid values, the empty (root) cgroup, non-services
443 if (k.endsWith('.service') && typeof v === 'number' && v != 0) {
444 const is_user = k.match(/^user.*user@\d+\.service.+/);
445 const label = k.replace(/.*\//, '').replace(/\.service$/, '');
446 // only keep cgroup basenames, and drop redundant .service suffix
447 merged.push([label, v, is_user, false, k]);
448 }
449 // filter out podman containers, but only for the logged in
450 // user or root user if the user is privileged. Other users
451 // containers will show up under the user@uid cgroup
452 const matches = k.match(podmanCgroupRe);
453 if (matches && v) {
454 let is_user = false;
455 let uid = 0;
456 const containerid = matches.groups.containerid;
457 const umatches = k.match(useridCgroupRe);
458 if (umatches) {
459 is_user = true;
460 uid = parseInt(umatches.groups.userid);
461 }
462
463 if (uid === 0 || this.state.userid == uid) {
464 merged.push([containerid, v, is_user, true, uid]);
465 }
466 }
467 });
468 merged.sort((a, b) => b[1] - a[1]);
469 return merged.slice(0, n);
470 };
471
472 // top 5 CPU and memory consuming systemd units
473 const topServicesCPU = n_biggest(this.cgroupCPUNames, this.samples[9], 5);
474 newState.topServicesCPU = topServicesCPU.map(
475 ([key, value, is_user, is_container, userid]) => this.cgroupRow(key, is_user, is_container, userid, Number(value / 10 / numCpu).toFixed(1)) // usec/s → percent
476 );
477
478 const topServicesMemory = n_biggest(this.cgroupMemoryNames, this.samples[10], 5);
479 newState.topServicesMemory = topServicesMemory.map(
480 ([key, value, is_user, is_container, userid]) => this.cgroupRow(key, is_user, is_container, userid, cockpit.format_bytes(value))
481 );
482
483 const notMappedContainers = topServicesMemory.concat(topServicesCPU).filter(([key, value, is_user, is_container, userid]) => is_container && this.getCachedPodName(userid, key) === undefined);
484 if (notMappedContainers.length !== 0) {
485 this.update_podman_name_mapping(notMappedContainers);
486 }
487
488 const mountsTotal = this.samples[16];
489 const mountsUsed = this.samples[17];
490 newState.mounts = mountsTotal.map((mountTotal, i) => {
491 return {
492 target: this.mountPoints[i],
493 size: mountTotal,
494 avail: mountTotal - mountsUsed[i],
495 use: Math.round(mountsUsed[i] / mountTotal * 100),
496 };
497 });
498
499 this.setState(newState);
500 }
501
502 onPrivilegedMetricsUpdate(event, message) {
503 debug("process metrics message", message);
504 const data = JSON.parse(message);
505
506 if (!Array.isArray(data)) {
507 this.cgroupDiskNames = data.metrics[0].instances.slice();
508 return;
509 }
510
511 data.forEach(privilegedSamples => decompress_samples(privilegedSamples, this.privilegedSamples));
512
513 // return [ name, read, write, isUser, isContainer, uid | cgroup ]
514 const n_biggest = (n, names, valuesA, valuesB) => {
515 const merged = [];
516 const userSlices = {};
517 names.forEach((name, i) => {
518 // filter out invalid values, the empty (root) cgroup, non-services
519 if (name.endsWith('.service')) {
520 // only keep cgroup basenames, and drop redundant .service suffix
521 const label = name.replace(/.*\//, '').replace(/\.service$/, '');
522 const isUser = name.match(useridCgroupRe);
523 merged.push([label, valuesA[i], valuesB[i], isUser, false, name]);
524 return;
525 }
526
527 // filter out podman containers, but only for the logged in
528 // user or root user if the user is privileged. Other users
529 // containers will show up under the user@uid cgroup
530 const matches = name.match(/libpod-(?<containerid>[a-z|0-9]{64})\.scope/);
531 if (matches && valuesA[i] !== undefined && valuesB[i] !== undefined) {
532 const containerid = matches.groups.containerid;
533 const umatches = name.match(useridCgroupRe);
534 const isUser = !!umatches;
535 const uid = parseInt(umatches?.groups.userid) || 0;
536
537 if (uid === 0 || this.state.userid == uid) {
538 merged.push([containerid, valuesA[i], valuesB[i], isUser, true, uid]);
539 return;
540 }
541 }
542
543 // combine user slices into user@ID
544 // { name: [ read, write ] }
545 const umatches = name.match(useridCgroupRe);
546 if (umatches) {
547 if (userSlices[umatches.groups.userid] === undefined) {
548 userSlices[umatches.groups.userid] = [valuesA[i], valuesB[i]];
549 } else {
550 userSlices[umatches.groups.userid][0] += valuesA[i];
551 userSlices[umatches.groups.userid][1] += valuesB[i];
552 }
553 }
554 });
555
556 Object.keys(userSlices).forEach((key) => {
557 merged.push(["user@" + key, userSlices[key][0], userSlices[key][1], false, false]);
558 });
559
560 // sort by overall (read + write) disk usage
561 merged.sort((a, b) => (b[1] + b[2]) - (a[1] + a[2]));
562 return merged.slice(0, n);
563 };
564
565 const newState = {};
566
567 const topServicesDiskIO = n_biggest(5, this.cgroupDiskNames, this.privilegedSamples[0], this.privilegedSamples[1]);
568 newState.topServicesDiskIO = topServicesDiskIO.filter(([_, read, write, ..._rest]) => read !== 0 || write !== 0).map(([name, read, write, isUser, isContainer, uid]) => {
569 return this.cgroupRow(name, isUser, isContainer, uid, read > 1 ? cockpit.format_bytes_per_sec(read) : 0, write > 1 ? cockpit.format_bytes_per_sec(write) : 0);
570 });
571
572 this.setState(newState);
573 }
574
575 getCachedPodName = (uid, containerid) => this.state.podNameMapping[uid] && this.state.podNameMapping[uid][containerid];
576
577 cgroupRow = (name, is_user, is_container, uid, ...values) => {
578 const podman_installed = cockpit.manifests?.podman;
579
580 const cgroupClickHandler = (name, isUser, isContainer, uid) => {
581 if (isContainer) {
582 const containerName = this.getCachedPodName(uid, name);
583 if (containerName) {
584 cockpit.jump("/podman#/?name=" + containerName);
585 } else {
586 cockpit.jump("/podman");
587 }
588 } else {
589 cockpit.jump("/system/services#/" + name + ".service" + (isUser ? "?owner=user" : ""));
590 }
591 };
592
593 let name_text = (
594 <Button variant="link" isInline isBlock component="a" key={name}
595 onClick={() => cgroupClickHandler(name, is_user, is_container, uid)}
596 isDisabled={is_container && !podman_installed}>
597 <TableText wrapModifier="truncate">
598 {is_container ? _("pod") + " " + (this.getCachedPodName(uid, name) || name.substring(0, 12)) : name}
599 </TableText>
600 </Button>
601 );
602 if (is_container && !podman_installed) {
603 name_text = (
604 <Tooltip content={_("cockpit-podman is not installed")} key={name + "_tooltip"}>
605 <div>
606 {name_text}
607 </div>
608 </Tooltip>);
609 }
610
611 const values_text = values.map((value, idx) => {
612 return <TableText key={idx} wrapModifier="nowrap">{value}</TableText>;
613 });
614
615 return [name_text, ...values_text];
616 };
617
618 /**
619 * Look up the container names using podman ps for the given cgroups.
620 */
621 update_podman_name_mapping = cgroups => {
622 // New mapping state
623 const podNameMapping = {};
624
625 const promises = cgroups.map(([containerid, value, is_user, is_container, userid]) => {
626 if (!(userid in podNameMapping)) {
627 podNameMapping[userid] = {};
628 }
629 // Always initialize the cache for when we hit an error.
630 podNameMapping[userid][containerid] = null;
631
632 if ((userid === 0 && !superuser.allowed) && userid !== this.state.userid) {
633 return null;
634 }
635 return cockpit.spawn(["podman", "ps", "--format", "json"], { superuser: userid === 0 ? "required" : null })
636 .then(result => [result, userid]);
637 }).filter(prom => prom !== null);
638
639 Promise.all(promises).then(results => {
640 for (const [output, uid] of results) {
641 try {
642 const containers = JSON.parse(output);
643 for (const container of containers) {
644 podNameMapping[uid][container.Id] = container.Names[0];
645 }
646 } catch (err) {
647 console.error("podman ps outputs invalid JSON", err.toString());
648 }
649 }
650 })
651 .catch(err => console.error("could not obtain podman names:", err))
652 .finally(() => this.setState(prevState => ({ podNameMapping: { ...prevState.podNameMapping, ...podNameMapping } })));
653 };
654
655 render() {
656 const memUsedFraction = memTotal ? this.state.memUsed / memTotal : 0;
657 const memAvail = memTotal ? (memTotal - this.state.memUsed) : 0;
658 const num_cpu_str = cockpit.format(cockpit.ngettext("$0 CPU", "$0 CPUs", numCpu), numCpu);
659
660 const netIO = this.netInterfacesNames.map((iface, i) => [
661 <Button variant="link" isInline onClick={() => cockpit.jump(`/network#/${iface}`) } key={iface}>{iface}</Button>,
662 this.state.netInterfacesRx[i] >= 1 ? cockpit.format_bytes_per_sec(this.state.netInterfacesRx[i]) : "0",
663 this.state.netInterfacesTx[i] >= 1 ? cockpit.format_bytes_per_sec(this.state.netInterfacesTx[i]) : "0",
664 ]);
665
666 let swapProgress;
667
668 if (swapTotal) {
669 const swapUsedFraction = this.state.swapUsed / swapTotal;
670 const swapAvail = swapTotal - this.state.swapUsed;
671 swapProgress = (
672 <Tooltip content={ cockpit.format(_("$0 total"), cockpit.format_bytes(swapTotal)) } position="bottom">
673 <Progress
674 id="current-swap-usage"
675 title={ _("Swap") }
676 value={this.state.swapUsed}
677 className="pf-m-sm"
678 min={0} max={swapTotal}
679 variant={swapUsedFraction > 0.9 ? ProgressVariant.danger : swapUsedFraction >= 0.8 ? ProgressVariant.warning : null}
680 label={ cockpit.format(_("$0 available"), cockpit.format_bytes(swapAvail)) } />
681 </Tooltip>);
682 }
683
684 let cores = null;
685 let topCore = null;
686 let allCpus = null;
687 let cpu_label = null;
688 if (this.state.cpuCoresUsed.length > 1) {
689 const top_cores = this.state.cpuCoresUsed.map((v, i) => [i, v]).sort((a, b) => b[1] - a[1])
690 .slice(0, 16);
691 cores = (<Grid className='cpu-all' component='dl'>
692 {top_cores.map(c =>
693 <React.Fragment key={c[0]}>
694 <GridItem component='dt'>{ cockpit.format(_("Core $0"), c[0]) }</GridItem>
695 <GridItem component='dd'>{c[1]}%</GridItem>
696 </React.Fragment>)
697 }
698 </Grid>);
699
700 cpu_label = (
701 <Flex spaceItems={{ default: 'spaceItemsNone' }} justifyContent={{ default: 'justifyContentFlexEnd' }}>
702 <FlexItem>&nbsp;{ cockpit.format(_("average: $0%"), this.state.cpuUsed) }</FlexItem>
703 <FlexItem>&nbsp;{ cockpit.format(_("max: $0%"), top_cores[0][1]) }</FlexItem>
704 </Flex>);
705
706 topCore = <Progress
707 aria-label={_("Current top CPU usage")}
708 id="current-top-cpu-usage"
709 value={top_cores[0][1]}
710 className="current-top-cpu-usage pf-m-sm"
711 min={0} max={100}
712 variant={ top_cores[0][1] > 90 ? ProgressVariant.danger : top_cores[0][1] >= 80 ? ProgressVariant.warning : ProgressVariant.info }
713 measureLocation="none" />;
714
715 allCpus = (
716 <Popover minWidth={0} aria-label={ _("View all CPUs") } bodyContent={cores}>
717 <Button variant="link" className='pf-v6-u-font-size-sm'>{ _("View all CPUs") }</Button>
718 </Popover>);
719 } else {
720 cpu_label = this.state.cpuUsed + '%';
721 }
722
723 const disksUsage = (this.disksNames.length > 0 && this.samples[14] && this.samples[15])
724 ? (
725 this.disksNames.map((name, i) => [
726 name,
727 this.samples[14][i] >= 1 ? cockpit.format_bytes_per_sec(this.samples[14][i]) : "0",
728 this.samples[15][i] >= 1 ? cockpit.format_bytes_per_sec(this.samples[15][i]) : "0",
729 ])
730 )
731 : [];
732
733 let allDisks = null;
734 const rowPropsDisks = row => ({ 'device-name': row[0] });
735 const diskColumns = [_("Device"), _("Read"), _("Write")];
736 if (disksUsage.length > 1) {
737 const disksTableContent = (
738 <Table
739 variant={TableVariant.compact}
740 gridBreakPoint={TableGridBreakpoint.gridLg}
741 borders={false}
742 aria-label={ _("Disks usage") }>
743 <Thead>
744 <Tr>{diskColumns.map(col => <Th key={col}>{col}</Th>)}</Tr>
745 </Thead>
746 <Tbody className="pf-v6-m-tabular-nums disks-nowrap">
747 {make_rows(disksUsage, rowPropsDisks, diskColumns)}
748 </Tbody>
749 </Table>
750 );
751
752 allDisks = (
753 <Popover minWidth={0} aria-label={ _("View all disks") } bodyContent={disksTableContent}>
754 <Button variant="link" className='pf-v6-u-font-size-sm'>{ _("View per-disk throughput") }</Button>
755 </Popover>
756 );
757 }
758
759 // first element is the jump button, key is interface name
760 const rowPropsIface = row => ({ 'data-interface': row[0].key });
761 const rowPropsDiskIO = row => ({ 'cgroup-name': row[0] });
762 const topServicesCPUColumns = [_("Service"), "%"];
763 const topServicesMemoryColumns = [_("Service"), _("Used")];
764 const ifaceColumns = [_("Interface"), _("In"), _("Out")];
765
766 return (
767 <Gallery className="current-metrics" hasGutter>
768 <Card id="current-metrics-card-cpu">
769 <CardHeader className='align-baseline'>
770 <CardTitle>{ _("CPU") }</CardTitle>
771 { this.cpuTemperature !== null &&
772 <span className="temperature">
773 <span className={this.cpuTemperatureColors.iconColor}>
774 {this.cpuTemperatureColors.icon}
775 </span>
776 &nbsp;
777 <span className={this.cpuTemperatureColors.textColor}>
778 { cockpit.format("$0 °C", this.cpuTemperature) }
779 </span>
780 </span> }
781 </CardHeader>
782 <CardBody>
783 <div className="progress-stack-no-space">
784 <Progress
785 id="current-cpu-usage"
786 value={this.state.cpuUsed}
787 className="current-cpu-usage pf-m-sm"
788 min={0} max={100}
789 variant={ this.state.cpuUsed > 90 ? ProgressVariant.danger : this.state.cpuUsed >= 80 ? ProgressVariant.warning : null }
790 title={ num_cpu_str }
791 label={ cpu_label } />
792 {topCore}
793 {allCpus}
794 </div>
795
796 { this.state.loadAvg &&
797 <DescriptionList className="pf-m-horizontal-on-sm">
798 <DescriptionListGroup>
799 <DescriptionListTerm>{ _("Load") }</DescriptionListTerm>
800 <DescriptionListDescription id="load-avg">
801 <Flex spaceItems={{ default: 'spaceItemsXs' }}>
802 <FlexItem>{ _("1 min") }:&nbsp;{ this.state.loadAvg[0] },</FlexItem>
803 <FlexItem>{ _("5 min") }:&nbsp;{ this.state.loadAvg[1] },</FlexItem>
804 <FlexItem>{ _("15 min") }:&nbsp;{ this.state.loadAvg[2] }</FlexItem>
805 </Flex>
806 </DescriptionListDescription>
807 </DescriptionListGroup>
808 </DescriptionList> }
809
810 { this.state.topServicesCPU.length > 0 &&
811 <Table
812 variant={TableVariant.compact}
813 gridBreakPoint={TableGridBreakpoint.none}
814 borders={false}
815 aria-label={ _("Top 5 CPU services") }>
816 <Thead>
817 <Tr>
818 <Th width={80}>{_("Service")}</Th>
819 <Th>%</Th>
820 </Tr>
821 </Thead>
822 <Tbody>
823 {make_rows(this.state.topServicesCPU, undefined, topServicesCPUColumns)}
824 </Tbody>
825 </Table> }
826 </CardBody>
827 </Card>
828
829 <Card>
830 <CardTitle>{ _("Memory") }</CardTitle>
831 <CardBody>
832 <div className="progress-stack">
833 <Tooltip
834 content={ cockpit.format(_("$0 total"), cockpit.format_bytes(memTotal)) }
835 position="bottom">
836 <Progress
837 id="current-memory-usage"
838 title={ _("RAM") }
839 value={memTotal ? this.state.memUsed : undefined}
840 className="pf-m-sm"
841 min={0} max={memTotal}
842 variant={memUsedFraction > 0.9 ? ProgressVariant.danger : memUsedFraction >= 0.8 ? ProgressVariant.warning : null}
843 label={ memAvail ? cockpit.format(_("$0 available"), cockpit.format_bytes(memAvail)) : "" } />
844 </Tooltip>
845 {swapProgress}
846 </div>
847
848 { this.state.topServicesMemory.length > 0 &&
849 <Table
850 variant={TableVariant.compact}
851 gridBreakPoint={TableGridBreakpoint.none}
852 borders={false}
853 aria-label={ _("Top 5 memory services") }>
854 <Thead>
855 <Tr>
856 <Th width={80}>{_("Service")}</Th>
857 <Th>{_("Used")}</Th>
858 </Tr>
859 </Thead>
860 <Tbody>
861 {make_rows(this.state.topServicesMemory, undefined, topServicesMemoryColumns)}
862 </Tbody>
863 </Table> }
864 </CardBody>
865 </Card>
866
867 <Card id="current-metrics-card-disks">
868 <CardTitle>{ _("Disks") }</CardTitle>
869 <CardBody>
870 <DescriptionList isHorizontal columnModifier={{ default: '2Col' }}>
871 <DescriptionListGroup>
872 <DescriptionListTerm>{ _("Read") }</DescriptionListTerm>
873 <DescriptionListDescription id="current-disks-read">{ this.state.disksRead >= 1 ? cockpit.format_bytes_per_sec(this.state.disksRead) : "0" }</DescriptionListDescription>
874 </DescriptionListGroup>
875 <DescriptionListGroup>
876 <DescriptionListTerm>{ _("Write") }</DescriptionListTerm>
877 <DescriptionListDescription id="current-disks-write">{ this.state.disksWritten >= 1 ? cockpit.format_bytes_per_sec(this.state.disksWritten) : "0" }</DescriptionListDescription>
878 </DescriptionListGroup>
879 </DescriptionList>
880 <div className="all-disks-no-gap">
881 {allDisks}
882 </div>
883 <div id="current-disks-usage" className="progress-stack"> {
884 this.state.mounts.map(info => {
885 let progress = (
886 <Progress
887 data-disk-usage-target={info.target}
888 value={info.use} min={0} max={100}
889 className="pf-m-sm"
890 variant={info.use > 90 ? ProgressVariant.danger : info.use >= 80 ? ProgressVariant.warning : null}
891 title={info.target}
892 label={ cockpit.format(_("$0 free"), cockpit.format_bytes(info.avail)) } />
893 );
894 if (cockpit.manifests?.storage)
895 progress = <Button variant="link" isInline onClick={() => cockpit.jump("/storage") }>{progress}</Button>;
896
897 return (
898 <Tooltip
899 key={info.target}
900 content={ cockpit.format(_("$0 total"), cockpit.format_bytes(info.size)) }
901 position="bottom">
902 {progress}
903 </Tooltip>
904 );
905 })
906 }
907 </div>
908 { this.state.topServicesDiskIO.length > 0 &&
909 <Table
910 variant={TableVariant.compact}
911 gridBreakPoint={TableGridBreakpoint.none}
912 borders={false}
913 aria-label={ _("Top 5 disk usage services") }>
914 <Thead>
915 <Tr>
916 <Th width={50}>{_("Service")}</Th>
917 <Th>{_("Read")}</Th>
918 <Th>{_("Write")}</Th>
919 </Tr>
920 </Thead>
921 <Tbody className="pf-v6-m-tabular-nums">
922 {make_rows(this.state.topServicesDiskIO, rowPropsDiskIO, [_("Service"), _("Read"), _("Write")])}
923 </Tbody>
924 </Table> }
925 </CardBody>
926 </Card>
927
928 <Card className="current-metrics-network">
929 <CardTitle>{ _("Network") }</CardTitle>
930 <CardBody>
931 <Table
932 variant={TableVariant.compact}
933 // FIXME: If we can make the table less wide, then we can switch from gridLg to none
934 // and (possibly) dropping (at least some of) the font size overrides
935 // this would require breaking out the units/s into its own row
936 gridBreakPoint={TableGridBreakpoint.gridLg}
937 borders={false}
938 aria-label={ _("Network usage") }>
939 <Thead>
940 <Tr>{ifaceColumns.map(col => <Th key={col}>{col}</Th>)}</Tr>
941 </Thead>
942 <Tbody className="network-nowrap-shrink">
943 {make_rows(netIO, rowPropsIface, ifaceColumns)}
944 </Tbody>
945 </Table>
946 </CardBody>
947 </Card>
948 </Gallery>
949 );
950 }
951 }
952
953 const SvgGraph = ({ data, resource, have_sat }) => {
954 const dataPoints = key => (
955 "0 0, " + // start polygon at (0, 0)
956 data.map((samples, index) => (samples && typeof samples[key] === 'number') ? parseInt(samples[key] * 100).toString() + "% " + (((index / SVG_YMAX) * 100).toString() + "%") : "").join(", ") +
957 ", 0 " + ((data.length - 1) / SVG_YMAX) * 100 + "%" // close polygon
958 );
959
960 return (
961 <>
962 <div
963 className="polygon polygon-use"
964 style={{ "--points": dataPoints("use_" + resource) }}
965 points={dataPoints("use_" + resource)}
966 />
967 { have_sat && <div
968 className="polygon polygon-sat"
969 style={{ "--points": dataPoints("sat_" + resource) }}
970 points={dataPoints("sat_" + resource)}
971 /> }
972 </>
973 );
974 };
975
976 class MetricsMinute extends React.Component {
977 constructor(props) {
978 super(props);
979
980 this.state = {
981 logs: null,
982 logsUrl: null,
983 };
984 this.onHover = this.onHover.bind(this);
985 this.findLogs = this.findLogs.bind(this);
986
987 this.spikesButtonRef = createRef();
988 }
989
990 componentDidMount() {
991 if (this.props.isExpanded && this.props.events)
992 this.findLogs(this.props.events.start - 4, this.props.events.end + 4); // +- 20s
993 }
994
995 onHover(ev) {
996 // FIXME - throttle debounce this
997 const bounds = ev.target.getBoundingClientRect();
998 const offsetY = (ev.clientY - bounds.y) / bounds.height;
999 const indexOffset = Math.floor((1 - offsetY) * SAMPLES_PER_MIN);
1000 const sample = this.props.rawData[indexOffset];
1001 if (!sample)
1002 return;
1003
1004 const time = this.props.startTime + this.props.minute * 60000 + indexOffset * INTERVAL;
1005 let tooltip = timeformat.timeSeconds(time) + "\n\n";
1006 Object.entries(sample).forEach(([t, v]) => {
1007 if (v !== null && v !== undefined)
1008 tooltip += `${RESOURCES[t].name}: ${RESOURCES[t].format(v)}\n`;
1009 });
1010 ev.target.setAttribute("title", tooltip);
1011 }
1012
1013 findLogs(start, end) {
1014 const timestamp = this.props.startTime + (this.props.minute * 60000);
1015 const start_minute = Math.floor(start / SAMPLES_PER_MIN);
1016 const start_second = (start - (start_minute * SAMPLES_PER_MIN)) * (60 / SAMPLES_PER_MIN);
1017 const end_minute = Math.floor(end / SAMPLES_PER_MIN);
1018 const end_second = (end - (end_minute * SAMPLES_PER_MIN)) * (60 / SAMPLES_PER_MIN);
1019
1020 const time = new Date(timestamp);
1021 time.setUTCMinutes(start_minute);
1022 time.setUTCSeconds(start_second);
1023 const since = formatUTC_ISO(time);
1024
1025 time.setUTCMinutes(end_minute);
1026 time.setUTCSeconds(end_second);
1027 const until = formatUTC_ISO(time);
1028
1029 const match = { priority: "info", since, until, follow: false, count: 10 };
1030 const journalctl = journal.journalctl(match);
1031
1032 const out = new JournalOutput(match);
1033 out.render_day_header = () => { return null };
1034 const render = journal.renderer(out);
1035
1036 journalctl.stream(entries => {
1037 entries.forEach(entry => render.prepend(entry));
1038 render.prepend_flush();
1039 })
1040 .then(() => {
1041 let logsUrl;
1042 if (out.logs.length === 0) {
1043 // without logs, increase verbosity and time range (-15 mins to + 1 min)
1044 const since = formatUTC_ISO(new Date(timestamp - 15 * 60000));
1045 const until = formatUTC_ISO(new Date(timestamp + 60000));
1046 logsUrl = `/system/logs/#/?priority=debug&since=${encodeURIComponent(since)}&until=${encodeURIComponent(until)}&follow=false`;
1047 } else {
1048 // with logs, show the exact minute and same log level as on the metrics page
1049 logsUrl = `/system/logs/#/?priority=info&since=${encodeURIComponent(since)}&until=${encodeURIComponent(until)}&follow=false`;
1050 }
1051
1052 this.setState({ logs: out.logs, logsUrl });
1053 });
1054 }
1055
1056 render() {
1057 const first = this.props.data.find(i => i !== null);
1058
1059 const graphs = Object.keys(this.props.selectedVisibility).filter(itm => this.props.selectedVisibility[itm]).map(resource => {
1060 // not all resources have a saturation metric
1061 let have_sat = !!RESOURCES["sat_" + resource];
1062
1063 // If there is no swap, don't render it
1064 if (resource === "memory" && !swapTotal)
1065 have_sat = false;
1066
1067 let graph = null;
1068 if (this.props.events) {
1069 // render full SVG graphs for "expanded" minutes with events
1070 graph = <SvgGraph key={resource} data={this.props.data} resource={resource} have_sat={have_sat} />;
1071 } else if (first) {
1072 // render simple bars for "compressed" minutes without events
1073 graph = <>
1074 <div className="polygon-use compressed" style={{ "--utilization": first["use_" + resource] || 0 }} />
1075 { have_sat && <div className="polygon-sat compressed" style={{ "--saturation": first["sat_" + resource] || 0 }} /> }
1076 </>;
1077 }
1078
1079 return (
1080 <div
1081 key={ resource + this.props.startTime + this.props.minute }
1082 className={ ("metrics-data metrics-data-" + resource) + (first ? " valid-data" : " empty-data") + (have_sat ? " have-saturation" : "") }
1083 aria-hidden="true"
1084 { ...(this.props.isExpanded && { onMouseMove: this.onHover }) }
1085 >
1086 {graph}
1087 </div>
1088 );
1089 });
1090
1091 let desc;
1092 if (this.props.isExpanded && this.props.booted) {
1093 const timestamp = this.props.startTime + (this.props.minute * 60000);
1094 desc = (
1095 <div className="metrics-events">
1096 <time>{ timeformat.time(timestamp) }</time>
1097 <span className="spikes_count" />
1098 <span className="spikes_info">
1099 <span className="type">
1100 {_("Boot")}
1101 </span>
1102 </span>
1103 </div>
1104 );
1105 } else if (this.props.isExpanded && this.props.events) {
1106 const timestamp = this.props.startTime + (this.props.minute * 60000);
1107
1108 const logsPanel = (
1109 <>
1110 {(this.state.logs?.length && this.state.logsUrl) && <Button variant="secondary" onClick={e => cockpit.jump(this.state.logsUrl)}>{_("View detailed logs")}</Button>}
1111 <div className="cockpit-log-panel">
1112 {this.state.logs?.length ? this.state.logs : _("No log entries")}
1113 </div>
1114 </>
1115 );
1116
1117 const resourceDesc = (
1118 <span className="type">
1119 {this.props.events.events.map(t => RESOURCES[t].event_description).join(", ")}
1120 </span>
1121 );
1122 desc = (
1123 <>
1124 <div className="metrics-events">
1125 <time>{ timeformat.time(timestamp) }</time>
1126 <span className="spikes_count" />
1127 {this.state.logs?.length > 0
1128 ? <Button
1129 ref={this.spikesButtonRef}
1130 variant="link" isInline
1131 className="spikes_info">
1132 {resourceDesc}
1133 </Button>
1134 : <span className="spikes_info">{resourceDesc}</span>}
1135 </div>
1136 {this.state.logs?.length > 0 && <Popover position="right" hasAutoWidth className="metrics-events-popover" bodyContent={logsPanel} triggerRef={this.spikesButtonRef} />}
1137 </>
1138 );
1139 }
1140
1141 return (
1142 <div className="metrics-minute" data-minute={this.props.minute}>
1143 { this.props.isExpanded && desc }
1144 <div className="metrics-graphs">
1145 { graphs }
1146 </div>
1147 </div>
1148 );
1149 }
1150 }
1151
1152 class MetricsHour extends React.Component {
1153 constructor(props) {
1154 super(props);
1155
1156 this.state = {
1157 minuteGraphs: [],
1158 minute_events: {},
1159 isHourExpanded: false,
1160 dataItems: 0,
1161 };
1162
1163 this.updateGraphs = this.updateGraphs.bind(this);
1164 }
1165
1166 componentDidMount() {
1167 this.updateGraphs(this.props.data, this.props.startTime, this.props.selectedVisibility);
1168 }
1169
1170 shouldComponentUpdate(nextProps, nextState) {
1171 if (this.state.dataItems !== nextProps.data.length ||
1172 this.state.isHourExpanded !== nextState.isHourExpanded ||
1173 this.props.startTime !== nextProps.startTime ||
1174 this.props.boots !== nextProps.boots ||
1175 Object.keys(this.props.selectedVisibility).some(itm => this.props.selectedVisibility[itm] != nextProps.selectedVisibility[itm])) {
1176 this.updateGraphs(nextProps.data, nextProps.startTime, nextProps.selectedVisibility, nextState.isHourExpanded);
1177 return false;
1178 }
1179
1180 return true;
1181 }
1182
1183 // data: type → SAMPLES_PER_H objects from startTime
1184 updateGraphs(data, startTime, selectedVisibility, isHourExpanded) {
1185 const filteredData = data.map(sample => Object.keys(sample)
1186 .filter(key => selectedVisibility[key.split("_")[1]])
1187 .reduce((cur, key) => Object.assign(cur, { [key]: sample[key] }), {}));
1188 // Normalize data
1189 const normData = filteredData.map(sample => {
1190 if (sample === null)
1191 return null;
1192 const n = {};
1193 for (const type in sample)
1194 n[type] = (sample[type] !== null && sample[type] !== undefined) ? RESOURCES[type].normalize(sample[type]) : null;
1195 return n;
1196 });
1197
1198 // Count minutes to render
1199 let minutes = 60;
1200 if (this.props.clipLeading) {
1201 // When clipping of empty leading minutes is allowed, find the highest 5 minute interval with valid data
1202 let m = 55;
1203 for (; m >= 0; m = m - 5) {
1204 const dataOffset = m * SAMPLES_PER_MIN;
1205 const dataSlice = normData.slice(dataOffset, dataOffset + SAMPLES_PER_MIN * 5);
1206 if (dataSlice.some(i => i !== null && i !== undefined))
1207 break;
1208 }
1209 minutes = m + 5;
1210 }
1211
1212 // Compute spike events
1213 const minute_events = {};
1214 for (const type in RESOURCES) {
1215 let prev_val = data[0] ? data[0][type] : null;
1216 normData.forEach((samples, i) => {
1217 if (samples === null)
1218 return;
1219 const value = samples[type];
1220 // either high enough slope, or crossing the 80% threshold
1221 if (prev_val !== null && (value - prev_val > 0.25 || (prev_val < 0.75 && value >= 0.8))) {
1222 const minute = Math.floor(i / SAMPLES_PER_MIN);
1223 if (minute_events[minute] === undefined)
1224 minute_events[minute] = { events: [], start: i - 1 };
1225
1226 minute_events[minute].end = i;
1227
1228 // For every minute show each type of event max once
1229 if (minute_events[minute].events.indexOf(type) === -1)
1230 minute_events[minute].events.push(type);
1231 }
1232 prev_val = value;
1233 });
1234 }
1235
1236 const minuteGraphs = [];
1237
1238 for (let minute = minutes - 1; minute >= 0; --minute) {
1239 const dataOffset = minute * SAMPLES_PER_MIN;
1240 const dataSlice = normData.slice(dataOffset, dataOffset + SAMPLES_PER_MIN);
1241 const rawSlice = this.props.data.slice(dataOffset, dataOffset + SAMPLES_PER_MIN);
1242 const is_boot = this.props.boots.includes(minute);
1243
1244 minuteGraphs.push(
1245 <MetricsMinute
1246 isExpanded={isHourExpanded}
1247 key={minute}
1248 minute={minute}
1249 data={dataSlice}
1250 rawData={rawSlice}
1251 events={minute_events[minute]}
1252 startTime={this.props.startTime}
1253 selectedVisibility={selectedVisibility}
1254 booted={is_boot} />
1255 );
1256 }
1257
1258 this.setState((_, prevProps) => ({
1259 isHourExpanded,
1260 minute_events,
1261 minuteGraphs,
1262 dataItems: prevProps.data.length
1263 }));
1264 }
1265
1266 render() {
1267 const hourDesc = (
1268 <HourDescription
1269 minute_events={this.state.minute_events}
1270 onToggleHourExpanded={isHourExpanded => this.setState({ isHourExpanded })}
1271 startTime={this.props.startTime}
1272 isHourExpanded={this.state.isHourExpanded} />
1273 );
1274
1275 return (
1276 <div id={ "metrics-hour-" + this.props.startTime.toString() }
1277 className={"metrics-hour" + (!this.state.isHourExpanded ? " metrics-hour-compressed" : "")}>
1278 {hourDesc}
1279 {!this.state.isHourExpanded ? <div className="metrics-minutes">{this.state.minuteGraphs}</div> : this.state.minuteGraphs}
1280 </div>
1281 );
1282 }
1283 }
1284
1285 const HourDescription = ({ minute_events, isHourExpanded, onToggleHourExpanded, startTime }) => {
1286 const event_types = {};
1287 Object.keys(RESOURCES).forEach(t => { event_types[t] = 0 });
1288 Object.values(minute_events).forEach(event => { event.events.forEach(t => { event_types[t] += 1 }) });
1289 const spikes = Object.values(event_types).reduce((acc, event_type_count) => acc + event_type_count, 0);
1290 return (
1291 <span className={"metrics-events" + (isHourExpanded ? " metrics-events-hour-header-expanded" : "")}>
1292 {spikes > 0 &&
1293 <Button variant="plain" className="metrics-events-expander" onClick={() => onToggleHourExpanded(!isHourExpanded)} icon={isHourExpanded ? <AngleDownIcon /> : <Icon shouldMirrorRTL><AngleRightIcon /></Icon>} />}
1294 <time>{ timeformat.time(startTime) }</time>
1295 <Flex flexWrap={{ default: 'nowrap' }} spaceItems={{ default: 'spaceItemsSm' }} alignItems={{ default: 'alignItemsBaseline' }} className="spikes_count">
1296 {spikes >= 10 && <ResourcesFullIcon color="var(--resource-icon-color-full)" />}
1297 {spikes >= 5 && spikes < 10 && <ResourcesAlmostFullIcon color="var(--resource-icon-color-middle)" />}
1298 {spikes < 5 && spikes > 0 && <ResourcesAlmostEmptyIcon color="var(--resource-icon-color-empty)" />}
1299 <FlexItem>
1300 {spikes ? cockpit.format(cockpit.ngettext("$0 spike", "$0 spikes", spikes), spikes) : _("No events")}
1301 </FlexItem>
1302 </Flex>
1303 <span className="spikes_info">
1304 {spikes > 0 && Object.entries(event_types)
1305 .filter(([_, count]) => count > 0)
1306 .map(([event_type, count]) => cockpit.format("$0 $1", count, RESOURCES[event_type].event_description))
1307 .join(", ")}
1308 </span>
1309 </span>
1310 );
1311 };
1312
1313 // null means "not initialized yet"
1314 const invalidService = proxy => proxy.state === null;
1315 const runningService = proxy => ['running', 'starting'].indexOf(proxy.state) >= 0;
1316
1317 const wait_cond = (cond, objects) => {
1318 return new Promise((resolve, reject) => {
1319 const check = () => {
1320 if (cond()) {
1321 objects.forEach(o => o.removeEventListener("changed", check));
1322 resolve();
1323 }
1324 };
1325 objects.forEach(o => o.addEventListener("changed", check));
1326 check();
1327 });
1328 };
1329
1330 const PCPConfigDialog = ({
1331 firewalldRequest,
1332 s_pmlogger, s_pmproxy, s_redis, s_redis_server, s_valkey,
1333 packageInstallCallback,
1334 }) => {
1335 const Dialogs = useDialogs();
1336 const dialogInitialProxyValue = runningService(s_pmproxy) && (
1337 runningService(s_redis) || runningService(s_redis_server) || runningService(s_valkey));
1338 const [dialogError, setDialogError] = useState(null);
1339 const [dialogLoggerValue, setDialogLoggerValue] = useState(runningService(s_pmlogger));
1340 const [dialogProxyValue, setDialogProxyValue] = useState(dialogInitialProxyValue);
1341 const [pending, setPending] = useState(false);
1342 const [packageManager, setPackageManager] = useState(null);
1343
1344 useInit(() => getPackageManager().then(setPackageManager));
1345
1346 const handleInstall = async () => {
1347 // when enabling services, install missing packages on demand
1348 const missing = [];
1349 if (dialogLoggerValue && !s_pmlogger.exists) {
1350 missing.push(...await get_pcp_packages());
1351 }
1352 const redisExists = () => s_redis.exists || s_redis_server.exists || s_valkey.exists;
1353 if (dialogProxyValue && !redisExists()) {
1354 const os_release = await read_os_release();
1355 missing.push(get_manifest_config_matchlist("metrics", "redis_package", "redis",
1356 [os_release.PLATFORM_ID, os_release.ID]));
1357 }
1358
1359 if (missing.length > 0) {
1360 debug("PCPConfig: missing packages", JSON.stringify(missing), ", offering install");
1361 Dialogs.close();
1362 await install_dialog(missing);
1363 debug("PCPConfig: package installation successful");
1364 await wait_cond(() => (s_pmlogger.exists &&
1365 (!dialogProxyValue || (s_pmproxy.exists && redisExists()))),
1366 [s_pmlogger, s_pmproxy, s_redis, s_redis_server, s_valkey]);
1367 }
1368 };
1369
1370 const handleSave = () => {
1371 debug("PCPConfig handleSave(): dialogLoggerValue", dialogLoggerValue, "dialogInitialProxyValue", dialogInitialProxyValue, "dialogProxyValue", dialogProxyValue);
1372
1373 handleInstall()
1374 .then(() => {
1375 setPending(true);
1376
1377 let real_redis;
1378 let redis_name;
1379 if (s_valkey.exists && s_valkey.unit?.UnitFileState !== 'masked') {
1380 real_redis = s_valkey;
1381 redis_name = "valkey.service";
1382 } else if (s_redis_server.exists && s_redis_server.unit?.UnitFileState !== 'masked') {
1383 real_redis = s_redis_server;
1384 redis_name = "redis-server.service";
1385 } else {
1386 real_redis = s_redis;
1387 redis_name = "redis.service";
1388 }
1389
1390 const redis_enable_cmd = `mkdir -p /etc/systemd/system/pmproxy.service.wants; ln -sf ../${redis_name} /etc/systemd/system/pmproxy.service.wants/${redis_name}`;
1391 const redis_disable_cmd = `rm -f /etc/systemd/system/pmproxy.service.wants/${redis_name}; rmdir -p /etc/systemd/system/pmproxy.service.wants 2>/dev/null || true`;
1392 let action;
1393
1394 // enable/disable does a daemon-reload, which interferes with start on some distros; so don't run them in parallel
1395 if (dialogLoggerValue)
1396 action = s_pmlogger.start().then(() => s_pmlogger.enable());
1397 else
1398 action = s_pmlogger.stop().finally(() => s_pmlogger.disable());
1399
1400 if (dialogProxyValue !== null && dialogInitialProxyValue !== dialogProxyValue) {
1401 if (dialogProxyValue === true) {
1402 // pmproxy.service needs to (re)start *after* redis to recognize it
1403 action = action
1404 .then(() => real_redis.start())
1405 .then(() => s_pmproxy.restart())
1406 // turn redis into a dependency, as the metrics API requires it
1407 .then(() => cockpit.script(redis_enable_cmd, { superuser: "require", err: "message" }))
1408 .then(() => s_pmproxy.enable());
1409 } else {
1410 // don't stop redis here -- it's a shared service, other things may be using it
1411 action = action
1412 .then(() => s_pmproxy.stop())
1413 .then(() => cockpit.script(redis_disable_cmd, { superuser: "require", err: "message" }))
1414 .then(() => s_pmproxy.disable());
1415 }
1416 }
1417
1418 action
1419 .then(() => {
1420 Dialogs.close();
1421 if (dialogProxyValue && !dialogInitialProxyValue && firewalldRequest)
1422 firewalldRequest({ service: "pmproxy", title: _("Open the pmproxy service in the firewall to share metrics.") });
1423 else
1424 firewalldRequest(null);
1425 packageInstallCallback();
1426 })
1427 .catch(err => { packageInstallCallback(); setPending(false); setDialogError(err.toString()) });
1428 })
1429 .catch(() => null); // ignore cancel in install dialog
1430 };
1431
1432 return (
1433 <Modal position="top" variant="small" isOpen
1434 id="pcp-settings-modal"
1435 onClose={Dialogs.close}
1436 >
1437 <ModalHeader title={ _("Metrics settings") }
1438 description={
1439 <div className="pcp-settings-modal-text">
1440 { _("Performance Co-Pilot collects and analyzes performance metrics from your system.") }
1441
1442 <Button component="a" variant="link" href="https://docs.cockpit-project.org/cockpit-guide/latest/guide/feature-pcp.html"
1443 isInline
1444 target="_blank" rel="noopener noreferrer"
1445 icon={<ExternalLinkAltIcon />}>
1446 { _("Read more...") }
1447 </Button>
1448 </div>}
1449 />
1450 <ModalBody>
1451 <Stack hasGutter>
1452 { dialogError && <ModalError dialogError={ _("Failed to configure PCP") } dialogErrorDetail={dialogError} /> }
1453 <StackItem>
1454 <Switch id="switch-pmlogger"
1455 isChecked={dialogLoggerValue}
1456 isDisabled={!s_pmlogger.exists && !packageManager}
1457 label={
1458 <Flex>
1459 <FlexItem>{ _("Collect metrics") }</FlexItem>
1460 <Content>
1461 <Content component={ContentVariants.small}>(pmlogger.service)</Content>
1462 </Content>
1463 </Flex>
1464 }
1465 onChange={(_event, enable) => {
1466 // pmproxy needs pmlogger, auto-disable it
1467 setDialogLoggerValue(enable);
1468 if (!enable)
1469 setDialogProxyValue(false);
1470 }} />
1471
1472 <Switch id="switch-pmproxy"
1473 isChecked={dialogProxyValue}
1474 label={
1475 <Flex>
1476 <FlexItem>{ _("Export to network") }</FlexItem>
1477 <Content component={ContentVariants.small}>(pmproxy.service)</Content>
1478 </Flex>
1479 }
1480 isDisabled={ !dialogLoggerValue }
1481 onChange={(_event, enable) => setDialogProxyValue(enable)} />
1482 </StackItem>
1483 </Stack>
1484 </ModalBody>
1485 <ModalFooter>
1486 <Button variant='primary' onClick={handleSave} isDisabled={pending} isLoading={pending}>
1487 { _("Save") }
1488 </Button>
1489 <Button variant='link' className='btn-cancel' onClick={Dialogs.close}>
1490 {_("Cancel")}
1491 </Button>
1492 </ModalFooter>
1493 </Modal>);
1494 };
1495
1496 const PCPConfig = ({ buttonVariant, firewalldRequest }) => {
1497 const Dialogs = useDialogs();
1498 const [packageInstallStatus, setPackageInstallStatus] = useState(null);
1499
1500 const s_pmlogger = useObject(() => service.proxy("pmlogger.service"), null, []);
1501 const s_pmproxy = useObject(() => service.proxy("pmproxy.service"), null, []);
1502 // redis.service on Fedora/RHEL, redis-server.service on Debian/Ubuntu with an Alias=redis
1503 const s_redis = useObject(() => service.proxy("redis.service"), null, []);
1504 const s_redis_server = useObject(() => service.proxy("redis-server.service"), null, []);
1505 const s_valkey = useObject(() => service.proxy("valkey.service"), null, []);
1506
1507 useEvent(superuser, "changed");
1508 useEvent(s_pmlogger, "changed");
1509 useEvent(s_pmproxy, "changed");
1510 useEvent(s_redis, "changed");
1511 useEvent(s_redis_server, "changed");
1512 useEvent(s_valkey, "changed");
1513
1514 debug("PCPConfig s_pmlogger.state", s_pmlogger.state);
1515 debug("PCPConfig s_pmproxy state", s_pmproxy.state,
1516 "redis exists", s_redis.exists, "state", s_redis.state,
1517 "redis-server exists", s_redis_server.exists, "state", s_redis_server.state,
1518 "valkey exists", s_valkey.exists, "state", s_valkey.state);
1519
1520 if (!superuser.allowed)
1521 return null;
1522
1523 function show_dialog() {
1524 setPackageInstallStatus(null);
1525 Dialogs.show(<PCPConfigDialog firewalldRequest={firewalldRequest}
1526 s_pmlogger={s_pmlogger}
1527 s_pmproxy={s_pmproxy}
1528 s_redis={s_redis} s_redis_server={s_redis_server} s_valkey={s_valkey}
1529 packageInstallCallback={() => setPackageInstallStatus("done")} />);
1530 }
1531
1532 return (
1533 <Button variant={buttonVariant} icon={<CogIcon />}
1534 isDisabled={ invalidService(s_pmlogger) || invalidService(s_pmproxy) ||
1535 invalidService(s_redis) || invalidService(s_redis_server) || invalidService(s_valkey) }
1536 onClick={show_dialog}
1537 data-test-install-finished={packageInstallStatus}>
1538 { _("Metrics settings") }
1539 </Button>);
1540 };
1541
1542 class MetricsHistory extends React.Component {
1543 constructor(props) {
1544 super(props);
1545 // metrics data: hour timestamp → array of SAMPLES_PER_H objects of { type → value } or null
1546 this.data = {};
1547 // timestamp of the most recent sample that we got (for auto-refresh)
1548 this.most_recent = 0;
1549 // Oldest read data
1550 this.oldest_timestamp = 0;
1551 // Timestamp representing today midnight to calculate other days for date select
1552 this.today_midnight = null;
1553 this.columns = [["cpu", _("CPU")], ["memory", _("Memory")], ["disks", _("Disk I/O")], ["network", _("Network")]];
1554
1555 this.state = {
1556 hours: [], // available hours for rendering in descending order
1557 loading: true, // show loading indicator
1558 metricsAvailable: true,
1559 pmLoggerState: null,
1560 error: null,
1561 selectedDate: null,
1562 packageManager: null,
1563 isBeibootBridge: false,
1564 isPythonPCPInstalled: null,
1565 selectedVisibility: this.columns.reduce((a, v) => ({ ...a, [v[0]]: true }), {}),
1566 boots: [], // journalctl --list-boots as [{started: Date, ended: Date}]
1567 };
1568
1569 this.handleMoreData = this.handleMoreData.bind(this);
1570 this.handleSelect = this.handleSelect.bind(this);
1571 this.handleInstall = this.handleInstall.bind(this);
1572
1573 /* supervise pmlogger.service, to diagnose missing history */
1574 this.pmlogger_service = service.proxy("pmlogger.service");
1575 this.pmlogger_service.addEventListener("changed", () => {
1576 if (!invalidService(this.pmlogger_service) && this.pmlogger_service.state !== this.state.pmLoggerState) {
1577 // when it got enabled while the page is running (e.g. through Settings dialog), start data collection
1578 if (!this.state.metricsAvailable && runningService(this.pmlogger_service))
1579 this.initialLoadData();
1580 this.setState({ pmLoggerState: this.pmlogger_service.state });
1581 }
1582 });
1583
1584 // FIXME: load less up-front, load more when scrolling
1585 machine_info_promise.then(() => this.initialLoadData());
1586
1587 cockpit.addEventListener("visibilitychange", () => {
1588 // update history metrics when in auto-update mode
1589 if (!cockpit.hidden && this.history_refresh_timer)
1590 this.load_data(this.most_recent);
1591 });
1592 }
1593
1594 // load and render the last 24 hours (plus current one) initially; this needs numCpu initialized for correct scaling
1595 initialLoadData() {
1596 cockpit.spawn(["date", "+%s"])
1597 .then(out => {
1598 const now = parseInt(out.trim()) * 1000;
1599 const current_hour = Math.floor(now / MSEC_PER_H) * MSEC_PER_H;
1600 this.most_recent = current_hour;
1601 this.today_midnight = new Date(current_hour).setHours(0, 0, 0, 0);
1602
1603 const selectedDate = parseInt(cockpit.location.options.date) || this.today_midnight;
1604
1605 if (selectedDate !== this.today_midnight)
1606 this.load_data(selectedDate, 24 * SAMPLES_PER_H, true);
1607 else
1608 this.load_data(current_hour - LOAD_HOURS * MSEC_PER_H, undefined, true);
1609
1610 this.setState({
1611 metricsAvailable: true,
1612 selectedDate,
1613 });
1614 })
1615 .catch(ex => this.setState({ error: ex.toString() }));
1616 }
1617
1618 async componentDidMount() {
1619 let packageManager = false;
1620 try {
1621 await getPackageManager();
1622 packageManager = true;
1623 } catch (err) {
1624 packageManager = false;
1625 }
1626 // HACK: See https://github.com/cockpit-project/cockpit/issues/19143
1627 let cmdline = "";
1628 try {
1629 cmdline = await cockpit.file("/proc/self/cmdline").read();
1630 } catch (_ex) {}
1631
1632 const isBeibootBridge = cmdline?.includes("ic# cockpit-bridge");
1633 this.setState({ packageManager, isBeibootBridge });
1634
1635 try {
1636 // Only 14 days of metrics are shown
1637 // Requires superuser on Debian/Ubuntu, on Fedora/Arch users in the wheel group can list without superuser.
1638 const output = await cockpit.spawn(["journalctl", "--list-boots", "--since", "-15d", "--output", "json"], { superuser: "try" });
1639 const list_boots = JSON.parse(output);
1640 const boots = list_boots.map(boot => {
1641 return {
1642 started: new Date(boot?.first_entry / 1000),
1643 ended: new Date(boot?.last_entry / 1000),
1644 current_boot: boot?.index === 0,
1645 };
1646 });
1647 this.setState({ boots });
1648 } catch (exc) {
1649 console.warn("journalctl --list-boots failed", exc);
1650 }
1651 }
1652
1653 handleMoreData() {
1654 this.load_data(this.oldest_timestamp - (LOAD_HOURS * MSEC_PER_H), LOAD_HOURS * SAMPLES_PER_H, true);
1655 }
1656
1657 handleSelect(sel) {
1658 // Stop fetching of new data
1659 if (this.history_refresh_timer !== null) {
1660 window.clearTimeout(this.history_refresh_timer);
1661 this.history_refresh_timer = null;
1662 }
1663
1664 this.oldest_timestamp = 0;
1665
1666 cockpit.location.go([], Object.assign(cockpit.location.options, { date: sel }));
1667 this.setState({
1668 selectedDate: sel,
1669 hours: [],
1670 }, () => this.load_data(sel, sel === this.today_midnight ? undefined : 24 * SAMPLES_PER_H, true));
1671 }
1672
1673 async handleInstall() {
1674 install_dialog(await get_pcp_packages())
1675 .then(() => this.initialLoadData())
1676 .catch(() => null); // ignore cancel
1677 }
1678
1679 load_data(load_timestamp, limit, show_spinner) {
1680 if (show_spinner)
1681 this.setState({ loading: true });
1682
1683 this.oldest_timestamp = this.oldest_timestamp > load_timestamp || this.oldest_timestamp === 0 ? load_timestamp : this.oldest_timestamp;
1684 let current_hour; // hour of timestamp, from most recent meta message
1685 let hour_index; // index within data[current_hour] array
1686 const current_sample = []; // last valid value, for decompression
1687 const new_hours = new Set(); // newly seen hours during this load
1688 this.history_refresh_timer = null;
1689
1690 const metrics = cockpit.channel({
1691 payload: "metrics1",
1692 interval: INTERVAL,
1693 source: "pcp-archive",
1694 timestamp: load_timestamp,
1695 limit,
1696 metrics: HISTORY_METRICS,
1697 "omit-instances": ["lo"],
1698 });
1699
1700 metrics.addEventListener("message", (event, message) => {
1701 debug("history metrics message", message);
1702 message = JSON.parse(message);
1703
1704 const init_current_hour = () => {
1705 if (!this.data[current_hour])
1706 this.data[current_hour] = [];
1707
1708 // When limit is considered only add hours in this time range
1709 if (!limit || load_timestamp + (limit * INTERVAL) >= current_hour)
1710 new_hours.add(current_hour);
1711 };
1712
1713 // meta message
1714 if (!Array.isArray(message)) {
1715 current_hour = Math.floor(message.timestamp / MSEC_PER_H) * MSEC_PER_H;
1716 init_current_hour();
1717 hour_index = Math.floor((message.timestamp - current_hour) / INTERVAL);
1718 console.assert(hour_index < SAMPLES_PER_H);
1719
1720 debug("message is metadata; time stamp", message.timestamp, "=", timeformat.dateTime(message.timestamp), "for current_hour", current_hour, "=", timeformat.dateTime(current_hour), "hour_index", hour_index);
1721 return;
1722 }
1723
1724 debug("message is", message.length, "samples data for current hour", current_hour, "=", timeformat.dateTime(current_hour));
1725
1726 message.forEach((samples, i) => {
1727 decompress_samples(samples, current_sample);
1728
1729 /* don't overwrite existing data with null data; this often happens at the first
1730 * data point when "rate" metrics cannot be calculated yet */
1731 if (typeof current_sample[0] !== 'number' && this.data[current_hour][hour_index]) {
1732 debug("load_data", load_timestamp, ": ignoring sample #", i, ":", JSON.stringify(current_sample), "current data sample", JSON.stringify(this.data[current_hour][hour_index]));
1733 return;
1734 }
1735
1736 // TODO: eventually track/display this by-interface?
1737 const use_network = current_sample[8].reduce((acc, cur) => acc + cur, 0);
1738 const sat_cpu = typeof current_sample[3][1] === 'number' ? current_sample[3][1] : null; // instances: (15min, 1min, 5min), pick 1min
1739
1740 this.data[current_hour][hour_index] = {
1741 use_cpu: typeof current_sample[2] === 'number' ? [current_sample[0], current_sample[1], current_sample[2]] : null,
1742 sat_cpu,
1743 use_memory: typeof current_sample[5] === 'number' ? [current_sample[4], current_sample[5]] : null,
1744 sat_memory: current_sample[6],
1745 use_disks: current_sample[7],
1746 use_network,
1747 };
1748
1749 // keep track of maximums of unbounded values, for dynamic scaling
1750 if (sat_cpu > scaleSatCPU)
1751 scaleSatCPU = scaleForValue(sat_cpu);
1752 if (current_sample[7] > scaleUseDisks)
1753 scaleUseDisks = scaleForValue(current_sample[7]);
1754 if (use_network > scaleUseNetwork)
1755 scaleUseNetwork = scaleForValue(use_network);
1756
1757 if (++hour_index === SAMPLES_PER_H) {
1758 current_hour += MSEC_PER_H;
1759 hour_index = 0;
1760 init_current_hour();
1761 debug("hour overflow, advancing to", current_hour, "=", timeformat.dateTime(current_hour));
1762 }
1763 });
1764
1765 // update most recent sample timestamp
1766 this.most_recent = Math.max(this.most_recent, current_hour + (hour_index - 5) * INTERVAL);
1767 debug("most recent timestamp is now", this.most_recent, "=", timeformat.dateTime(this.most_recent));
1768 });
1769
1770 metrics.addEventListener("close", (event, message) => {
1771 if (message.problem) {
1772 debug("could not load metrics:", message.problem);
1773 this.setState({
1774 loading: false,
1775 metricsAvailable: false,
1776 isPythonPCPInstalled: message?.message !== "python3-pcp not installed",
1777 });
1778 } else {
1779 this.setState({ isPythonPCPInstalled: true });
1780 debug("loaded metrics for timestamp", timeformat.dateTime(load_timestamp), "new hours", JSON.stringify(Array.from(new_hours)));
1781 new_hours.forEach(hour => debug("hour", hour, "data", JSON.stringify(this.data[hour])));
1782
1783 const hours = Array.from(new Set([...this.state.hours, ...new_hours]));
1784 // sort in descending order
1785 hours.sort((a, b) => b - a);
1786 // re-render
1787 this.setState({ hours, loading: false });
1788
1789 // trigger automatic update every minute when visible
1790 if (!limit) {
1791 this.history_refresh_timer = window.setTimeout(() => {
1792 if (!cockpit.hidden)
1793 this.load_data(this.most_recent);
1794 }, 60000);
1795 }
1796 }
1797
1798 metrics.close();
1799 });
1800 }
1801
1802 render() {
1803 // on a single machine, cockpit-pcp depends on pcp; but this may not be the case in the beiboot scenario,
1804 // so additionally check if pcp is available on the logged in target machine
1805 if (this.state.isPythonPCPInstalled === false || this.pmlogger_service.exists === false)
1806 return <EmptyStatePanel
1807 icon={ExclamationCircleIcon}
1808 title={_("PCP is missing for metrics history")}
1809 action={this.state.packageManager && <Button onClick={this.handleInstall}>{_("Install PCP support")}</Button>}
1810 />;
1811
1812 if (!this.state.metricsAvailable) {
1813 let action;
1814 let paragraph;
1815
1816 if (this.pmlogger_service.state === 'stopped') {
1817 paragraph = _("pmlogger.service is not running");
1818 action = <PCPConfig buttonVariant="primary"
1819 firewalldRequest={this.props.firewalldRequest} />;
1820 } else {
1821 if (this.pmlogger_service.state === 'failed')
1822 paragraph = _("pmlogger.service has failed");
1823 else /* running, or initialization hangs */
1824 paragraph = _("pmlogger.service is failing to collect data");
1825 action = <Button variant="link" onClick={() => cockpit.jump("/system/services#/pmlogger.service") }>{_("Troubleshoot")}</Button>;
1826 }
1827
1828 return <EmptyStatePanel
1829 icon={ExclamationCircleIcon}
1830 title={_("Metrics history could not be loaded")}
1831 paragraph={paragraph}
1832 action={action}
1833 />;
1834 }
1835
1836 if (this.state.error)
1837 return <EmptyStatePanel
1838 icon={ExclamationCircleIcon}
1839 title={_("Error has occurred")}
1840 paragraph={this.state.error}
1841 />;
1842
1843 let nodata_alert = null;
1844 const lastHourIndex = this.state.hours.length - 1;
1845 if (!this.state.loading && this.state.hours.length > 0 && this.oldest_timestamp < this.state.hours[lastHourIndex]) {
1846 let t1;
1847 let t2;
1848 if (this.state.hours[lastHourIndex] - this.oldest_timestamp < 24 * MSEC_PER_H) {
1849 t1 = timeformat.time(this.oldest_timestamp);
1850 t2 = timeformat.time(this.state.hours[lastHourIndex]);
1851 } else {
1852 t1 = timeformat.dateTime(this.oldest_timestamp);
1853 t2 = timeformat.dateTime(this.state.hours[lastHourIndex]);
1854 }
1855 nodata_alert = <Alert className="nodata" variant="info" isInline title={ cockpit.format(_("No data available between $0 and $1"), t1, t2) } />;
1856 }
1857
1858 if (!this.state.loading && this.state.hours.length === 0)
1859 nodata_alert = <EmptyStatePanel icon={ExclamationCircleIcon} title={_("No data available")} />;
1860
1861 // generate selection of last 14 days
1862 const options = Array(15).fill()
1863 .map((_undef, i) => {
1864 const date = this.today_midnight - i * 86400000;
1865 const text = i == 0 ? _("Today") : timeformat.weekdayDate(date);
1866 return { value: date, content: text };
1867 });
1868
1869 function Label(props) {
1870 return (
1871 <div className={"metrics-label metrics-label-graph" + (props.items.length > 1 ? " have-saturation" : "")}>
1872 <span>{props.label}</span>
1873 <Content className="metrics-sublabels">
1874 { props.items.map(i => <Content component={ContentVariants.small} key={i}>{i}</Content>) }
1875 </Content>
1876 </div>
1877 );
1878 }
1879
1880 const columnVisibilityMenuItems = this.columns.map(itm => {
1881 return {
1882 value: itm[0],
1883 content: itm[1],
1884 "data-label": itm[0],
1885 };
1886 });
1887 const selections = (
1888 this.columns
1889 .filter(itm => this.state.selectedVisibility[itm[0]])
1890 .map(itm => itm[0])
1891 );
1892
1893 return (
1894 <div className="metrics" style={{ "--graph-cnt": selections.length }}>
1895 <PageGroup stickyOnBreakpoint={{ default: 'top' }}>
1896 <section className="metrics-heading">
1897 <Flex className="metrics-selectors" spaceItems={{ default: 'spaceItemsSm' }}>
1898 <SimpleSelect
1899 onSelect={this.handleSelect}
1900 selected={this.state.selectedDate}
1901 options={options}
1902 isScrollable
1903 toggleProps={{
1904 id: "date-picker-select-toggle",
1905 className: "select-min metrics-label",
1906 "aria-label": _("Jump to")
1907 }} />
1908 <CheckboxSelect
1909 toggleProps={{
1910 "aria-label": _("Graph visibility options menu"),
1911 className: "select-min metrics-label",
1912 }}
1913 toggleContent={_("Graph visibility")}
1914 noBadge
1915 onSelect={(selection, checked) => {
1916 this.setState(prevState => ({
1917 selectedVisibility: { ...prevState.selectedVisibility, [selection]: checked }
1918 }));
1919 }}
1920 selected={selections}
1921 options={columnVisibilityMenuItems} />
1922 </Flex>
1923 <Stack className="metrics-label-graph-mobile">
1924 {[["cpu", _("CPU usage/load")], ["memory", _("Memory usage/swap")], ["disks", _("Disk I/O")], ["network", _("Network")]]
1925 .filter(itm => this.state.selectedVisibility[itm[0]])
1926 .map(itm => (
1927 <Flex key={itm[0]} flexWrap={{ default: 'nowrap' }} spaceItems={{ default: 'spaceItemsSm' }} alignItems={{ default: 'alignItemsBaseline' }}>
1928 <div className={"square label-" + itm[0]} />
1929 <FlexItem>{itm[1]}</FlexItem>
1930 </Flex>
1931 ))}
1932 </Stack>
1933 <div className="metrics-graphs metrics-heading-graphs">
1934 {this.state.selectedVisibility.cpu && <Label label={_("CPU")} items={[_("Usage"), _("Load")]} />}
1935 {this.state.selectedVisibility.memory && <Label label={_("Memory")} items={[_("Usage"), ...swapTotal ? [_("Swap")] : []]} />}
1936 {this.state.selectedVisibility.disks && <Label label={_("Disk I/O")} items={[_("Usage")]} />}
1937 {this.state.selectedVisibility.network && <Label label={_("Network")} items={[_("Usage")]} />}
1938 </div>
1939 </section>
1940 </PageGroup>
1941 <PageSection hasBodyWrapper={false} className="metrics-history-section">
1942 <>
1943 { this.state.hours.length > 0 &&
1944 <Card isPlain>
1945 <CardBody className="metrics-history">
1946 { this.state.hours.map((time, i) => {
1947 const date_time = new Date(time);
1948 const boot_minutes = this.state.boots.filter(reboot => reboot.started.getDay() === date_time.getDay() &&
1949 reboot.started.getYear() === date_time.getYear() &&
1950 reboot.started.getHours() === date_time.getHours())
1951 .map(reboot => reboot.started.getMinutes());
1952 const showHeader = i == 0 || timeformat.date(time) != timeformat.date(this.state.hours[i - 1]);
1953
1954 return (
1955 <React.Fragment key={timeformat.dateTime(time)}>
1956 {showHeader && <Content><Content component={ContentVariants.h3} className="metrics-time"><time>{ timeformat.date(time) }</time></Content></Content>}
1957 <MetricsHour key={time} startTime={parseInt(time)}
1958 selectedVisibility={this.state.selectedVisibility}
1959 data={this.data[time]} clipLeading={i == 0}
1960 boots={boot_minutes} />
1961 </React.Fragment>
1962 );
1963 })}
1964 </CardBody>
1965 </Card> }
1966 {nodata_alert}
1967 <div className="bottom-panel">
1968 { this.state.loading
1969 ? <EmptyStatePanel loading title={_("Loading...")} />
1970 : <Button onClick={this.handleMoreData}>{_("Load earlier data")}</Button> }
1971 </div>
1972 </>
1973 </PageSection>
1974 </div>
1975 );
1976 }
1977 }
1978
1979 export const Application = () => {
1980 const [firewalldRequest, setFirewalldRequest] = useState(null);
1981
1982 return (
1983 <WithDialogs>
1984 <Page className="pf-m-no-sidebar">
1985 <PageBreadcrumb
1986 id='metrics-header-section'
1987 hasBodyWrapper={false}
1988 stickyOnBreakpoint={{ default: "top" }}
1989 >
1990 <Flex>
1991 <FlexItem>
1992 <Breadcrumb>
1993 <BreadcrumbItem onClick={() => cockpit.jump("/system")} className="pf-v6-c-breadcrumb__link">{_("Overview")}</BreadcrumbItem>
1994 <BreadcrumbItem isActive>{_("Metrics and history")}</BreadcrumbItem>
1995 </Breadcrumb>
1996 </FlexItem>
1997 <FlexItem align={{ default: 'alignRight' }}>
1998 <PCPConfig buttonVariant="secondary"
1999 firewalldRequest={setFirewalldRequest} />
2000 </FlexItem>
2001 </Flex>
2002 </PageBreadcrumb>
2003 { firewalldRequest &&
2004 <FirewalldRequest service={firewalldRequest.service} title={firewalldRequest.title} pageSection /> }
2005 <PageSection hasBodyWrapper={false}>
2006 <CurrentMetrics />
2007 </PageSection>
2008 <MetricsHistory firewalldRequest={setFirewalldRequest} />
2009 </Page>
2010 </WithDialogs>);
2011 };