Debian Codegraph @

test/verify/check-metrics

raw
1 #!/usr/bin/python3 -cimport os, sys; os.execv(os.path.dirname(sys.argv[1]) + "/../common/pywrap", sys.argv)
2 # Run this with --help to see available options for tracing and debugging
3 # See https://github.com/cockpit-project/cockpit/blob/main/test/common/testlib.py
4 # "class Browser" and "class MachineCase" for the available API.
5
6 import re
7 import time
8
9 import packagelib
10 import testlib
11 from lib.constants import TEST_OS_DEFAULT
12
13
14 def getMaximumSpike(test, g_type, saturation, hour, minute):
15 # only for minutes with events, which have SVG graphs
16 sel = f"#metrics-hour-{hour} div.metrics-minute[data-minute='{minute}'] div.metrics-data-{g_type} div"
17 if saturation:
18 sel += ":nth-child(2)"
19 else:
20 sel += ":first-child"
21
22 points = test.browser.attr(sel, "points")
23 xs = [float(x.split(" ")[0].rstrip("%")) for x in points.split(", ") if x != ""]
24 test.assertNotIn("NaN", xs)
25
26 return max(xs) / 100
27
28
29 def getCompressedMinuteValue(test, g_type, saturation, hour, minute):
30 # only for minutes without events, which only have bars
31
32 polygon_class = ".polygon-sat" if saturation else ".polygon-use"
33 sel = f"#metrics-hour-{hour} div.metrics-minute[data-minute='{minute}'] div.metrics-data-{g_type} .compressed{polygon_class}"
34 m = re.search(r"--%s:\s*([0-9.]+);" % ("saturation" if saturation else "utilization"), test.browser.attr(sel, "style"))
35 test.assertIsNotNone(m)
36 return float(m.group(1))
37
38
39 def topServiceValue(test, aria_label, col_label, row):
40 sel = "table[aria-label='%s'] tbody tr:nth-of-type(%d) td[data-label='%s']" % (aria_label, row, col_label)
41 # split off unit, like "12 MB"
42 return float(test.browser.text(sel).split(' ')[0])
43
44
45 def prepareArchive(machine, name, time, hostname="localhost.localdomain"):
46 machine.upload([f"verify/files/metrics-archives/{name}"], "/tmp/")
47
48 command = f"tar -C / -xzvf /tmp/{name}"
49 if name.endswith("zip"):
50 command = f"unzip /tmp/{name} -d /"
51
52 machine.execute(f"""ntp=`timedatectl show --property NTP --value`
53 if [ $ntp == "yes" ]; then
54 timedatectl set-ntp off
55 fi
56 systemctl stop pmlogger
57 # don't let NM set transient host names from DHCP
58 systemctl stop NetworkManager
59 hostnamectl set-hostname {hostname}
60 rm -rf /var/log/pcp/pmlogger/*
61 {command}
62 # set-ntp off is asynchronous; wait until timesyncd stops before the time can be set
63 while systemctl is-active systemd-timesyncd; do sleep 1; done
64 date --set='@{time}'""")
65
66
67 def redisService(image):
68 if image.startswith(("debian", "ubuntu")):
69 return "redis-server"
70 if image.startswith(("fedora", "centos-10", "rhel-10", "arch")):
71 return "valkey"
72 return "redis"
73
74
75 def applySettings(browser, dialog_selector):
76 browser.click(f"{dialog_selector} button.pf-m-primary")
77 with browser.wait_timeout(60):
78 browser.wait_not_present(dialog_selector)
79
80
81 @testlib.skipOstree("no PCP support")
82 class TestHistoryMetrics(testlib.MachineCase):
83 def setUp(self):
84 super().setUp()
85 # start with a clean slate and avoid running into restart limits
86 self.machine.execute("systemctl stop pmlogger pmproxy; systemctl reset-failed pmlogger pmproxy 2>/dev/null || true")
87 self.pcp_dialog_selector = "#pcp-settings-modal"
88
89 def waitStream(self, current_max):
90 # should only have at most <current_max> valid minutes, the rest should be empty
91 valid_start = self.browser.count(".metrics-data-cpu.valid-data")
92 self.assertLessEqual(valid_start, current_max)
93 # page auto-updates every minute
94 with self.browser.wait_timeout(90):
95 self.browser.wait_count('.metrics-data-cpu.valid-data', valid_start + 1)
96
97 # Should never show more then 4 empty leading minutes (block of 5 minutes but always at least one used)
98 leading_empty = self.browser.call_js_func("""(function () {
99 const lines = document.getElementsByClassName("metrics-data-cpu");
100 let counter = 0;
101
102 Array.from(lines).every(l => {
103 if (l.classList.contains("empty-data")) {
104 counter++;
105 return true;
106 } else {
107 return false;;
108 }
109 });
110
111 return counter;
112 })""")
113 self.assertLessEqual(leading_empty, 4)
114
115 def testBasic(self):
116 b = self.browser
117 m = self.machine
118
119 m.execute("""ntp=`timedatectl show --property NTP --value`
120 if [ $ntp == "yes" ]; then
121 timedatectl set-ntp off
122 fi""")
123 m.execute("while systemctl is-active systemd-timesyncd; do sleep 1; done")
124 m.execute("date --set='2020-11-24 09:24:05'")
125
126 # clean slate, to avoid seeing the data from preparing the VM
127 m.execute("rm -rf /var/log/pcp/pmlogger/*; systemctl start pmlogger")
128
129 self.login_and_go("/metrics")
130 # eventually finishes data loading and shows heading
131 b.wait_in_text(".metrics-heading", "CPU")
132
133 # only shows current hour
134 b.wait_count(".metrics-hour", 1)
135
136 # VM just started, we don't have 12 hours of data
137 b.wait_in_text(".metrics .pf-v6-c-alert", "No data available between")
138 # initial data gap is < 24 hours, does not show date
139 year = m.execute("date +%Y").strip()
140 self.assertNotIn(year, b.text(".metrics .pf-v6-c-alert"))
141
142 # can try to load earlier data; only updates "no data" alert as there is no data
143 b.wait_text(".bottom-panel button", "Load earlier data")
144 b.click(".bottom-panel button")
145 # now the gap is > 24 hours, does show date
146 b.wait_in_text(".metrics .pf-v6-c-alert", year)
147 # still only one hour
148 b.wait_count(".metrics-hour", 1)
149
150 self.waitStream(3)
151
152 # Graphs are by default all visible
153 b.click("button[aria-label='Graph visibility options menu']")
154 testlib.wait(lambda: b.get_checked(".pf-v6-c-menu__list-item[data-label='cpu'] input"))
155 b.wait_visible(".metrics-label-graph:contains('CPU')")
156 self.assertTrue(b.get_checked(".pf-v6-c-menu__list-item[data-label='memory'] input"))
157 b.wait_visible(".metrics-label-graph:contains('Memory')")
158 self.assertTrue(b.get_checked(".pf-v6-c-menu__list-item[data-label='disks'] input"))
159 b.wait_visible(".metrics-label-graph:contains('Disk I/O')")
160 self.assertTrue(b.get_checked(".pf-v6-c-menu__list-item[data-label='network'] input"))
161 b.wait_visible(".metrics-label-graph:contains('Network')")
162
163 # Change graph visibility
164 b.wait_visible(".metrics-events:contains('Network I/O')")
165 b.set_checked(".pf-v6-c-menu__list-item[data-label='network'] input", val=False)
166 b.wait_not_present(".metrics-events:contains('Network I/O')")
167 b.wait_not_present(".metrics-label-graph:contains('Network')")
168 b.set_checked(".pf-v6-c-menu__list-item[data-label='network'] input", val=True)
169
170 # Change date to yesterday, should be empty
171 b.click("#date-picker-select-toggle")
172 b.click(".pf-v6-c-menu__list-item:nth-child(2) button")
173 b.wait_text(".pf-v6-c-empty-state", "No data available")
174
175 # Breadcrumb back to Overview page
176 b.click(".pf-v6-c-breadcrumb li:first-child")
177 b.enter_page("/system")
178 b.wait_visible('.system-information')
179
180 def testEvents(self):
181 b = self.browser
182 m = self.machine
183
184 b.wait_timeout(60)
185
186 def events_at(hour, minute):
187 b.wait_visible(f"#metrics-hour-{hour}.metrics-hour-compressed")
188 b.click(f"#metrics-hour-{hour} button.metrics-events-expander")
189 events = b.text(f"#metrics-hour-{hour} div.metrics-minute[data-minute='{minute}'] .metrics-events")
190 b.click(f"#metrics-hour-{hour} button.metrics-events-expander")
191
192 return events
193
194 #
195 # Disks
196 #
197
198 # disable swap, so that we can test current metrics without swap
199 m.execute("""systemctl stop "*.swap" "swap-create@*" "systemd-zram-setup@*" || true
200 systemctl mask "swap-create@" "systemd-zram-setup@"
201 swapoff --all
202 while [ -n "$(swapon --show)" ]; do sleep 1; done""")
203
204 prepareArchive(m, "disk.tar.gz", 1597672800)
205
206 self.login_and_go("/metrics")
207 # eventually finishes data loading and shows heading
208 b.wait_in_text(".metrics-heading", "CPU")
209
210 # Big spike lasting 3 minutes
211 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=25), 0.9)
212 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=26), 0.9)
213 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=27), 0.9)
214
215 # Smaller spike lasting 2 minutes
216 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=28), 0.4)
217 self.assertLessEqual(getMaximumSpike(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=28), 0.6)
218 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=29), 0.4)
219 # recognized as event
220
221 self.assertIn("Disk I/O", events_at(1597662000000, 28))
222
223 # No visible activity after that
224 self.assertLessEqual(getCompressedMinuteValue(test=self, g_type="disks", saturation=False, hour=1597662000000, minute=30), 0.01)
225
226 # swap usage is not shown if there is no swap
227 b.wait_visible("#current-memory-usage")
228 self.assertFalse(b.is_present("#current-swap-usage"))
229
230 # Check that we don't show too much empty minutes in the first hour
231 self.assertLessEqual(b.count(".metrics-data-cpu"), 35)
232
233 # Check metrics hour header in compressed and expanded mode
234 b.click("#metrics-hour-1597662000000 button.metrics-events-expander")
235 b.wait_in_text("#metrics-hour-1597662000000:not(.metrics-hour-compressed) .metrics-events-hour-header-expanded time", "1:00")
236 b.wait_in_text("#metrics-hour-1597662000000:not(.metrics-hour-compressed) .metrics-events-hour-header-expanded .spikes_count", "3 spikes")
237 b.wait_in_text("#metrics-hour-1597662000000:not(.metrics-hour-compressed) .metrics-events-hour-header-expanded .spikes_info", "1 Memory, 1 Disk I/O, 1 Network I/O")
238
239 # move the mouse away from the pixel test region, to avoid spurious focus highlights
240 b.mouse("#metrics-header-section", "mousemove")
241
242 # "hold still while I take a photo!" -- the current metrics are too jumpy
243 b.eval_js("document.querySelector('.current-metrics').style.display = 'none'")
244
245 def on_layout_change():
246 # wait until the toolbar is fully rendered
247 b.wait_visible("#date-picker-select-toggle")
248 # wait until the metrics data is fully rendered
249 b.wait_visible("#metrics-hour-1597662000000")
250
251 # FIXME: mobile layout is racy in tests (only, not in reality), scrollIntoView() misplaces the menu bar
252 b.assert_pixels(
253 ".metrics",
254 "metrics-history-expanded-hour",
255 ignore=[".spikes_count"],
256 skip_layouts=["mobile"],
257 wait_after_layout_change=True,
258 wait_delay=1,
259 chrome_hack_double_shots=True,
260 abs_tolerance=40,
261 layout_change_hook=on_layout_change,
262 )
263
264 b.click("#metrics-hour-1597662000000 button.metrics-events-expander")
265 b.wait_in_text("#metrics-hour-1597662000000.metrics-hour-compressed", "1:00")
266 b.wait_in_text("#metrics-hour-1597662000000.metrics-hour-compressed .spikes_count", "3 spikes")
267 b.wait_in_text("#metrics-hour-1597662000000.metrics-hour-compressed .spikes_info", "1 Memory, 1 Disk I/O, 1 Network I/O")
268
269 # HACK: the bottom panel has some unpredictable extra white line at the bottom, but is also uninteresting
270 b.eval_js("document.querySelector('.bottom-panel').style.display = 'none'")
271
272 # move the mouse away from the pixel test region, to avoid spurious focus highlights
273 b.mouse("#metrics-header-section", "mousemove")
274
275 b.assert_pixels(".metrics", "metrics-history-compressed-hour", ignore=[".nodata"],
276 skip_layouts=["mobile"], wait_after_layout_change=True)
277
278 # as you were -- you can jump around again
279 b.eval_js("document.querySelector('.current-metrics').style.removeProperty('display')")
280
281 b.eval_js("document.querySelector('.bottom-panel').style.removeProperty('display')")
282
283 # Check that events are not visible for compressed hours
284 b.wait_not_present("#metrics-hour-1597662000000 div.metrics-minute[data-minute='28'] .metrics-events")
285 b.click("#metrics-hour-1597662000000 button.metrics-events-expander")
286 b.wait_visible("#metrics-hour-1597662000000 div.metrics-minute[data-minute='28'] .metrics-events")
287
288 b.logout()
289
290 #
291 # Network and CPU
292 #
293
294 prepareArchive(m, "cpu_network.tar.gz", 1598918400)
295
296 self.login_and_go("/metrics")
297 # eventually finishes data loading and shows heading
298 b.wait_in_text(".metrics-heading", "CPU")
299
300 # Test network - Big spike lasting 2 minutes
301 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="network", saturation=False, hour=1598950800000, minute=3), 0.5)
302 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="network", saturation=False, hour=1598950800000, minute=4), 0.5)
303 # recognized as event
304 self.assertIn("Network I/O", events_at(1598950800000, 3))
305 # but it's not a new event in minute 4
306 self.assertNotIn("Network I/O", events_at(1598950800000, 4))
307
308 # Followed by smaller spike
309 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="network", saturation=False, hour=1598950800000, minute=5), 0.35)
310 self.assertLessEqual(getMaximumSpike(test=self, g_type="network", saturation=False, hour=1598950800000, minute=5), 0.5)
311 # still not a new spike
312 self.assertNotIn("Network I/O", events_at(1598950800000, 5))
313
314 # Followed by virtually no data
315 self.assertLessEqual(getCompressedMinuteValue(test=self, g_type="network", saturation=False, hour=1598950800000, minute=6), 0.01)
316
317 # Test CPU load - big - small - big spikes
318 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598950800000, minute=3), 0.9)
319 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598950800000, minute=4), 0.5)
320 self.assertLessEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598950800000, minute=4), 0.55)
321 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598950800000, minute=5), 0.9)
322 self.assertIn("CPU", events_at(1598950800000, 2))
323 self.assertIn("CPU", events_at(1598950800000, 5))
324
325 # Test CPU saturation - 3 spikes, each 2 minutes (medium, big, small)
326 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=3), 0.5)
327 self.assertLessEqual(getMaximumSpike(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=3), 0.6)
328 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=4), 0.5)
329 self.assertLessEqual(getMaximumSpike(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=4), 0.6)
330
331 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=5), 0.8)
332 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=6), 0.8)
333
334 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=7), 0.3)
335 self.assertLessEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=7), 0.4)
336 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=8), 0.1)
337 self.assertLessEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=True, hour=1598950800000, minute=8), 0.4)
338
339 self.assertNotIn("Load", events_at(1598950800000, 2))
340 self.assertIn("Load", events_at(1598950800000, 3))
341 self.assertNotIn("Load", events_at(1598950800000, 4))
342 self.assertIn("Load", events_at(1598950800000, 5))
343
344 b.logout()
345
346 #
347 # Memory
348 #
349
350 have_swap = m.execute("swapon --show").strip()
351
352 prepareArchive(m, "memory.tar.gz", 1600248000)
353 self.login_and_go("/metrics")
354 b.wait_in_text(".metrics-heading", "CPU")
355
356 # basic RAM consumption after boot; it's still a network spike, thus event+SVG
357 self.assertLessEqual(getMaximumSpike(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=44), 0.4)
358 self.assertNotIn("Memory", events_at(1600236000000, 44))
359 if have_swap:
360 self.assertAlmostEqual(getMaximumSpike(test=self, g_type="memory", saturation=True, hour=1600236000000, minute=44), 0)
361 self.assertNotIn("Swap", events_at(1600236000000, 44))
362
363 # swap event from :46 to :47
364 self.assertGreater(getMaximumSpike(test=self, g_type="memory", saturation=True, hour=1600236000000, minute=46), 0.9)
365 self.assertIn("Swap", events_at(1600236000000, 46))
366 # continuous, no new Swap event, but still a Memory+Network event
367 self.assertGreater(getMaximumSpike(test=self, g_type="memory", saturation=True, hour=1600236000000, minute=47), 0.9)
368 self.assertNotIn("Swap", events_at(1600236000000, 47))
369
370 else:
371 # If no swap, the column is hidden
372 self.assertNotIn(b.text(".metrics-heading"), "Swap")
373 b.wait_not_present(".metrics-data-memory .saturation")
374
375 # memory spike in :46 or :47 (depends on PCP version)
376 self.assertGreater(getMaximumSpike(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=47), 0.6)
377 try:
378 self.assertIn("Memory", events_at(1600236000000, 46))
379 except AssertionError:
380 self.assertIn("Memory", events_at(1600236000000, 47))
381
382 # at :54 the machine is loaded to ~80% so no event even if elevated
383 self.assertGreater(getCompressedMinuteValue(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=54), 0.3)
384 b.wait_not_present("#metrics-hour-1600236000000 div.metrics-minute[data-minute='54'] .metrics-events")
385 if have_swap:
386 self.assertAlmostEqual(getCompressedMinuteValue(test=self, g_type="memory", saturation=True, hour=1600236000000, minute=54), 0.0)
387
388 # everything is quiet in :55
389 self.assertLess(getCompressedMinuteValue(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=55), 0.4)
390 if have_swap:
391 self.assertAlmostEqual(getCompressedMinuteValue(test=self, g_type="memory", saturation=True, hour=1600236000000, minute=55), 0.0)
392
393 b.logout()
394
395 #
396 # Check changing of time
397 #
398
399 m.execute("date --set=@1600550674")
400 self.login_and_go("/metrics")
401 # self.waitStream(3) # FIXME: wait for new data - pcp does not handle time change greatly
402 b.wait_text("#date-picker-select-toggle .pf-v6-c-menu-toggle__text", "Today")
403
404 b.select_PF("#date-picker-select-toggle", "Wednesday, September 16, 2020")
405 # memory spike at :50 or :51 (depends on PCP version)
406 try:
407 self.assertGreater(getMaximumSpike(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=50), 0.3)
408 self.assertIn("Memory", events_at(1600236000000, 50))
409 except (AttributeError, AssertionError):
410 self.assertGreater(getMaximumSpike(test=self, g_type="memory", saturation=False, hour=1600236000000, minute=51), 0.3)
411 self.assertIn("Memory", events_at(1600236000000, 51))
412
413 # Reload should keep the filters intact
414 b.reload()
415 b.enter_page("/metrics")
416 b.wait_text("#date-picker-select-toggle .pf-v6-c-menu-toggle__text", "Wednesday, September 16, 2020")
417
418 b.click("#date-picker-select-toggle")
419 b.click(".pf-v6-c-menu__list-item button:contains('Today')")
420 b.wait_text("#date-picker-select-toggle .pf-v6-c-menu-toggle__text", "Today")
421 # self.waitStream(4) # FIXME: wait for new data - pcp does not handle time change greatly
422
423 b.logout()
424
425 #
426 # Check that for every minute only one event is present
427 #
428
429 if self.machine.image == TEST_OS_DEFAULT: # Debian/Ubuntu is unhappy about this archive, one Fedora test is enough though
430 prepareArchive(m, "double_events.zip", 1602345600, "m1.cockpit.lan")
431 self.login_and_go("/metrics")
432 b.wait_in_text(".metrics-heading", "CPU")
433 b.wait_in_text("#metrics-hour-1602334800000", "CPU")
434 self.assertTrue(self.browser.call_js_func("""(function () {
435 const min_events = document.getElementsByClassName("metrics-events");
436 return Array.from(min_events).every(l => {
437 const events = Array.from(l.getElementsByTagName("dd")).map(d => d.innerHTML);
438 return (new Set(events)).size === events.length;
439 });
440 })"""))
441
442 b.logout()
443
444 #
445 # Journal logs
446 #
447
448 prepareArchive(m, "with_journal.tar.gz", 1615200500, "m1.cockpit.lan")
449 # first check the "no logs found" case
450 self.login_and_go("/metrics")
451 b.wait_in_text(".metrics-heading", "CPU")
452 b.click("#metrics-hour-1615197600000 button.metrics-events-expander")
453 b.wait_in_text("#metrics-hour-1615197600000", "Load")
454 # Load event at :38 or :39 (depending on PCP version)
455 for load_minute in [38, 39]:
456 load_minute_sel = f"#metrics-hour-1615197600000 div.metrics-minute[data-minute='{load_minute}']"
457 if "Load" in b.text(load_minute_sel):
458 break
459 else:
460 self.fail("no Load event found at either :38 or :39")
461
462 # Now add the journal
463 # Older systemds get a slightly wrong log window with --since/until, so only run on newer ones
464 if re.search(r"centos-[89]|rhel-[89]", self.machine.image):
465 return
466
467 m.upload(["verify/files/metrics-archives/journal.journal.gz"], "/tmp")
468 # we need to move all other existing journals out of the way, otherwise boot order is going back in time
469 m.execute("""gunzip /tmp/journal.journal.gz
470 systemctl stop systemd-journald
471 rm /var/log/journal/*/*.journal
472 cp /tmp/journal.journal /var/log/journal/*/
473 systemctl start systemd-journald""")
474 b.reload()
475 b.enter_page("/metrics")
476
477 # Expand metrics when loaded
478 b.wait_in_text(".metrics-heading", "CPU")
479 b.click("#metrics-hour-1615197600000 button.metrics-events-expander")
480
481 # Show boot as event
482 with b.wait_timeout(60):
483 b.wait_in_text(".metrics-minute[data-minute='35']", "Boot")
484
485 # details for above load event
486 b.click(f"{load_minute_sel} .metrics-events button.spikes_info")
487 b.wait_in_text(".cockpit-log-panel", "load-hog")
488 action = "Stopping" if load_minute == 39 else "Started"
489 b.wait_in_text(".cockpit-log-panel", f"{action} /usr/bin/sh -ec for i in `seq 500`")
490 b.click(f".cockpit-log-message:contains('{action} /usr/bin/sh -ec for i in `seq 500`')")
491 b.enter_page("/system/logs")
492 b.wait_in_text(".pf-v6-c-card__header", "load-hog.service")
493 b.wait_in_text(".pf-v6-c-card__title", "/usr/bin/sh -ec")
494 b.click("li:contains('Logs')")
495 b.wait_in_text(".cockpit-log-panel", "/usr/bin/sh -ec")
496
497 b.go("/metrics")
498 b.enter_page("/metrics")
499 # logs exist, should show tight range
500 b.click("button:contains('View detailed logs')")
501 b.enter_page("/system/logs")
502 b.wait_in_text(".cockpit-log-panel", "load-hog")
503 url = b.eval_js('window.location.hash')
504 self.assertIn("priority=info", url)
505 self.assertIn(f"since=2021-3-8%2010%3A{load_minute}%3A", url)
506 try:
507 self.assertIn(f"until=2021-3-8%2010%3A{load_minute}%3A", url)
508 except AssertionError:
509 self.assertIn(f"until=2021-3-8%2010%3A{load_minute + 1}%3A", url)
510
511 @testlib.nondestructive
512 def testNoDataEnable(self):
513 b = self.browser
514 m = self.machine
515
516 m.execute("""mount -t tmpfs tmpfs /var/log/pcp/pmlogger
517 chown -R pcp:pcp /var/log/pcp/pmlogger
518 if selinuxenabled; then restorecon /var/log/pcp/pmlogger; fi""")
519 self.addCleanup(m.execute, "systemctl stop pmlogger; until umount /var/log/pcp/pmlogger; do sleep 1; done")
520
521 self.login_and_go("/metrics")
522
523 b.wait_in_text(".pf-v6-c-empty-state", "Metrics history could not be loaded")
524 b.wait_in_text(".pf-v6-c-empty-state", "pmlogger.service is not running")
525
526 # enable pmlogger in settings dialog from empty state
527 b.click(".pf-v6-c-empty-state button.pf-m-primary")
528 b.wait_visible(self.pcp_dialog_selector)
529 b.wait_visible("#switch-pmlogger:not(:checked)")
530 b.click("#switch-pmlogger")
531 b.wait_visible("#switch-pmlogger:checked")
532 applySettings(b, self.pcp_dialog_selector)
533
534 m.execute("until systemctl is-active pmlogger; do sleep 1; done")
535
536 # there is a transient "No data available" state, but sometimes it's very short, so don't assert that
537
538 # page auto-updates every minute and starts to receive data,
539 # On ubuntu at least, we need to wait for two samples.
540 with self.browser.wait_timeout(180):
541 self.browser.wait(lambda: b.count(".metrics-data-cpu.valid-data") >= 1)
542 b.wait_not_present(".pf-v6-c-empty-state")
543
544 b.logout()
545
546 @testlib.nondestructive
547 def testNoDataFailed(self):
548 b = self.browser
549 m = self.machine
550
551 m.write("/run/systemd/system/pmlogger.service.d/break.conf", "[Service]\nExecStart=\nExecStart=/bin/false")
552 m.execute(r"""mount -t tmpfs tmpfs /var/log/pcp/pmlogger
553 if selinuxenabled; then restorecon /var/log/pcp/pmlogger; fi
554 systemctl daemon-reload
555 systemctl start pmlogger || true""")
556 self.addCleanup(m.execute,
557 """rm -r /run/systemd/system/pmlogger.service.d/
558 umount /var/log/pcp/pmlogger
559 systemctl daemon-reload""")
560
561 self.login_and_go("/metrics")
562
563 b.wait_in_text(".pf-v6-c-empty-state", "Metrics history could not be loaded")
564 b.wait_in_text(".pf-v6-c-empty-state", "pmlogger.service has failed")
565
566 # Troubleshoot
567 b.click(".pf-v6-c-empty-state button.pf-m-link")
568 b.enter_page("/system/services")
569 b.wait_in_text("#service-details", "pmlogger.service")
570
571 @testlib.nondestructive
572 def testLoggerSettings(self):
573 b = self.browser
574 m = self.machine
575
576 # start in defined state
577 m.execute("systemctl enable --now pmlogger")
578 self.addCleanup(m.execute, "systemctl disable --now pmlogger")
579
580 self.login_and_go("/metrics")
581
582 # disable pmlogger in settings dialog from header bar
583 b.click("#metrics-header-section button.pf-m-secondary")
584 b.wait_visible(self.pcp_dialog_selector)
585 b.wait_visible("#switch-pmlogger:checked")
586 b.click("#switch-pmlogger")
587 b.wait_visible("#switch-pmlogger:not(:checked)")
588 applySettings(b, self.pcp_dialog_selector)
589
590 self.assertEqual(m.execute("systemctl is-active pmlogger || true").strip(), "inactive")
591 self.assertEqual(m.execute("systemctl is-enabled pmlogger || true").strip(), "disabled")
592
593 # enable pmlogger in settings dialog from header bar
594 b.click("#metrics-header-section button.pf-m-secondary")
595 b.wait_visible(self.pcp_dialog_selector)
596 b.wait_visible("#switch-pmlogger:not(:checked)")
597 b.click("#switch-pmlogger")
598 b.wait_visible("#switch-pmlogger:checked")
599 applySettings(b, self.pcp_dialog_selector)
600
601 m.execute("until systemctl is-active pmlogger; do sleep 1; done")
602 self.assertEqual(m.execute("systemctl is-enabled pmlogger").strip(), "enabled")
603
604 @testlib.nondestructive
605 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
606 def testPmProxySettings(self, customRedisService=None):
607 b = self.browser
608 m = self.machine
609
610 m.execute("systemctl start firewalld")
611
612 # Arch Linux has no active zone by default which the firewalld port alert test requires.
613 if m.image == "arch":
614 m.execute("firewall-cmd --zone=public --change-interface eth0 --permanent")
615 m.execute("firewall-cmd --reload")
616
617 redis = customRedisService or redisService(m.image)
618 hostname = m.execute("hostname").strip()
619
620 self.addCleanup(m.execute, f"systemctl disable --now {redis}")
621
622 def checkEnable(firewalld_alert):
623 b.click("#metrics-header-section button.pf-m-secondary")
624 b.wait_visible(self.pcp_dialog_selector)
625 b.wait_visible("#switch-pmproxy:not(:checked)")
626 b.click('#switch-pmproxy')
627 b.wait_visible('#switch-pmproxy:checked')
628 applySettings(b, self.pcp_dialog_selector)
629 if firewalld_alert:
630 b.wait_in_text("#firewalld-request-alert", "pmproxy")
631 else:
632 b.wait_not_present("#firewalld-request-alert")
633 m.execute('while [ $(systemctl is-active pmproxy) = activating ]; do sleep 1; done')
634 self.assertEqual(m.execute("systemctl is-active pmproxy").strip(), "active")
635 self.assertEqual(m.execute(f"systemctl is-active {redis}").strip(), "active")
636 self.assertEqual(m.execute("systemctl is-enabled pmproxy").strip(), "enabled")
637 self.assertIn(redis, m.execute("systemctl show -p Wants --value pmproxy").strip())
638 testlib.wait(lambda: hostname in m.execute("curl --max-time 10 --silent --show-error 'http://localhost:44322/series/labels?names=hostname'"), delay=10, tries=30)
639
640 def checkDisable():
641 b.click("#metrics-header-section button.pf-m-secondary")
642 b.wait_visible(self.pcp_dialog_selector)
643 b.wait_visible('#switch-pmproxy:checked')
644 b.click('#switch-pmproxy')
645 b.wait_visible("#switch-pmproxy:not(:checked)")
646 applySettings(b, self.pcp_dialog_selector)
647 # always clears the firewalld alert
648 b.wait_not_present("#firewalld-request-alert")
649 self.assertEqual(m.execute("! systemctl is-active pmproxy").strip(), "inactive")
650 self.assertEqual(m.execute("! systemctl is-enabled pmproxy").strip(), "disabled")
651 # keeps redis running, it's a shared service
652 self.assertEqual(m.execute(f"systemctl is-active {redis}").strip(), "active")
653 # but drops the pmproxy dependency
654 self.assertNotIn(redis, m.execute("systemctl show -p Wants --value pmproxy").strip())
655 m.execute("! curl --silent --show-error --max-time 10 'http://localhost:44322/series/labels?names=hostname' 2>&1")
656
657 # start in a defined state; all test images have pcp and redis pre-installed
658 m.execute(f"systemctl disable --now pmlogger pmie pmproxy {redis}")
659 m.execute("systemctl reset-failed")
660 # ensure pmproxy is not already opened in firewall
661 m.execute("firewall-cmd --remove-service pmproxy; firewall-cmd --permanent --remove-service pmproxy")
662 self.login_and_go("/metrics")
663
664 # pmproxy can't be enabled without pmlogger
665 b.click("#metrics-header-section button.pf-m-secondary")
666 b.wait_visible(self.pcp_dialog_selector)
667 b.wait_visible("#switch-pmlogger:not(:checked)")
668 b.wait_visible("#switch-pmproxy:not(:checked)")
669 b.wait_visible("#switch-pmproxy:disabled")
670 # enable pmlogger
671 b.click('#switch-pmlogger')
672 b.wait_visible('#switch-pmlogger:checked')
673 applySettings(b, self.pcp_dialog_selector)
674 m.execute('while [ $(systemctl is-active pmlogger) = activating ]; do sleep 1; done')
675 self.assertEqual(m.execute("systemctl is-active pmlogger").strip(), "active")
676 b.wait_not_present("#firewalld-request-alert")
677
678 checkEnable(firewalld_alert=True)
679 checkDisable()
680
681 # redis already running
682 m.execute(f"systemctl start {redis}")
683 checkEnable(firewalld_alert=True)
684 checkDisable()
685
686 # pmproxy already running; 44322 queries hang without redis and until restart
687 m.execute(f"systemctl disable --now {redis}; systemctl start pmproxy")
688 checkEnable(firewalld_alert=True)
689
690 # without firewalld
691 m.execute("firewall-cmd --remove-service pmproxy; firewall-cmd --permanent --remove-service pmproxy")
692 m.execute("systemctl stop firewalld")
693 self.allow_journal_messages(".*org.fedoraproject.FirewallD1.*disconnected.*")
694 checkDisable()
695 checkEnable(firewalld_alert=False)
696 m.execute("systemctl start firewalld")
697
698 # Go to firewall page from alert
699 checkDisable()
700 checkEnable(firewalld_alert=True)
701 b.click(".pf-v6-c-alert button.pf-m-link")
702 b.enter_page("/network/firewall")
703 b.wait_visible("#firewall-heading")
704 b.go("/metrics")
705 b.enter_page("/metrics")
706
707 # add pmproxy to default zone directly in alert
708 default_zone = m.execute("firewall-cmd --get-default-zone").strip()
709 b.wait_text("#firewalld-request-pmproxy", default_zone)
710 b.click(".pf-v6-c-alert button.pf-m-primary")
711 b.wait_not_present(".pf-v6-c-alert:contains('pmproxy')")
712 self.assertIn("pmproxy", m.execute("firewall-cmd --list-services").strip())
713 self.assertIn("pmproxy", m.execute("firewall-cmd --list-services --permanent").strip())
714
715 # now service is already enabled, does not show alert
716 checkDisable()
717 checkEnable(firewalld_alert=False)
718
719 # firewalld service enabled in permanent config already, does not trip over ALREADY_ENABLED
720 checkDisable()
721 m.execute("firewall-cmd --remove-service pmproxy")
722 checkEnable(firewalld_alert=True)
723 b.click(".pf-v6-c-alert button.pf-m-primary")
724 b.wait_not_present(".pf-v6-c-alert:contains('pmproxy')")
725 self.assertIn("pmproxy", m.execute("firewall-cmd --list-services").strip())
726
727 # error during zone addition: zone disappears underneath us
728 checkDisable()
729 m.execute("""set -eux
730 firewall-cmd --permanent --remove-service pmproxy
731 firewall-cmd --permanent --new-zone=comeandgo
732 systemctl start NetworkManager
733 nmcli con add type dummy con-name fake ifname fake0 ip4 1.2.3.4/24
734 firewall-cmd --permanent --zone public --remove-interface fake0
735 firewall-cmd --permanent --zone comeandgo --add-interface fake0
736 firewall-cmd --reload
737 """)
738 self.addCleanup(m.execute, "nmcli con delete fake; firewall-cmd --permanent --delete-zone comeandgo || true; firewall-cmd --reload")
739 checkEnable(firewalld_alert=True)
740 b.select_PF("#firewalld-request-pmproxy", "comeandgo")
741 m.execute("firewall-cmd --permanent --delete-zone comeandgo; firewall-cmd --reload")
742 b.click(".pf-v6-c-alert button.pf-m-primary")
743 self.allow_browser_errors("Failed to enable pmproxy in firewalld:.*INVALID_ZONE: comeandgo.*")
744 b.wait_in_text(".pf-v6-c-alert.pf-m-warning", "Failed to enable pmproxy in firewalld")
745 b.wait_in_text(".pf-v6-c-alert.pf-m-warning", "INVALID_ZONE: comeandgo")
746 # close warning
747 b.click(".pf-v6-c-alert.pf-m-warning button.pf-m-plain")
748 b.wait_not_present(".pf-v6-c-alert:contains('pmproxy')")
749
750 # reacts to service changes from outside; this is asynchronous and the dialog deliberately
751 # does not update automatically, so retry a few times
752 def checkEnabled(expected):
753 for _ in range(10):
754 b.click("#metrics-header-section button.pf-m-secondary")
755 b.wait_visible('#switch-pmproxy')
756 found = b.is_present("#switch-pmproxy" + (":checked" if expected else ":not(:checked)"))
757 b.click(f"{self.pcp_dialog_selector} button.btn-cancel")
758 b.wait_not_present(self.pcp_dialog_selector)
759
760 if found:
761 break
762 time.sleep(1)
763 else:
764 raise testlib.Error("PCP settings dialog did not get expected value")
765
766 m.execute(f"systemctl stop {redis}")
767 checkEnabled(expected=False)
768 m.execute(f"systemctl start {redis}")
769 checkEnabled(expected=True)
770 m.execute("systemctl stop pmproxy")
771 checkEnabled(expected=False)
772 m.execute("systemctl start pmproxy")
773 checkEnabled(expected=True)
774
775
776 @testlib.nondestructive
777 class TestCurrentMetrics(testlib.MachineCase):
778 def setUp(self):
779 super().setUp()
780 m = self.machine
781 # packagekit/dnf often eats a lot of CPU; silence it to have better control over CPU usage
782 packagekitd = "/usr/lib/packagekitd" if m.image == "arch" else "/usr/libexec/packagekitd"
783 m.execute(f"systemctl mask packagekit && killall -9 {packagekitd} && killall -9 dnf || true")
784
785 self.addCleanup(m.execute, "systemctl unmask packagekit")
786 # make sure to clean up our test resource consumers on failures
787 self.addCleanup(m.execute, "systemctl stop cockpittest.slice 2>/dev/null || true")
788 self.addCleanup(m.execute, "su - admin -c 'XDG_RUNTIME_DIR=/run/user/$(id -u admin) "
789 "systemctl --user stop cockpittest.slice 2>/dev/null || true'")
790
791 self.busybox_image = m.execute("podman images --format '{{.Repository}}' | grep busybox").strip()
792 self.login_and_go("/metrics")
793
794 # Disable pre-loading packagekit, dnf consumes tons of memory/CPU and interferes too much
795 self.disable_preload("packagekit")
796
797 def run_as_admin(self, cmd: str) -> str:
798 return self.machine.execute(f"systemd-run --machine=admin@ --quiet --user --collect --pipe --wait /bin/sh -ec '{cmd}'")
799
800 def run_as_admin_background(self, cmd: str, unit: str) -> None:
801 """Asynchronous alternative to `run_as_admin` which can "background" tasks."""
802 m = self.machine
803 m.execute(f"systemd-run --user --machine=admin@ --unit={unit} /bin/sh -ec '{cmd}'")
804 m.execute(f"until systemctl --user --machine=admin@ is-active {unit}; do sleep 1; done")
805
806 def testCPU(self):
807 b = self.browser
808 m = self.machine
809
810 if m.image.startswith(("fedora-", "rhel-")):
811 # HACK - https://bugzilla.redhat.com/show_bug.cgi?id=2461071
812 m.execute("setenforce 0")
813 self.addCleanup(m.execute, "setenforce 1")
814
815 b.wait_timeout(60)
816
817 nproc = m.execute("nproc").strip()
818 b.wait_in_text("#current-cpu-usage", nproc + " CPU")
819 # top CPU core is not visible with just 1 core; our upstream test VMs have only 1 core,
820 # but let's not just assume this for downstream gating/custom VMs
821 if nproc == '1':
822 self.assertFalse(b.is_present("#current-top-cpu-usage"))
823 b.wait_text("#current-cpu-usage-description", "1 CPU")
824 else:
825 b.wait_visible("#current-top-cpu-usage")
826
827 # wait until system settles down
828 b.wait(lambda: b.get_pf_progress_value("#current-cpu-usage") < 20)
829 m.execute("systemd-run --collect --slice cockpittest -p CPUQuota=60% --unit cpu-hog dd if=/dev/urandom of=/dev/null")
830 m.execute("systemd-run --collect --slice cockpittest -p CPUQuota=30% --unit cpu-piglet dd if=/dev/urandom of=/dev/null")
831 try:
832 b.wait(lambda: b.get_pf_progress_value("#current-cpu-usage") > 75)
833 # no other process in the test VM should take > 30% CPU, by the "settles down" assertion above
834 b.wait_text("table[aria-label='Top 5 CPU services'] tbody tr:nth-of-type(1) td[data-label='Service']", "cpu-hog")
835 b.wait_text("table[aria-label='Top 5 CPU services'] tbody tr:nth-of-type(2) td[data-label='Service']", "cpu-piglet")
836
837 # There might be some other processes which take more resources
838 # Keep this logging so we can easily debug which ones we might need to cleanup
839 try:
840 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 1) > 50)
841 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 1) < 70)
842 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 2) > 20)
843 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 2) < 40)
844 except BaseException:
845 print(m.execute("top -b -n 1"))
846 raise
847 finally:
848 m.execute("systemctl stop cpu-hog cpu-piglet")
849 # should go back to idle usage
850 b.wait(lambda: b.get_pf_progress_value("#current-cpu-usage") < 20)
851 # it could be that the table disappears completely if no service has a noticeable CPU usage;
852 # so don't assume the table exists
853 b.wait_not_in_text("#current-metrics-card-cpu", "cpu-hog")
854 b.wait_not_in_text("#current-metrics-card-cpu", "cpu-piglet")
855
856 # Load is a flex, each part looks like "1 min: 1.41,"; wait until the 1min load is low
857 b.wait(lambda: float(b.text("#load-avg .pf-v6-l-flex div:first-child").split()[-1].rstrip(',')) < 5)
858
859 m.execute("systemd-run --collect --slice cockpittest --unit load-hog sh -ec "
860 " 'for i in `seq 50`; do dd if=/dev/urandom of=/dev/zero bs=100K status=none & done; sleep infinity'")
861 try:
862 with b.wait_timeout(120):
863 b.wait(lambda: float(b.text("#load-avg .pf-v6-l-flex div:first-child").split()[-1].rstrip(',')) > 15)
864 finally:
865 m.execute("systemctl stop load-hog 2>/dev/null || true") # ok to fail, as the command exits by itself
866
867 container_name = "pod-cpu-hog"
868 m.execute(f"podman run --rm -d --name {container_name} {self.busybox_image} /bin/dd if=/dev/urandom of=/dev/null")
869 try:
870 container_sha = m.execute(f"podman inspect --format '{{{{.Id}}}}' {container_name}").strip()
871 shortid = container_sha[:12]
872
873 # On some test images the container takes a while to show up
874 with b.wait_timeout(300):
875 b.wait_in_text("#current-metrics-card-cpu", f"pod {shortid}")
876 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 1) > 70)
877
878 # It takes one re-render for the name lookup
879 with b.wait_timeout(30):
880 b.wait_in_text("#current-metrics-card-cpu", f"pod {container_name}")
881 finally:
882 m.execute(f"podman stop -t 0 {container_name}")
883
884 # RHEL-8's podman user containers do not show up as
885 # libpod-$containerid but as podman-3679.scope.
886 if not m.image.startswith("rhel-8"):
887 # copy images for user podman tests; podman insists on user session
888 m.execute(f"podman save {self.busybox_image} | sudo -i -u admin podman load")
889
890 # Test user containers
891 user_container_name = "user-cpu-hog"
892 self.run_as_admin_background(
893 f"podman run --rm -i --name {user_container_name} {self.busybox_image} /bin/dd if=/dev/urandom of=/dev/null",
894 unit=user_container_name)
895
896 # Wait for container to be running as we can't infer this from the systemd unit state
897 self.run_as_admin(f'while [ "$(podman inspect --format {{{{.State.Status}}}} {user_container_name} 2>/dev/null)" != "running" ]; do sleep 1; done')
898 container_sha = self.run_as_admin(f"podman inspect --format '{{{{.Id}}}}' {user_container_name}").strip()
899 shortid = container_sha[:12]
900
901 # On some test images the container takes a while to show up
902 with b.wait_timeout(300):
903 b.wait_in_text("#current-metrics-card-cpu", f"pod {shortid}")
904 b.wait(lambda: topServiceValue(self, "Top 5 CPU services", "%", 1) > 70)
905
906 # It takes one re-render for the name lookup
907 with b.wait_timeout(30):
908 b.wait_in_text("#current-metrics-card-cpu", f"pod {user_container_name}")
909
910 self.run_as_admin(f"podman stop -t 0 {user_container_name}")
911
912 # this settles down slowly, don't wait for becoming really quiet
913 with b.wait_timeout(300):
914 b.wait(lambda: float(b.text("#load-avg .pf-v6-l-flex div:first-child").split()[-1].rstrip(',')) < 10)
915
916 # Files with CPU temperature do not exist, nothing is displayed
917 b.wait_not_present("#current-metrics-card-cpu .temperature")
918
919 # No matching type
920 self.addCleanup(m.execute, "rm -rf /tmp/sensor-sys-class")
921 m.write("/tmp/sensor-sys-class/hwmon/hwmon0/name", "BAT0")
922 m.write("/tmp/sensor-sys-class/hwmon/hwmon0/temp1_input", "40000")
923 m.execute("mount -o bind /tmp/sensor-sys-class /sys/class")
924 self.addCleanup(m.execute, "umount /sys/class")
925 b.logout()
926 self.login_and_go("/metrics")
927
928 b.wait_not_present("#current-metrics-card-cpu .temperature")
929
930 # create files that contain CPU temperature
931 # ARM
932 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/name", "cpu_thermal")
933 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "30000")
934
935 b.logout()
936 self.login_and_go("/metrics")
937
938 b.wait_in_text("#current-metrics-card-cpu", "30 °C")
939 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "45000")
940 b.wait_in_text("#current-metrics-card-cpu", "45 °C")
941
942 # AMD
943 m.execute("rm -rf /tmp/sensor-sys-class/hwmon/hwmon1/*")
944 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/name", "k10temp")
945 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_label", "Tctl")
946 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "40000")
947 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_max", "100000")
948 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_label", "Tccd1")
949 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "35000")
950 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_max", "100000")
951 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp3_label", "Tccd3")
952 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp3_input", "30000")
953 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp3_max", "100000")
954
955 b.logout()
956 self.login_and_go("/metrics")
957
958 b.wait_in_text("#current-metrics-card-cpu", "40 °C")
959 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp3_input", "55000")
960 b.wait_in_text("#current-metrics-card-cpu", "55 °C")
961 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "90000")
962 b.wait_visible("#current-metrics-card-cpu .text-color-warning")
963 b.wait_in_text("#current-metrics-card-cpu .text-color-warning", "90 °C")
964 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "45000")
965 # temp2_input cooled down, temp3_input is the hottest again
966 b.wait_in_text("#current-metrics-card-cpu", "55 °C")
967
968 # atk0110 motherboard
969 m.execute("rm -rf /tmp/sensor-sys-class/hwmon/hwmon1/*")
970 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/name", "atk0110")
971 # MB Temperature (temp2_label) will be ignored
972 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_label", "CPU Temperature")
973 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "50000")
974 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_label", "MB Temperature")
975 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "70000")
976
977 b.logout()
978 self.login_and_go("/metrics")
979
980 b.wait_in_text("#current-metrics-card-cpu", "50 °C")
981 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "95000")
982 b.wait_visible("#current-metrics-card-cpu .text-color-critical")
983 b.wait_in_text("#current-metrics-card-cpu .text-color-critical", "95 °C")
984 # cooled down a little, warning color changes from red to yellow
985 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "85000")
986 b.wait_visible("#current-metrics-card-cpu .text-color-warning")
987 b.wait_in_text("#current-metrics-card-cpu .text-color-warning", "85 °C")
988
989 # intel
990 m.execute("rm -rf /tmp/sensor-sys-class/hwmon/hwmon1/*")
991 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/name", "coretemp")
992 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_label", "Package id 0")
993 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "60000")
994 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_crit", "100000")
995 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_label", "Core 0")
996 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "50000")
997 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_crit", "100000")
998
999 b.logout()
1000 self.login_and_go("/metrics")
1001
1002 b.wait_in_text("#current-metrics-card-cpu", "60 °C")
1003 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "85000")
1004 b.wait_visible("#current-metrics-card-cpu .text-color-warning")
1005 b.wait_in_text("#current-metrics-card-cpu .text-color-warning", "85 °C")
1006 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp2_input", "70000")
1007 # cooled down, warning color is not visible
1008 b.wait_not_present("#current-metrics-card-cpu .text-color-warning")
1009 b.wait_in_text("#current-metrics-card-cpu", "70 °C")
1010
1011 # add second CPU
1012 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/name", "coretemp")
1013 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/temp1_label", "Package id 0")
1014 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/temp1_input", "60000")
1015 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/temp2_label", "Core 0")
1016 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/temp2_input", "75000")
1017
1018 b.logout()
1019 self.login_and_go("/metrics")
1020
1021 # CPU 2 is the hottest
1022 b.wait_in_text("#current-metrics-card-cpu", "75 °C")
1023 m.write("/tmp/sensor-sys-class/hwmon/hwmon2/temp1_input", "80000")
1024 b.wait_in_text("#current-metrics-card-cpu", "80 °C")
1025 # CPU 1 is the hottest again
1026 m.write("/tmp/sensor-sys-class/hwmon/hwmon1/temp1_input", "90000")
1027 b.wait_in_text("#current-metrics-card-cpu", "90 °C")
1028
1029 # Test link to user services
1030 # older releases don't have CPU accounting enabled for user services
1031 if not self.machine.image.startswith("rhel-8-"):
1032 m.execute("su - admin -c 'XDG_RUNTIME_DIR=/run/user/$(id -u admin) systemd-run --user --collect --slice cockpittest -p CPUQuota=60% --unit cpu-userhog dd if=/dev/urandom of=/dev/null'")
1033 # user services are always running underneath [email protected], so these two will compete for row 1 or 2
1034 b.wait_in_text("table[aria-label='Top 5 CPU services'] tbody", "cpu-userhog")
1035 b.click("table[aria-label='Top 5 CPU services'] tbody td[data-label='Service'] a:contains('cpu-userhog')")
1036 b.enter_page("/system/services")
1037 b.wait_in_text(".service-name", "/usr/bin/dd if=/dev/urandom of=/dev/null")
1038
1039 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1040 def testMemory(self):
1041 b = self.browser
1042 m = self.machine
1043
1044 if m.image.startswith(("fedora-", "rhel-")):
1045 # HACK - https://bugzilla.redhat.com/show_bug.cgi?id=2461071
1046 m.execute("setenforce 0")
1047 self.addCleanup(m.execute, "setenforce 1")
1048
1049 # only some images have swap
1050 have_swap = m.execute("swapon --show").strip()
1051 # wait until RAM usage is initialized
1052 b.wait(lambda: b.get_pf_progress_value("#current-memory-usage") > 10)
1053
1054 # our test machines should use a reasonable chunk of available memory
1055 initial_usage = b.get_pf_progress_value("#current-memory-usage")
1056 self.assertGreater(initial_usage, 10)
1057 self.assertLess(initial_usage, 80)
1058 # allocate a chunk of memory; this may cause other stuff to get unmapped,
1059 # thus not exact addition, but usage should go up
1060 size = 300 if have_swap else 200 # MB
1061 self.write_file("/usr/local/bin/memhog.sh", f"""#!/usr/bin/awk -f
1062 BEGIN {{
1063 x = sprintf("%{size}000000s","");
1064 system("touch /tmp/hogged; sleep infinity")
1065 }}""", perm="755")
1066
1067 m.execute("systemd-run --collect --slice cockpittest --unit mem-hog memhog.sh")
1068 m.execute("while [ ! -e /tmp/hogged ]; do sleep 1; done")
1069 # bars update every 3s
1070 time.sleep(8)
1071 hog_usage = b.get_pf_progress_value("#current-memory-usage")
1072 self.assertGreater(hog_usage, initial_usage + 8)
1073
1074 b.wait_text("table[aria-label='Top 5 memory services'] tbody tr:nth-of-type(1) td[data-label='Service']", "mem-hog")
1075 b.wait(lambda: topServiceValue(self, "Top 5 memory services", "Used", 1) > size)
1076 b.wait(lambda: topServiceValue(self, "Top 5 memory services", "Used", 1) < size + 50)
1077
1078 # total memory is shown as tooltip
1079 b.mouse("#current-memory-usage", "mouseenter")
1080 b.wait_in_text(".pf-v6-c-tooltip", "B total")
1081 b.mouse("#current-memory-usage", "mouseleave")
1082
1083 # table entries are links to Services page
1084 b.click("table[aria-label='Top 5 memory services'] tbody tr:nth-of-type(1) td[data-label='Service'] a")
1085 b.enter_page("/system/services")
1086 b.wait_in_text("#path", "/mem-hog.service")
1087 b.wait_in_text(".service-name", "memhog.sh")
1088
1089 b.go("/metrics")
1090 b.enter_page("/metrics")
1091 b.wait_visible("table[aria-label='Top 5 memory services']")
1092
1093 if have_swap:
1094 usage_hog1 = b.get_pf_progress_value("#current-memory-usage")
1095
1096 # use even more memory to trigger swap
1097 m.execute("systemd-run --collect --slice cockpittest --unit mem-hog2 awk "
1098 """'BEGIN { x = sprintf("%750000000s",""); system("touch /tmp/hogged2; sleep infinity") }'""")
1099 m.execute("while [ ! -e /tmp/hogged2 ]; do sleep 1; done")
1100 b.wait(lambda: b.get_pf_progress_value("#current-swap-usage") > 0)
1101
1102 m.execute("systemctl stop mem-hog mem-hog2; rm /tmp/hogged2")
1103
1104 # after stopping both hogs, usage should go down
1105 b.wait(lambda: b.get_pf_progress_value("#current-memory-usage") < usage_hog1)
1106 self.assertGreater(b.get_pf_progress_value("#current-memory-usage"), 10)
1107 b.wait_not_in_text("table[aria-label='Top 5 memory services'] tbody", "mem-hog")
1108
1109 # total swap is shown as tooltip
1110 b.mouse("#current-swap-usage", "mouseenter")
1111 b.wait_in_text(".pf-v6-c-tooltip", "B total")
1112 b.mouse("#current-swap-usage", "mouseleave")
1113 else:
1114 m.execute("systemctl stop mem-hog")
1115
1116 m.execute("rm /tmp/hogged")
1117
1118 # Test Podman containers
1119 container_name = "pod-mem-hog"
1120 # pipe to tail to keep the data in memory
1121 m.execute(f"""
1122 podman run --rm -d --name {container_name} {self.busybox_image} /bin/sh -c '
1123 head -c 300m /dev/zero | tail | sleep infinity'""")
1124
1125 # It takes one re-render for the name lookup
1126 with b.wait_timeout(30):
1127 b.wait_text("table[aria-label='Top 5 memory services'] tbody tr:nth-of-type(1) td[data-label='Service']", f"pod {container_name}")
1128
1129 m.execute(f"podman stop -t 0 {container_name}")
1130
1131 # RHEL-8's podman user containers do not show up as
1132 # libpod-$containerid but as podman-3679.scope.
1133 if not m.image.startswith("rhel-8"):
1134 # copy images for user podman tests; podman insists on user session
1135 m.execute(f"podman save {self.busybox_image} | sudo -i -u admin podman load")
1136
1137 # Test user containers
1138 user_container_name = "user-mem-hog"
1139 cmd = f'podman run --rm -i --name {user_container_name} {self.busybox_image} /bin/sh -c "head -c 300m /dev/zero | tail | sleep infinity"'
1140 self.run_as_admin_background(cmd, user_container_name)
1141
1142 # It takes one re-render for the name lookup
1143 with b.wait_timeout(30):
1144 b.wait_text("table[aria-label='Top 5 memory services'] tbody tr:nth-of-type(2) td[data-label='Service']", f"pod {user_container_name}")
1145
1146 self.run_as_admin(f"podman stop -t 0 {user_container_name}")
1147
1148 # Test link to user services
1149 # older releases don't have memory accounting enabled for user services
1150 if not m.image.startswith("rhel-8"):
1151 m.execute("su - admin -c 'XDG_RUNTIME_DIR=/run/user/$(id -u admin) systemd-run --user --collect --slice cockpittest --unit mem-userhog memhog.sh'")
1152 m.execute("while [ ! -e /tmp/hogged ]; do sleep 1; done")
1153 # The DOM is very volatile and we sometimes click on the
1154 # wrong row, so let's try a couple of times
1155 n = 0
1156 while True:
1157 # user services are always running underneath [email protected], so these two will compete for row 1 or 2
1158 b.wait_in_text("table[aria-label='Top 5 memory services'] tbody", "mem-userhog")
1159 b.click("table[aria-label='Top 5 memory services'] tbody td[data-label='Service'] a:contains('mem-userhog')")
1160 b.enter_page("/system/services")
1161 try:
1162 b.wait_in_text(".service-name", "memhog.sh")
1163 break
1164 except testlib.Error as ex:
1165 if n < 5:
1166 print("WARNING: Got the wrong service, retrying")
1167 else:
1168 raise ex
1169 b.eval_js("window.history.back()")
1170 b.enter_page("/metrics")
1171 n = n + 1
1172
1173 def testDiskIO(self):
1174 b = self.browser
1175 m = self.machine
1176
1177 b.wait_timeout(60)
1178
1179 # test env should be quiet enough to not transmit MB/s
1180 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-read")))
1181 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-write")))
1182 # reading lots of data
1183 m.execute("systemd-run --collect --slice cockpittest --unit disk-read-hog sh -ec 'while true; do echo 3 > /proc/sys/vm/drop_caches; grep -r . /usr >/dev/null; done'")
1184 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("#current-disks-read")))
1185 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-write"))) # this should stay calm
1186 # read in popover
1187 b.click("#current-metrics-card-disks .all-disks-no-gap button")
1188 b.wait_visible(".pf-v6-c-popover .disks-nowrap")
1189 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Read']")))
1190 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Write']"))) # write should stay calm
1191 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='sr0'] [data-label='Read']"))) # other disks should stay calm
1192 # top service should be disk-read-hog
1193 # unsupported on rhel 8 as it uses cgroupv1
1194 if not m.image.startswith("rhel-8"):
1195 b.wait_text_matches("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Service']", "disk-read-hog")
1196 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Read']")))
1197 b.wait(lambda: re.match(r'^0|([0-9.]+ (kB|B)/s)$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Write']"))) # this should stay calm
1198
1199 m.execute("systemctl stop disk-read-hog")
1200 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Read']"))) # back to quiet
1201 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-read"))) # back to quiet
1202 b.click(".pf-v6-c-popover__close > button")
1203 # writing lots of data
1204 m.execute("systemd-run --collect --slice cockpittest --unit disk-write-hog sh -ec "
1205 " 'while true; do dd if=/dev/zero of=/var/tmp/blob bs=1M count=100; done'")
1206 self.addCleanup(m.execute, "rm -f /var/tmp/blob")
1207 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("#current-disks-write")))
1208 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-read"))) # this should stay calm
1209 # write in popover
1210 b.click("#current-metrics-card-disks .all-disks-no-gap button")
1211 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Write']")))
1212 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Read']"))) # read should stay calm
1213 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='sr0'] [data-label='Write']"))) # other disks should stay calm
1214 # top service should be disk-write-hog
1215 # unsupported on rhel 8 as it uses cgroupv1
1216 if not m.image.startswith("rhel-8"):
1217 b.wait_text_matches("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Service']", "disk-write-hog")
1218 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Write']")))
1219 b.wait(lambda: re.match(r'^0|([0-9.]+ (kB|B)/s)$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Read']"))) # this should stay calm
1220
1221 m.execute("systemctl stop disk-write-hog")
1222 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("[aria-label='Disks usage'] [device-name='vda'] [data-label='Write']"))) # back to quiet
1223 b.wait(lambda: re.match(r'^(0|[0-9.]+ (kB|B)/s)$', b.text("#current-disks-write"))) # back to quiet
1224 b.click(".pf-v6-c-popover__close > button")
1225 # top service should be podman container busybox-write-hog
1226 m.execute(f"podman run --rm -d --name busybox-write-hog {self.busybox_image} /bin/ash -c 'while true; do dd if=/dev/urandom of=/testfile bs=20M count=100; done'")
1227 self.addCleanup(m.execute, "podman rm -f busybox-write-hog || true")
1228 b.wait_text_matches("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Service']", "pod busybox-write-hog")
1229 b.wait(lambda: re.match(r'^[0-9.]+ (MB|GB)/s$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Write']")))
1230 b.wait(lambda: re.match(r'^0|([0-9.]+ (kB|B)/s)$', b.text("table[aria-label='Top 5 disk usage services'] tr:first-child td[data-label='Read']"))) # this should stay calm
1231 m.execute('podman stop busybox-write-hog')
1232
1233 # Disk usage
1234
1235 # add 50 MB loopback disk; mount it once rw and once ro
1236 m.execute("""
1237 F=$(mktemp /var/tmp/loop.XXXX)
1238 dd if=/dev/zero of=$F bs=1M count=50
1239 mkfs -t ext3 $F
1240 mkdir -p /var/cockpittest /var/cockpit-ro-test
1241 mount -o loop $F /var/cockpittest
1242 RODEV=$(losetup -f --show $F)
1243 mount -r $RODEV /var/cockpit-ro-test
1244 losetup -d $RODEV
1245 rm $F""")
1246 self.addCleanup(m.execute, "umount /var/cockpittest /var/cockpit-ro-test")
1247
1248 self.assertLess(b.get_pf_progress_value(".pf-v6-c-progress[data-disk-usage-target='/var/cockpittest']"), 5)
1249 progress_sel = ".pf-v6-c-progress[data-disk-usage-target='/var/cockpittest'] .pf-v6-c-progress__status"
1250 # free size is anything between 40 and 50 MB
1251 self.assertRegex(b.text(progress_sel), r"^4\d\.\d MB free$")
1252 # total size is shown in tooltip
1253 b.mouse(progress_sel, "mouseenter")
1254 b.wait_in_text(".pf-v6-c-tooltip", "total")
1255 # total size is anything between 40 and 50 MB
1256 self.assertRegex(b.text(".pf-v6-c-tooltip"), r"^4\d\.\d MB total$")
1257 b.mouse(progress_sel, "mouseleave")
1258 # read-only loop devices are not shown
1259 self.assertFalse(b.is_present(".pf-v6-c-progress[data-disk-usage-target='/var/cockpit-ro-test']"))
1260
1261 m.execute("dd if=/dev/zero of=/var/cockpittest/blob bs=1M count=40")
1262 b.wait(lambda: b.get_pf_progress_value(".pf-v6-c-progress[data-disk-usage-target='/var/cockpittest']") >= 90)
1263
1264 # clicking on progress leads to the storage page
1265 # CoreOS images don't have cockpit-storaged; all others including bootc do
1266 if "coreos" not in m.image:
1267 self.assertTrue(b.is_present("#current-disks-usage button"))
1268 b.click(progress_sel)
1269 b.enter_page("/storage")
1270 # weird -- storage page does not show transient mount points, only permanent ones; so check for the device
1271 dev = m.execute("findmnt --noheadings -o SOURCE /var/cockpittest").strip()
1272 b.wait_in_text('[data-test-card-title="Storage"]', dev.replace("/dev/", ""))
1273
1274 b.go("/metrics")
1275 b.enter_page("/metrics")
1276 b.wait_visible(progress_sel)
1277 b.logout()
1278
1279 # no host-local configs/overrides in beiboot mode
1280 if testlib.isBeibootLogin():
1281 return
1282
1283 # without cockpit-storaged, mounts are not links
1284 self.write_file("/etc/cockpit/storaged.override.json",
1285 '{"conditions": [{"path-exists": "/disable"}]}')
1286 self.login_and_go("/metrics")
1287 b.wait_visible(progress_sel)
1288 self.assertFalse(b.is_present("#current-disks-usage button"))
1289
1290 @testlib.skipOstree("no netcat on CoreOS")
1291 def testNetwork(self):
1292 b = self.browser
1293 m = self.machine
1294
1295 # add synthetic veth which is guaranteed quiet
1296 m.execute("ip link add name cockpittest1 type veth peer name vcockpittest1")
1297 self.addCleanup(m.execute, "ip link del dev cockpittest1")
1298
1299 # has expected interfaces
1300 b.wait_in_text("[aria-label='Network usage'] [data-interface='cockpittest1']", "cockpittest1")
1301 b.wait_in_text("[aria-label='Network usage'] [data-interface='lo']", "lo")
1302
1303 # can jump to network interface details
1304 b.wait_visible("[aria-label='Network usage'] [data-interface='cockpittest1'] button")
1305 b.wait_visible("[aria-label='Network usage'] [data-interface='lo'] button")
1306
1307 def rateMatches(label, regexp):
1308 text = b.text(f"[aria-label='Network usage'] [data-interface='lo'] td[data-label='{label}']")
1309 return re.match(regexp, text) is not None
1310
1311 # loopback is quiet enough to not transmit MB/s
1312 b.wait(lambda: rateMatches("In", r'^(0|[0-9.]+ (kB|B)/s)$'))
1313 b.wait(lambda: rateMatches("Out", r'^(0|[0-9.]+ (kB|B)/s)$'))
1314 # pipe lots of data through lo
1315 m.execute("systemd-run --collect --slice cockpittest --unit lo-hog sh -ec "
1316 " 'nc -n -vv -l 2000 > /dev/null & sleep 1; nc -vv localhost 2000 </dev/zero'")
1317 b.wait(lambda: rateMatches("In", r'^[0-9.]+ (MB|GB)/s$'))
1318 b.wait(lambda: rateMatches("Out", r'^[0-9.]+ (MB|GB)/s$'))
1319 m.execute("systemctl stop lo-hog")
1320
1321 # nothing happens on cockpittest1
1322 b.wait_text("[aria-label='Network usage'] [data-interface='cockpittest1'] td[data-label='In']", "0")
1323 b.wait_text("[aria-label='Network usage'] [data-interface='cockpittest1'] td[data-label='Out']", "0")
1324
1325 b.click("[aria-label='Network usage'] [data-interface='lo'] button")
1326 b.enter_page("/network")
1327 b.wait_in_text("#network-interface-name", "lo")
1328 b.wait_in_text(".network-interface-details", "This device cannot be managed here.")
1329
1330 b.go("/metrics")
1331 b.enter_page("/metrics")
1332 b.click("[aria-label='Network usage'] [data-interface='cockpittest1'] button")
1333 b.enter_page("/network")
1334 b.wait_in_text("#network-interface-name", "cockpittest1")
1335 b.wait_in_text(".network-interface-details", "This device cannot be managed here.")
1336
1337
1338 @testlib.skipImage("TODO: Arch Linux packagekit support", "arch")
1339 @testlib.skipImage("image has pcp installed, but cannot be removed", "*-bootc")
1340 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1341 class TestMetricsPackages(packagelib.PackageCase):
1342 pcp_dialog_selector = "#pcp-settings-modal"
1343
1344 def testBasic(self):
1345 b = self.browser
1346 m = self.machine
1347
1348 # Packaging python in the correct directory generates some noisy *pyc*
1349 # files on at least Fedora, for testing purposes extend PYTHONPATH and
1350 # install to /usr/local/lib in the fake python3-pcp package.
1351 self.write_file("/etc/environment", "PYTHONPATH=/usr/local/lib")
1352
1353 redis_service = redisService(m.image)
1354 redis_package = "valkey" if redis_service == "valkey" else "redis"
1355 extra_packages = []
1356 if redis_package == "valkey" and m.image.startswith(("fedora", "rhel-10", "centos-10")):
1357 # Fedora has a compat package that we need to
1358 # remove at the same time as valkey.
1359 # Fedora split out valkey to more packages as
1360 # well which we need to remove.
1361 extra_packages += m.execute("rpm -qa valkey-*").split("\n")
1362
1363 if m.ostree_image:
1364 self.login_and_go("/metrics")
1365 b.wait_in_text(".pf-v6-c-empty-state", "PCP is missing")
1366 b.wait_not_present(".pf-v6-c-empty-state button.pf-m-primary")
1367
1368 b.click("#metrics-header-section button.pf-m-secondary")
1369 b.wait_visible(self.pcp_dialog_selector)
1370 b.wait_visible("#switch-pmlogger:not(:checked)")
1371 # no packagekit, can't enable
1372 b.wait_visible("#switch-pmlogger:disabled")
1373 b.wait_visible("#switch-pmproxy:disabled")
1374 return
1375
1376 if m.image.startswith("debian") or m.image.startswith("ubuntu"):
1377 m.execute("dpkg --purge libpcp-pmda-perl python3-pcp pcp-dstat pcp redis redis-server")
1378 # HACK: pcp does not clean up correctly on Debian https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=986074
1379 m.execute("rm -f /etc/systemd/system/pmlogger.service.requires/pmlogger_farm.service")
1380 else:
1381 m.execute(f"rpm --erase --verbose pcp python3-pcp {redis_package} {' '.join(extra_packages)}")
1382 if "centos-8" in m.image or "rhel-8" in m.image:
1383 # RHEL 8 ships this in a module, make sure that doesn't hide our fake package
1384 m.execute("dnf module disable -y redis || true")
1385
1386 dummy_service = "[Service]\nExecStart=/bin/sleep infinity\n[Install]\nWantedBy=multi-user.target\n"
1387
1388 # Fake it enough for cockpit.channels.pcp to import successfully
1389 cpcp_content = {
1390 "/usr/local/lib/pcp.py": "pmapi = True",
1391 "/usr/local/lib/cpmapi.py": "",
1392 }
1393 pcp_content = {
1394 "/lib/systemd/system/pmlogger.service": dummy_service,
1395 "/lib/systemd/system/pmproxy.service": dummy_service,
1396 }
1397 redis_content = {
1398 f"/lib/systemd/system/{redis_service}.service": dummy_service,
1399 }
1400
1401 self.createPackage("python3-pcp", "999", "1", content=cpcp_content, depends="pcp")
1402 self.createPackage("pcp", "999", "1", content=pcp_content, postinst="systemctl daemon-reload")
1403 self.createPackage(redis_package, "999", "1", content=redis_content, postinst="systemctl daemon-reload")
1404 self.enableRepo(refresh_repo=self.backend != "dnf5")
1405
1406 # install c-pcp from the empty state
1407 self.login_and_go("/metrics")
1408 b.wait_in_text(".pf-v6-c-empty-state", "Install PCP support")
1409 b.click(".pf-v6-c-empty-state button.pf-m-primary")
1410 b.click("#dialog button:contains('Install')")
1411 b.wait_not_present("#dialog")
1412 b.wait_in_text(".pf-v6-c-empty-state", "Metrics history could not be loaded")
1413 b.logout()
1414
1415 # install c-pcp from the Metrics Settings dialog
1416 self.removePackages(["python3-pcp", "pcp"])
1417 self.login_and_go("/metrics")
1418 b.click("#metrics-header-section button.pf-m-secondary")
1419 b.wait_visible(self.pcp_dialog_selector)
1420 b.wait_visible("#switch-pmlogger:not(:checked)")
1421 b.click("#switch-pmlogger")
1422 b.wait_visible("#switch-pmlogger:checked")
1423 applySettings(b, self.pcp_dialog_selector)
1424 # install dialog
1425 b.click("#dialog button:contains('Install')")
1426 b.wait_not_present("#dialog")
1427 # sets up pmlogger correctly; this is asynchronous, as it happens in the background after closing install dialog
1428 m.execute('until [ $(systemctl is-enabled pmlogger) = enabled ]; do sleep 1; done')
1429 # also needs to wait for activating → active
1430 m.execute('until [ $(systemctl is-active pmlogger) = active ]; do sleep 1; done')
1431 b.wait_in_text(".pf-v6-c-empty-state", "Metrics history could not be loaded")
1432 b.wait_in_text(".pf-v6-c-empty-state", "pmlogger.service is failing to collect data")
1433 # wait till systemd actions are finished before opening a new dialog,
1434 # not doing so creates a race where Dialogs.close() can be called when opening a new dialog.
1435 b.wait_visible("#metrics-header-section button.pf-m-secondary[data-test-install-finished='done']")
1436
1437 # HACK: There's a PF bug that makes the memory tooltip stay around forever
1438 # once opening the PCP config dialog; make sure it goes away, to avoid
1439 # obscuring the pmproxy switch
1440 if b.is_present(".pf-v6-c-tooltip"):
1441 b.mouse("#current-memory-usage-description", "mouseleave")
1442 b.wait_not_present(".pf-v6-c-tooltip")
1443
1444 # install redis
1445 b.click("#metrics-header-section button.pf-m-secondary")
1446 b.wait_visible(self.pcp_dialog_selector)
1447 b.wait_visible("#switch-pmproxy:not(:checked)")
1448 b.click("#switch-pmproxy")
1449 b.wait_visible("#switch-pmproxy:checked")
1450 applySettings(b, self.pcp_dialog_selector)
1451 # install dialog
1452 b.click("#dialog button:contains('Install')")
1453 b.wait_not_present("#dialog")
1454 # sets up redis correctly; this is asynchronous, as it happens in the background after closing install dialog
1455 m.execute('until [ $(systemctl is-enabled pmproxy) = enabled ]; do sleep 1; done')
1456 m.execute('until [ $(systemctl is-active pmproxy) = active ]; do sleep 1; done')
1457 m.execute(f'until [ $(systemctl is-active {redis_service}) = active ]; do sleep 1; done')
1458 self.assertIn(redis_service, m.execute("systemctl show -p Wants --value pmproxy").strip())
1459
1460
1461 @testlib.skipOstree("no PCP support")
1462 class TestMultiCPU(testlib.MachineCase):
1463
1464 provision = {
1465 "0": {"cpus": 2}
1466 }
1467
1468 def testCPUUsage(self):
1469 b = self.browser
1470 m = self.machine
1471
1472 # Disable pre-loading packagekit, dnf consumes tons of memory/CPU and interferes too much
1473 self.disable_preload("packagekit")
1474
1475 prepareArchive(m, "2corescpu.tar.gz", 1598971635)
1476 self.login_and_go("/metrics")
1477
1478 # one core is busy, the other idle -- that should be 50% total usage
1479 self.assertGreaterEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=False, hour=1598968800000, minute=44), 0.2)
1480 self.assertLessEqual(getCompressedMinuteValue(test=self, g_type="cpu", saturation=False, hour=1598968800000, minute=44), 0.55)
1481
1482 # next minute, both cores are busy
1483 self.assertGreaterEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598968800000, minute=45), 0.5)
1484 self.assertLessEqual(getMaximumSpike(test=self, g_type="cpu", saturation=False, hour=1598968800000, minute=45), 1.0)
1485
1486 b.wait_timeout(60)
1487
1488 # Test current usage of cores
1489 b.wait_text("#current-cpu-usage-description", "2 CPUs")
1490 b.wait(lambda: b.get_pf_progress_value("#current-cpu-usage") < 20)
1491 m.execute("systemd-run --collect --slice cockpittest -p CPUQuota=50% --unit cpu-hog dd if=/dev/urandom of=/dev/null")
1492 m.execute("systemd-run --collect --slice cockpittest -p CPUQuota=20% --unit cpu-piglet dd if=/dev/urandom of=/dev/null")
1493 # View all CPUs
1494 b.click("#current-metrics-card-cpu button")
1495 b.wait(lambda: int(b.text(".pf-v6-c-popover .cpu-all dd:nth-of-type(1)")[:-1]) > 40)
1496 b.wait(lambda: int(b.text(".pf-v6-c-popover .cpu-all dd:nth-of-type(2)")[:-1]) > 15)
1497 b.click(".pf-v6-c-popover button")
1498 b.wait_not_present(".pf-v6-c-popover")
1499
1500 # the top CPU core runs cpu-hog
1501 b.wait(lambda: b.get_pf_progress_value("#current-top-cpu-usage") >= 38)
1502 # the hoglet gets scheduled between core 1 and 2
1503 b.wait(lambda: b.get_pf_progress_value("#current-top-cpu-usage") <= 80)
1504 # looks like "average: 45% max: 60%"
1505 b.wait(lambda: int(b.text("#current-cpu-usage .pf-v6-c-progress__status").split()[-1].rstrip('%')) >= 38)
1506 b.wait(lambda: int(b.text("#current-cpu-usage .pf-v6-c-progress__status").split()[-1].rstrip('%')) <= 80)
1507
1508 self.allow_journal_messages('.*apparmor="DENIED" operation="open" class="file" profile="hostname" name="/proc/sys/net/ipv6/conf/all/disable_ipv6".*')
1509
1510
1511 @testlib.skipOstree("no PCP support")
1512 @testlib.skipImage("TODO: fix for OpenSUSE", "opensuse-tumbleweed")
1513 class TestGrafanaClient(testlib.MachineCase):
1514
1515 provision = {
1516 "0": {"address": "10.111.112.1/20", "dns": "10.111.112.1"},
1517 # forward Grafana port, so that a developer can connect to it with local browser
1518 "services": {"image": "services", "forward": {"3000": 3000}}
1519 }
1520
1521 def testBasic(self):
1522 m = self.machine
1523 b = self.browser
1524 mg = self.machines['services']
1525 pcp_dialog_selector = "#pcp-settings-modal"
1526
1527 # Disable pre-loading packagekit, dnf needs-restarting (dnf 4) consumes tons of cpu/memory on RHEL-10-1
1528 self.disable_preload("packagekit")
1529
1530 # HACK - https://github.com/performancecopilot/pcp/issues/2573 https://launchpad.net/bugs/2152271
1531 # Unset PMPROXY_LOCAL, we want it to listen externally.
1532 if m.image == "ubuntu-2604":
1533 m.execute("sed -i 's/^PMPROXY_LOCAL/# PMPROXY_LOCAL/' /etc/default/pmproxy")
1534
1535 # avoid dynamic host name changes during PCP data collection, and start from clean slate
1536 m.execute("""systemctl stop pmlogger || true
1537 systemctl reset-failed pmlogger || true
1538 rm -rf /var/log/pcp/pmlogger/*
1539 hostnamectl set-hostname grafana-client""")
1540
1541 # start Grafana
1542 mg.execute("/root/run-grafana")
1543 m.execute("until curl --silent --show-error http://10.111.112.100:3000; do sleep 1; done")
1544 # enable PCP plugin; like on Cog (Configuration) menu → Plugins → Performance Co-Pilot → Enable
1545 mg.execute("curl --silent --show-error -u admin:foobar -d '' 'http://127.0.0.1:3000/api/plugins/performancecopilot-pcp-app/settings?enabled=true'")
1546 self.login_and_go("/metrics")
1547
1548 # pmlogger data collection is not running initially
1549 b.wait_in_text(".pf-v6-c-empty-state", "Metrics history could not be loaded")
1550 b.wait_in_text(".pf-v6-c-empty-state", "pmlogger.service is not running")
1551 b.click(".pf-v6-c-empty-state button.pf-m-primary")
1552 b.wait_visible(pcp_dialog_selector)
1553 b.wait_visible("#switch-pmlogger:not(:checked)")
1554 b.click("#switch-pmlogger")
1555 b.wait_visible("#switch-pmlogger:checked")
1556 applySettings(b, pcp_dialog_selector)
1557
1558 # enable pmproxy+redis (none of our test OSes have both of them running by default)
1559 b.click("#metrics-header-section button.pf-m-secondary")
1560 b.wait_visible(pcp_dialog_selector)
1561 b.wait_visible("#switch-pmproxy:not(:checked)")
1562 b.click('#switch-pmproxy')
1563 b.wait_visible('#switch-pmproxy:checked')
1564 applySettings(b, pcp_dialog_selector)
1565
1566 # enable pmproxy service in firewalld in the alert
1567 b.wait_visible("#firewalld-request-pmproxy")
1568 b.click(".pf-v6-c-alert button.pf-m-primary")
1569
1570 # we are done with the Cockpit side
1571 b.logout()
1572 b.kill()
1573
1574 # Log into Grafana (usually http://127.0.0.2:3002 if you do it interactively)
1575 bg = testlib.Browser(mg.forward['3000'], label=self.label() + "-" + mg.label, machine=self)
1576
1577 # HACK: Grafana uses zone.js which patches the global Promise object
1578 # this breaks webdriver's `awaitPromise` logic, so none of our Browser.wait_*() work
1579 def bgwait_present(sel):
1580 for _ in range(15):
1581 if bg.is_present(sel):
1582 break
1583 time.sleep(1)
1584 else:
1585 raise testlib.Error("timed out waiting for " + sel)
1586
1587 # we don't get the Promise result of ph_find_scroll_into_view, use JS events
1588 def bgclick(sel):
1589 bgwait_present(sel)
1590 bg.mouse(sel, "click", x=1)
1591
1592 try:
1593 bg.open("/")
1594 bgwait_present("input[name='password']")
1595 testlib.wait(lambda: "Welcome to Grafana" in bg.text("body"))
1596 bg.set_input_text("input[name='user']", "admin")
1597 bg.set_input_text("input[name='password']", "foobar")
1598 bgclick("button:contains('Log in')")
1599 testlib.wait(lambda: "Add your first data source" in bg.text("body"))
1600
1601 # Add the PCP redis data source for our client machine
1602 # Cog (Configuration) menu → Data Sources → Add
1603 # Select PCP redis, HTTP URL http://10.111.112.1:44322
1604 redis_url = 'http://10.111.112.1:44322'
1605 bg.open("/datasources/new")
1606 bgclick("[aria-label='Add new data source PCP Redis']")
1607 bgwait_present("input[placeholder='http://localhost:44322']")
1608 bg.set_input_text("input[placeholder='http://localhost:44322']", redis_url)
1609 bgclick("button:contains('Save &')") # Save & [tT]est
1610 testlib.wait(lambda: "Data source is working" in bg.text("body"))
1611
1612 # Grafana auto-discovers "host" variable for incoming metrics; it takes a while to receive the first
1613 # measurement; that event is not observable directly in Grafana, and the dashboard does not auto-update to
1614 # new variables; so probe the API until it appears
1615 testlib.wait(lambda: "grafana-client" in mg.execute(f"curl --max-time 10 --silent --show-error '{redis_url}/series/labels?names=hostname'"), delay=10, tries=30)
1616 # ... and the load metrics as well
1617 testlib.wait(lambda: mg.execute(f"curl --max-time 10 --silent --show-error '{redis_url}/series/query?expr=kernel.all.load'").strip() != '[]', delay=10, tries=30)
1618
1619 # Switch to "Dashboards" tab, import "Host Overview"
1620 bgclick("a[href$='/dashboards'][role=tab]")
1621 testlib.wait(lambda: "Loading" not in bg.text("body"))
1622 # Assert that PCP Redis: Host overview is the first row.
1623 bgwait_present(".filter-table tr:first-of-type:contains('PCP Redis: Host Overview')")
1624 bgclick("tr:first-of-type button:contains('Import')")
1625 bgwait_present(".filter-table tr:first-of-type:contains('PCP Redis: Host Overview')")
1626 bgwait_present("tr:first-of-type button:contains('Re-import')")
1627
1628 # .. and the dashboard name becomes clickable
1629 bgclick("a:contains('PCP Redis: Host Overview')")
1630
1631 # expect the hostname in the dashboard controls
1632 bgwait_present("[data-testid*='link text grafana-client']")
1633
1634 # expect a "Load average" panel with sensible numbers
1635 load_avg_sel = "section[data-testid*='Load average'],div[data-testid*='Load average']"
1636 testlib.wait(lambda: "minute" in bg.text(load_avg_sel))
1637 self.assertRegex(bg.text(load_avg_sel), r"[0-9]\.[0-9]")
1638 except Exception:
1639 bg.snapshot("FAIL-grafana")
1640 raise
1641 finally:
1642 bg.kill()
1643
1644
1645 if __name__ == '__main__':
1646 testlib.test_main()