Cyberpunk 2077 look for the server view, refreshed every second
Rajdhani font (OFL), chamfered/glitch drawing kit, Docker list every 5 s and process ranking over 3 s windows so the 1 s refresh stays cheap and calm. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
edba341f30
commit
5e64bfb64e
15 files changed
+524
-95
No files matched your search
@@ -1,13 +1,14 @@
|
|||||||
# second-screen
|
# second-screen
|
||||||
|
|
||||||
A second 3.5" Turing Smart Screen (Rev A) on the Coolify home server, next to the bus board
|
A second 3.5" Turing Smart Screen (Rev A) on the Coolify home server, next to the bus board
|
||||||
(`bus-department-schedule`). One Docker container shows **one view at a time**, drawn in the style of a
|
(`bus-department-schedule`). One Docker container shows **one view at a time**: a Casio digital watch (slanted
|
||||||
Casio digital watch (slanted 7-segment digits, pale LCD green):
|
7-segment digits, pale LCD green) for the weather, and a Cyberpunk 2077 look (yellow/cyan on black, chamfered
|
||||||
|
shapes, glitch numbers) for the server stats:
|
||||||
|
|
||||||
| `VIEW` | Shows |
|
| `VIEW` | Shows |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `weather` | Czech weekday strip, big `HH:MM` with seconds, date, current weather for Zlín, today's max/min, highest rain chance and a 12-hour rain probability bar graph with the total mm |
|
| `weather` | Czech weekday strip, big `HH:MM` with seconds, date, current weather for Zlín, today's max/min, highest rain chance and a 12-hour rain probability bar graph with the total mm |
|
||||||
| `server` | CPU / RAM / disk bars, load, CPU temperature, uptime, Docker containers (readable names and status) and the busiest processes |
|
| `server` | Cyberpunk style: CPU / RAM / disk gauges (red from 80 %), load, CPU temperature, uptime, Docker containers (readable names and status chips) and the busiest processes. Refreshed every second; the container list every 5 s and the process ranking over 3 s windows |
|
||||||
|
|
||||||
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
Design: `docs/superpowers/specs/2026-10-22-second-screen-design.md`.
|
||||||
Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/previews/`.
|
Plan: `docs/superpowers/plans/2026-10-22-second-screen.md`. Previews: `docs/previews/`.
|
||||||
@@ -89,3 +90,8 @@ The screen library is pinned to one upstream commit in the `Dockerfile` (`LCD_CO
|
|||||||
and time grows with the bytes sent. So after the first frame the runner sends only the rectangles that changed
|
and time grows with the bytes sent. So after the first frame the runner sends only the rectangles that changed
|
||||||
(`regions.py`), a full frame when more than 60 % of the screen changed or after any failed push, and a full refresh
|
(`regions.py`), a full frame when more than 60 % of the screen changed or after any failed push, and a full refresh
|
||||||
every 15 minutes. The weather seconds are a small patch once per second.
|
every 15 minutes. The weather seconds are a small patch once per second.
|
||||||
|
|
||||||
|
## Fonts
|
||||||
|
|
||||||
|
`assets/fonts/Roboto-Bold.ttf` (Apache 2.0, from the screen library) is used by the weather view;
|
||||||
|
`Rajdhani-Bold.ttf` / `Rajdhani-SemiBold.ttf` (SIL Open Font License, see `Rajdhani-OFL.txt`) by the server view.
|
||||||
Binary file not shown.
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright (c) 2014, Indian Type Foundry ([email protected]).
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
@@ -0,0 +1,108 @@
|
|||||||
|
"""Cyberpunk-2077-style drawing kit: black scanlined background, yellow/cyan/red, chamfered shapes, glitch text."""
|
||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Sequence
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
|
||||||
|
W, H = 480, 320
|
||||||
|
BG = (9, 9, 14)
|
||||||
|
SCAN = (13, 13, 20)
|
||||||
|
YELLOW = (252, 238, 10)
|
||||||
|
CYAN = (0, 240, 255)
|
||||||
|
RED = (255, 38, 74)
|
||||||
|
MAGENTA = (255, 0, 160)
|
||||||
|
DIM = (38, 38, 52)
|
||||||
|
TEXT = (226, 226, 232)
|
||||||
|
GREY = (120, 120, 140)
|
||||||
|
INK = (10, 10, 10)
|
||||||
|
|
||||||
|
FONT_DIR = Path(__file__).parent / "assets" / "fonts"
|
||||||
|
HOT_FROM = 80 # gauges turn red at this percentage
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=None)
|
||||||
|
def font(size: int, bold: bool = True) -> ImageFont.FreeTypeFont:
|
||||||
|
return ImageFont.truetype(str(FONT_DIR / ("Rajdhani-Bold.ttf" if bold else "Rajdhani-SemiBold.ttf")), size)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _background() -> Image.Image:
|
||||||
|
img = Image.new("RGB", (W, H), BG)
|
||||||
|
d = ImageDraw.Draw(img)
|
||||||
|
for y in range(0, H, 3):
|
||||||
|
d.line((0, y, W, y), fill=SCAN)
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def background() -> Image.Image:
|
||||||
|
"""A fresh copy of the scanlined black background."""
|
||||||
|
return _background().copy()
|
||||||
|
|
||||||
|
|
||||||
|
def chamfer(d: ImageDraw.ImageDraw, box: tuple[int, int, int, int], cut: int, outline=None, fill=None,
|
||||||
|
width: int = 1, cuts: str = "tl br") -> None:
|
||||||
|
"""A rectangle with the named corners (tl tr br bl) cut off at 45 degrees."""
|
||||||
|
x0, y0, x1, y1 = box
|
||||||
|
c = cut
|
||||||
|
pts: list[tuple[int, int]] = []
|
||||||
|
pts.append((x0 + c, y0) if "tl" in cuts else (x0, y0))
|
||||||
|
pts.append((x1 - c, y0) if "tr" in cuts else (x1, y0))
|
||||||
|
if "tr" in cuts:
|
||||||
|
pts.append((x1, y0 + c))
|
||||||
|
pts.append((x1, y1 - c) if "br" in cuts else (x1, y1))
|
||||||
|
if "br" in cuts:
|
||||||
|
pts.append((x1 - c, y1))
|
||||||
|
pts.append((x0 + c, y1) if "bl" in cuts else (x0, y1))
|
||||||
|
if "bl" in cuts:
|
||||||
|
pts.append((x0, y1 - c))
|
||||||
|
if "tl" in cuts:
|
||||||
|
pts.append((x0, y0 + c))
|
||||||
|
if fill is not None:
|
||||||
|
d.polygon(pts, fill=fill)
|
||||||
|
if outline is not None:
|
||||||
|
d.line(pts + [pts[0]], fill=outline, width=width)
|
||||||
|
|
||||||
|
|
||||||
|
def glitch_text(d: ImageDraw.ImageDraw, xy: tuple[float, float], text: str, f, main=YELLOW) -> None:
|
||||||
|
"""Text with a cyan and a red copy offset to either side (chromatic aberration)."""
|
||||||
|
x, y = xy
|
||||||
|
d.text((x - 1.5, y), text, font=f, fill=CYAN)
|
||||||
|
d.text((x + 1.5, y), text, font=f, fill=RED)
|
||||||
|
d.text((x, y), text, font=f, fill=main)
|
||||||
|
|
||||||
|
|
||||||
|
def slanted_bar(d: ImageDraw.ImageDraw, x: float, y: float, pct: float | None, h: float, n: int,
|
||||||
|
seg_w: float, gap: float, slant: float = 5, hot: float = HOT_FROM) -> None:
|
||||||
|
"""Segmented bar of slanted parallelograms: yellow, red from `hot` percent, unlit segments dark."""
|
||||||
|
lit = 0 if pct is None else max(0, min(n, round(pct / 100 * n)))
|
||||||
|
colour = RED if pct is not None and pct >= hot else YELLOW
|
||||||
|
for i in range(n):
|
||||||
|
x0 = x + i * (seg_w + gap)
|
||||||
|
d.polygon([(x0 + slant, y), (x0 + seg_w + slant, y), (x0 + seg_w, y + h), (x0, y + h)],
|
||||||
|
fill=colour if i < lit else DIM)
|
||||||
|
|
||||||
|
|
||||||
|
def tag(d: ImageDraw.ImageDraw, xy: tuple[int, int], text: str, f, colour=YELLOW, ink=INK) -> tuple[int, int, int, int]:
|
||||||
|
"""A chamfered label sized from its text; returns its box."""
|
||||||
|
left, top, right, bottom = d.textbbox((0, 0), text, font=f)
|
||||||
|
x, y = xy
|
||||||
|
box = (x, y, x + (right - left) + 20, y + (bottom - top) + 8)
|
||||||
|
chamfer(d, box, 7, fill=colour, cuts="tl br")
|
||||||
|
d.text((x + 10 - left, y + 4 - top), text, font=f, fill=ink)
|
||||||
|
return box
|
||||||
|
|
||||||
|
|
||||||
|
def fit(d: ImageDraw.ImageDraw, text: str, f, max_w: float) -> str:
|
||||||
|
"""`text`, shortened with an ellipsis until it is at most max_w pixels wide."""
|
||||||
|
if d.textlength(text, font=f) <= max_w:
|
||||||
|
return text
|
||||||
|
while text and d.textlength(text + "…", font=f) > max_w:
|
||||||
|
text = text[:-1]
|
||||||
|
return text + "…"
|
||||||
|
|
||||||
|
|
||||||
|
def hazard_stripe(d: ImageDraw.ImageDraw, x: int, y: int, length: int, h: int = 6, step: int = 12) -> None:
|
||||||
|
"""Yellow diagonal hazard stripes."""
|
||||||
|
for i in range(0, length, step * 2):
|
||||||
|
d.polygon([(x + i, y), (x + i + step, y), (x + i + step - h, y + h), (x + i - h, y + h)], fill=YELLOW)
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 91 KiB |
@@ -171,3 +171,12 @@ Reading host processes may need `pid: host`; builder decides the narrowest setup
|
|||||||
dropping the top-processes section.
|
dropping the top-processes section.
|
||||||
- **Gitea repo creation and removal of the `apod-test` leftovers** are not yet answered by the
|
- **Gitea repo creation and removal of the `apod-test` leftovers** are not yet answered by the
|
||||||
owner: do not create the remote repo, push, or delete anything on the server without asking.
|
owner: do not create the remote repo, push, or delete anything on the server without asking.
|
||||||
|
|
||||||
|
## Addendum 2026-10-22: server view restyle and refresh rate
|
||||||
|
|
||||||
|
After deployment the owner asked for the server view in a **Cyberpunk 2077** style (approved from a mockup:
|
||||||
|
black scanlined background, yellow/cyan/red, chamfered shapes, glitch-offset numbers, Rajdhani font) and a
|
||||||
|
faster refresh than 5 s. The screen link moves about 150 KB/s (measured), so the runner now sends only the changed
|
||||||
|
rectangles of each frame (`regions.py`), which makes a 1 s refresh cost about 4 % of the link. The weather view
|
||||||
|
keeps its Casio style. Stats are read every second; Docker is asked every 5 s and processes are ranked over 3 s
|
||||||
|
windows to stop the list flickering. The server view is marked stale after 10 s.
|
||||||
+1
-1
@@ -10,7 +10,7 @@ from weather_data import fetch_weather
|
|||||||
from weather_view import WeatherView
|
from weather_view import WeatherView
|
||||||
|
|
||||||
WEATHER_REFRESH_S = 15 * 60
|
WEATHER_REFRESH_S = 15 * 60
|
||||||
SERVER_REFRESH_S = 5
|
SERVER_REFRESH_S = 1
|
||||||
|
|
||||||
|
|
||||||
class UnknownView(Exception):
|
class UnknownView(Exception):
|
||||||
|
|||||||
+75
-65
@@ -1,19 +1,18 @@
|
|||||||
"""Casio-style server stats: CPU/RAM/disk bars, load, temperature, uptime, containers, busiest processes."""
|
"""Cyberpunk-style server stats: CPU/RAM/disk gauges, load, temperature, uptime, containers, busiest processes."""
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from PIL import Image, ImageDraw
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
import lcdkit
|
import cyber
|
||||||
from lcdkit import BG, H, INK, W
|
from cyber import CYAN, GREY, INK, MAGENTA, RED, TEXT, W, H, YELLOW
|
||||||
from poller import Poller
|
from poller import Poller
|
||||||
from stats_data import Container, Stats, status_label
|
from stats_data import Container, Stats, status_label
|
||||||
from view import Patch
|
from view import Patch
|
||||||
|
|
||||||
|
TITLE = "HOME // SERVER"
|
||||||
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
ATTENTION = ("UNHEALTHY", "RESTART", "EXITED")
|
||||||
CONTAINER_ROWS = 7
|
CONTAINER_ROWS = 5
|
||||||
ROW_STEP, ROWS_TOP = 17, 184
|
GAUGES = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 94), ("DISK", "disk_pct", 134))
|
||||||
DIGITS = dict(w=16, h=26, t=3, gap=5) # small segment digits used for all numbers
|
|
||||||
BAR_ROWS = (("CPU", "cpu_pct", 54), ("RAM", "mem_pct", 88), ("DISK", "disk_pct", 122))
|
|
||||||
|
|
||||||
|
|
||||||
def fmt_uptime(seconds: float | None) -> str:
|
def fmt_uptime(seconds: float | None) -> str:
|
||||||
@@ -27,17 +26,9 @@ def fmt_uptime(seconds: float | None) -> str:
|
|||||||
return f"{hours}H {minutes}M" if hours else f"{minutes}M"
|
return f"{hours}H {minutes}M" if hours else f"{minutes}M"
|
||||||
|
|
||||||
|
|
||||||
def _fit(d: ImageDraw.ImageDraw, text: str, font, max_w: float) -> str:
|
|
||||||
if d.textlength(text, font=font) <= max_w:
|
|
||||||
return text
|
|
||||||
while text and d.textlength(text + "…", font=font) > max_w:
|
|
||||||
text = text[:-1]
|
|
||||||
return text + "…"
|
|
||||||
|
|
||||||
|
|
||||||
class ServerView:
|
class ServerView:
|
||||||
name = "server"
|
name = "server"
|
||||||
STALE_AFTER = 30.0 # seconds without a successful read before the numbers are marked old
|
STALE_AFTER = 10.0 # seconds without a successful read before the numbers are marked old
|
||||||
|
|
||||||
def __init__(self, poller: Poller[Stats]) -> None:
|
def __init__(self, poller: Poller[Stats]) -> None:
|
||||||
self._poller = poller
|
self._poller = poller
|
||||||
@@ -53,87 +44,106 @@ class ServerView:
|
|||||||
return age is not None and age > self.STALE_AFTER
|
return age is not None and age > self.STALE_AFTER
|
||||||
|
|
||||||
def frame_key(self, now: datetime):
|
def frame_key(self, now: datetime):
|
||||||
return (now.second // 5, self._poller.version, self._is_stale())
|
return (self._poller.version, self._is_stale())
|
||||||
|
|
||||||
def patch(self, now: datetime) -> Patch | None:
|
def patch(self, now: datetime) -> Patch | None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def render(self, now: datetime) -> Image.Image:
|
def render(self, now: datetime) -> Image.Image:
|
||||||
stats: Stats | None = self._poller.value
|
stats: Stats | None = self._poller.value
|
||||||
img = Image.new("RGB", (W, H), BG)
|
img = cyber.background()
|
||||||
d = ImageDraw.Draw(img)
|
d = ImageDraw.Draw(img)
|
||||||
f_small, f_tiny, f_row = lcdkit.load_font(15), lcdkit.load_font(12), lcdkit.load_font(14)
|
cyber.chamfer(d, (5, 5, W - 6, H - 6), 16, outline=YELLOW, width=2, cuts="tl br")
|
||||||
|
d.line((W - 26, 10, W - 10, 10), fill=CYAN, width=2) # corner brackets
|
||||||
|
d.line((W - 10, 10, W - 10, 26), fill=CYAN, width=2)
|
||||||
|
d.line((10, H - 26, 10, H - 10), fill=CYAN, width=2)
|
||||||
|
d.line((10, H - 10, 26, H - 10), fill=CYAN, width=2)
|
||||||
|
|
||||||
d.rectangle((6, 6, W - 7, H - 7), outline=INK, width=2)
|
self._header(d, stats)
|
||||||
self._header(d, stats, f_small, f_tiny)
|
self._gauges(d, stats)
|
||||||
d.line((12, 46, W - 13, 46), fill=INK, width=2)
|
self._load_and_temp(d, stats)
|
||||||
self._bars(d, stats, f_small)
|
d.line((22, 176, 318, 176), fill=YELLOW, width=1)
|
||||||
self._load_and_temp(d, stats, f_small, f_tiny)
|
self._docker(d, stats)
|
||||||
d.line((12, 160, W - 13, 160), fill=INK, width=2)
|
d.line((324, 190, 324, H - 22), fill=YELLOW, width=1)
|
||||||
self._docker(d, stats, f_tiny, f_row)
|
self._processes(d, stats)
|
||||||
d.line((306, 168, 306, H - 14), fill=INK, width=2)
|
|
||||||
self._processes(d, stats, f_tiny, f_row)
|
|
||||||
return img
|
return img
|
||||||
|
|
||||||
def _header(self, d, stats: Stats | None, f_small, f_tiny) -> None:
|
def _header(self, d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
lcdkit.tag(d, (14, 14), "SERVER", f_small)
|
box = cyber.tag(d, (22, 14), TITLE, cyber.font(22))
|
||||||
d.text((100, 16), f"UP {fmt_uptime(stats.uptime_s if stats else None)}", font=f_small, fill=INK)
|
d.text((box[2] + 16, 17), "UP", font=cyber.font(13, False), fill=GREY)
|
||||||
|
d.text((box[2] + 36, 14), fmt_uptime(stats.uptime_s if stats else None), font=cyber.font(22), fill=CYAN)
|
||||||
if self._is_stale():
|
if self._is_stale():
|
||||||
width = d.textbbox((0, 0), "STARÉ", font=f_tiny)[2] + 6
|
cyber.tag(d, (W - 22 - 70, 14), "STARÉ", cyber.font(16), colour=RED)
|
||||||
lcdkit.tag(d, (W - 14 - width, 17), "STARÉ", f_tiny)
|
else:
|
||||||
|
tick = int(stats.uptime_s) & 0xFFFF if stats and stats.uptime_s is not None else 0
|
||||||
|
d.text((W - 22 - 92, 18), f"0x{tick:04X}", font=cyber.font(13, False), fill=MAGENTA)
|
||||||
|
d.rectangle((W - 22 - 40, 21, W - 22 - 36, 25), fill=CYAN)
|
||||||
|
d.text((W - 22 - 30, 17), "ON", font=cyber.font(13), fill=CYAN)
|
||||||
|
d.line((22, 46, W - 22, 46), fill=YELLOW, width=1)
|
||||||
|
d.line((22, 48, box[2], 48), fill=YELLOW, width=1)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _bars(d, stats: Stats | None, f_small) -> None:
|
def _gauges(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
for label, field, y in BAR_ROWS:
|
big = cyber.font(36)
|
||||||
|
for label, field, y in GAUGES:
|
||||||
pct = getattr(stats, field) if stats else None
|
pct = getattr(stats, field) if stats else None
|
||||||
d.text((18, y + 3), label, font=f_small, fill=INK)
|
d.text((24, y), label, font=cyber.font(15), fill=CYAN)
|
||||||
lcdkit.h_bar(d, 72, y, pct, 24, 16, 8, 2)
|
cyber.slanted_bar(d, 24, y + 22, pct, 10, 21, 7, 3)
|
||||||
text = "--" if pct is None else str(round(pct))
|
text = "--" if pct is None else str(round(pct))
|
||||||
x = lcdkit.number(d, text, 244, y - 1, **DIGITS, ghost=False)
|
cyber.glitch_text(d, (246, y - 4), text, big)
|
||||||
if pct is not None:
|
if pct is not None:
|
||||||
d.text((x + 2, y + 6), "%", font=f_small, fill=INK)
|
d.text((246 + d.textlength(text, font=big) + 4, y + 8), "%", font=cyber.font(16), fill=CYAN)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _load_and_temp(d, stats: Stats | None, f_small, f_tiny) -> None:
|
def _load_and_temp(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
load = stats.load if stats else None
|
load = stats.load if stats else None
|
||||||
d.text((336, 50), "LOAD", font=f_tiny, fill=INK)
|
cyber.chamfer(d, (330, 56, W - 22, 108), 8, outline=CYAN, cuts="tr bl")
|
||||||
lcdkit.number(d, f"{load[0]:.2f}" if load else "--", 336, 64, **DIGITS, ghost=False)
|
d.text((340, 58), "LOAD AVG", font=cyber.font(13, False), fill=GREY)
|
||||||
d.text((336, 96), f"{load[1]:.2f} {load[2]:.2f}" if load else "-- --", font=f_tiny, fill=INK)
|
d.text((340, 68), f"{load[0]:.2f}" if load else "--", font=cyber.font(30), fill=YELLOW)
|
||||||
|
d.text((410, 78), f"{load[1]:.2f} {load[2]:.2f}" if load else "", font=cyber.font(13, False), fill=CYAN)
|
||||||
temp = stats.temp_c if stats else None
|
temp = stats.temp_c if stats else None
|
||||||
x = lcdkit.number(d, lcdkit.fmt_temp(temp), 336, 116, **DIGITS, ghost=False)
|
cyber.chamfer(d, (330, 114, W - 22, 166), 8, outline=CYAN, cuts="tr bl")
|
||||||
d.text((x + 2, 126), "°C" if temp is not None else "", font=f_small, fill=INK)
|
d.text((340, 116), "CORE TEMP", font=cyber.font(13, False), fill=GREY)
|
||||||
|
d.text((340, 126), f"{round(temp)}°C" if temp is not None else "--", font=cyber.font(30), fill=YELLOW)
|
||||||
|
cyber.hazard_stripe(d, 336, 170, 118)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _docker(d, stats: Stats | None, f_tiny, f_row) -> None:
|
def _docker(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
|
d.text((24, 180), "DOCKER", font=cyber.font(16), fill=YELLOW)
|
||||||
containers = stats.containers if stats else None
|
containers = stats.containers if stats else None
|
||||||
if containers is None:
|
if containers is None:
|
||||||
d.text((14, 166), "DOCKER", font=f_tiny, fill=INK)
|
d.text((24, 226), "NO DOCKER", font=cyber.font(26), fill=RED)
|
||||||
d.text((22, 230), "NO DOCKER", font=lcdkit.load_font(18), fill=INK)
|
d.text((24, 256), "SOCKET UNAVAILABLE", font=cyber.font(13, False), fill=GREY)
|
||||||
return
|
return
|
||||||
running = sum(1 for c in containers if c.state == "running")
|
running = sum(1 for c in containers if c.state == "running")
|
||||||
d.text((14, 166), f"DOCKER {running}/{len(containers)}", font=f_tiny, fill=INK)
|
d.text((86, 183), f"{running}/{len(containers)} ACTIVE", font=cyber.font(13, False), fill=CYAN)
|
||||||
ordered = sorted(containers, key=lambda c: (status_label(c) not in ATTENTION, c.name))
|
ordered = sorted(containers, key=lambda c: (status_label(c) not in ATTENTION, c.name))
|
||||||
shown = ordered if len(ordered) <= CONTAINER_ROWS else ordered[:CONTAINER_ROWS - 1]
|
y = 202
|
||||||
for i, c in enumerate(shown):
|
for c in ordered[:CONTAINER_ROWS]:
|
||||||
ServerView._container_row(d, c, ROWS_TOP + i * ROW_STEP, f_tiny, f_row)
|
ServerView._container_row(d, c, y)
|
||||||
if len(shown) < len(ordered):
|
y += 17
|
||||||
d.text((14, ROWS_TOP + len(shown) * ROW_STEP), f"+{len(ordered) - len(shown)}", font=f_row, fill=INK)
|
if len(ordered) > CONTAINER_ROWS:
|
||||||
|
d.text((24, y + 1), f"+{len(ordered) - CONTAINER_ROWS} MORE", font=cyber.font(13, False), fill=GREY)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _container_row(d, c: Container, y: int, f_tiny, f_row) -> None:
|
def _container_row(d: ImageDraw.ImageDraw, c: Container, y: int) -> None:
|
||||||
label = status_label(c)
|
label = status_label(c)
|
||||||
d.text((14, y), _fit(d, c.name, f_row, 170), font=f_row, fill=INK)
|
d.text((24, y), cyber.fit(d, c.name.upper(), cyber.font(15), 226), font=cyber.font(15), fill=TEXT)
|
||||||
if label in ATTENTION:
|
if label in ATTENTION:
|
||||||
width = d.textbbox((0, 0), label, font=f_tiny)[2] + 6
|
colour = MAGENTA if label == "RESTART" else RED
|
||||||
lcdkit.tag(d, (294 - width, y), label, f_tiny)
|
width = d.textlength(label, font=cyber.font(13))
|
||||||
|
cyber.chamfer(d, (int(314 - width - 14), y + 1, 314, y + 16), 4, fill=colour, cuts="tl br")
|
||||||
|
d.text((314 - width - 7, y - 1), label, font=cyber.font(13), fill=INK)
|
||||||
else:
|
else:
|
||||||
d.text((294 - d.textlength(label, font=f_tiny), y + 2), label, font=f_tiny, fill=INK)
|
d.text((312 - d.textlength(label, font=cyber.font(13)), y), label, font=cyber.font(13), fill=CYAN)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _processes(d, stats: Stats | None, f_tiny, f_row) -> None:
|
def _processes(d: ImageDraw.ImageDraw, stats: Stats | None) -> None:
|
||||||
d.text((318, 166), "PROCESY", font=f_tiny, fill=INK)
|
d.text((336, 180), "TOP PROCESSES", font=cyber.font(16), fill=YELLOW)
|
||||||
for i, proc in enumerate(stats.procs if stats else ()):
|
y = 204
|
||||||
y = ROWS_TOP + i * 22
|
for proc in stats.procs if stats else ():
|
||||||
|
d.text((336, y), cyber.fit(d, proc.name.upper(), cyber.font(15), 76), font=cyber.font(15), fill=CYAN)
|
||||||
pct = f"{proc.cpu_pct:.1f}%"
|
pct = f"{proc.cpu_pct:.1f}%"
|
||||||
d.text((W - 16 - d.textlength(pct, font=f_row), y), pct, font=f_row, fill=INK)
|
d.text((W - 24 - d.textlength(pct, font=cyber.font(15)), y), pct, font=cyber.font(15), fill=YELLOW)
|
||||||
d.text((318, y), _fit(d, proc.name, f_row, 80), font=f_row, fill=INK)
|
d.rectangle((336, y + 17, 336 + int(min(proc.cpu_pct, 10) * 11), y + 18), fill=MAGENTA)
|
||||||
|
y += 22
|
||||||
+39
-14
@@ -5,9 +5,11 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
|
import time
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -144,15 +146,25 @@ def list_containers(sock_path: str, timeout: float = 3.0) -> tuple[Container, ..
|
|||||||
# --- reader --------------------------------------------------------------------
|
# --- reader --------------------------------------------------------------------
|
||||||
|
|
||||||
class StatsReader:
|
class StatsReader:
|
||||||
|
"""Reads everything on each call, but asks Docker only every `docker_every` seconds and ranks processes
|
||||||
|
over windows of `proc_every` seconds (a 1 s window makes the ranking flicker)."""
|
||||||
|
|
||||||
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
def __init__(self, proc_root: str = "/host/proc", sys_root: str = "/host/sys", disk_path: str = "/host/root",
|
||||||
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0) -> None:
|
docker_sock: str = "/var/run/docker.sock", docker_timeout: float = 3.0,
|
||||||
|
docker_every: float = 5.0, proc_every: float = 3.0,
|
||||||
|
clock: Callable[[], float] = time.monotonic) -> None:
|
||||||
self._proc = Path(proc_root)
|
self._proc = Path(proc_root)
|
||||||
self._sys = Path(sys_root)
|
self._sys = Path(sys_root)
|
||||||
self._disk = disk_path
|
self._disk = disk_path
|
||||||
self._sock = docker_sock
|
self._sock = docker_sock
|
||||||
self._docker_timeout = docker_timeout
|
self._docker_timeout = docker_timeout
|
||||||
|
self._docker_every = docker_every
|
||||||
|
self._proc_every = proc_every
|
||||||
|
self._clock = clock
|
||||||
self._prev_cpu: tuple[int, int] | None = None
|
self._prev_cpu: tuple[int, int] | None = None
|
||||||
self._prev_ticks: dict[int, int] = {}
|
self._docker: tuple[float, tuple[Container, ...] | None] | None = None # (when asked, result)
|
||||||
|
self._snapshot: tuple[float, int, dict[int, int], dict[int, str]] | None = None # (when, jiffies, ticks, names)
|
||||||
|
self._procs: tuple[Proc, ...] = ()
|
||||||
self._failing: set[str] = set()
|
self._failing: set[str] = set()
|
||||||
|
|
||||||
def _try(self, section: str, fn, default=None):
|
def _try(self, section: str, fn, default=None):
|
||||||
@@ -170,12 +182,11 @@ class StatsReader:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def read(self) -> Stats:
|
def read(self) -> Stats:
|
||||||
total_delta = None
|
total = None
|
||||||
cpu = None
|
cpu = None
|
||||||
try:
|
try:
|
||||||
cur = parse_cpu_times((self._proc / "stat").read_text())
|
cur = parse_cpu_times((self._proc / "stat").read_text())
|
||||||
if self._prev_cpu is not None:
|
total = cur[1]
|
||||||
total_delta = cur[1] - self._prev_cpu[1]
|
|
||||||
cpu = cpu_pct(self._prev_cpu, cur)
|
cpu = cpu_pct(self._prev_cpu, cur)
|
||||||
self._prev_cpu = cur
|
self._prev_cpu = cur
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -192,10 +203,17 @@ class StatsReader:
|
|||||||
load=self._try("load", self._load),
|
load=self._try("load", self._load),
|
||||||
temp_c=self._try("temperature", self._temperature),
|
temp_c=self._try("temperature", self._temperature),
|
||||||
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
uptime_s=self._try("uptime", lambda: float((self._proc / "uptime").read_text().split()[0])),
|
||||||
containers=self._try("docker", lambda: list_containers(self._sock, self._docker_timeout)),
|
containers=self._containers(),
|
||||||
procs=self._try("processes", lambda: self._processes(total_delta), ()),
|
procs=self._try("processes", lambda: self._processes(total), self._procs),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _containers(self) -> tuple[Container, ...] | None:
|
||||||
|
now = self._clock()
|
||||||
|
if self._docker is None or now - self._docker[0] >= self._docker_every:
|
||||||
|
result = self._try("docker", lambda: list_containers(self._sock, self._docker_timeout))
|
||||||
|
self._docker = (now, result)
|
||||||
|
return self._docker[1]
|
||||||
|
|
||||||
def _disk_pct(self) -> float:
|
def _disk_pct(self) -> float:
|
||||||
st = os.statvfs(self._disk)
|
st = os.statvfs(self._disk)
|
||||||
used = st.f_blocks - st.f_bfree
|
used = st.f_blocks - st.f_bfree
|
||||||
@@ -218,7 +236,13 @@ class StatsReader:
|
|||||||
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
cpu_zones = [c for is_cpu, c in readings if is_cpu]
|
||||||
return max(cpu_zones or [c for _, c in readings])
|
return max(cpu_zones or [c for _, c in readings])
|
||||||
|
|
||||||
def _processes(self, total_delta: int | None) -> tuple[Proc, ...]:
|
def _processes(self, total: int | None) -> tuple[Proc, ...]:
|
||||||
|
"""Top processes by CPU over the last window; the previous ranking is kept between windows."""
|
||||||
|
now = self._clock()
|
||||||
|
if total is None:
|
||||||
|
return self._procs
|
||||||
|
if self._snapshot is not None and now - self._snapshot[0] < self._proc_every:
|
||||||
|
return self._procs
|
||||||
ticks: dict[int, int] = {}
|
ticks: dict[int, int] = {}
|
||||||
names: dict[int, str] = {}
|
names: dict[int, str] = {}
|
||||||
for entry in os.scandir(self._proc):
|
for entry in os.scandir(self._proc):
|
||||||
@@ -229,12 +253,13 @@ class StatsReader:
|
|||||||
except (OSError, ValueError, IndexError):
|
except (OSError, ValueError, IndexError):
|
||||||
continue # the process exited while we were reading
|
continue # the process exited while we were reading
|
||||||
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
ticks[int(entry.name)], names[int(entry.name)] = t, name
|
||||||
previous, self._prev_ticks = self._prev_ticks, ticks
|
previous, self._snapshot = self._snapshot, (now, total, ticks, names)
|
||||||
if not total_delta or total_delta <= 0 or not previous:
|
if previous is None or total - previous[1] <= 0:
|
||||||
return ()
|
return self._procs
|
||||||
per_name: dict[str, float] = defaultdict(float)
|
per_name: dict[str, float] = defaultdict(float)
|
||||||
for pid, t in ticks.items():
|
for pid, t in ticks.items():
|
||||||
if pid in previous and t > previous[pid]:
|
if pid in previous[2] and t > previous[2][pid]:
|
||||||
per_name[names[pid]] += (t - previous[pid]) / total_delta * 100
|
per_name[names[pid]] += (t - previous[2][pid]) / (total - previous[1]) * 100
|
||||||
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
ranked = sorted(per_name.items(), key=lambda kv: kv[1], reverse=True)[:TOP_PROCESSES]
|
||||||
return tuple(Proc(name, pct) for name, pct in ranked)
|
self._procs = tuple(Proc(name, pct) for name, pct in ranked)
|
||||||
|
return self._procs
|
||||||
@@ -7,3 +7,11 @@ def count_colour(img: Image.Image, colour, box=None) -> int:
|
|||||||
if box is not None:
|
if box is not None:
|
||||||
img = img.crop(box)
|
img = img.crop(box)
|
||||||
return int((np.asarray(img.convert("RGB")) == np.array(colour)).all(axis=2).sum())
|
return int((np.asarray(img.convert("RGB")) == np.array(colour)).all(axis=2).sum())
|
||||||
|
|
||||||
|
|
||||||
|
def count_near(img: Image.Image, colour, tolerance: int = 70, box=None) -> int:
|
||||||
|
"""Pixels within `tolerance` (per channel) of `colour`: for anti-aliased text, which is never exactly pure."""
|
||||||
|
if box is not None:
|
||||||
|
img = img.crop(box)
|
||||||
|
diff = np.abs(np.asarray(img.convert("RGB")).astype(int) - np.array(colour))
|
||||||
|
return int((diff.max(axis=2) <= tolerance).sum())
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
from PIL import Image, ImageDraw
|
||||||
|
|
||||||
|
import cyber
|
||||||
|
from cyber import BG, CYAN, DIM, RED, SCAN, YELLOW
|
||||||
|
from tests.helpers import count_colour, count_near
|
||||||
|
|
||||||
|
|
||||||
|
def canvas(w=200, h=100):
|
||||||
|
img = Image.new("RGB", (w, h), BG)
|
||||||
|
return img, ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
|
||||||
|
def test_background_has_scanlines_and_is_a_private_copy():
|
||||||
|
a = cyber.background()
|
||||||
|
assert a.size == (480, 320)
|
||||||
|
assert a.getpixel((5, 0)) == SCAN and a.getpixel((5, 1)) == BG
|
||||||
|
a.putpixel((5, 1), (1, 2, 3))
|
||||||
|
assert cyber.background().getpixel((5, 1)) == BG # the cached original is untouched
|
||||||
|
|
||||||
|
|
||||||
|
def test_chamfer_cuts_the_requested_corner_only():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.chamfer(d, (10, 10, 90, 50), 12, fill=YELLOW, cuts="tl")
|
||||||
|
assert img.getpixel((11, 11)) == BG # cut away
|
||||||
|
assert img.getpixel((88, 48)) == YELLOW # the bottom-right corner is square
|
||||||
|
assert img.getpixel((30, 30)) == YELLOW
|
||||||
|
|
||||||
|
|
||||||
|
def test_glitch_text_shows_all_three_colours():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.glitch_text(d, (20, 10), "88", cyber.font(48))
|
||||||
|
for colour in (YELLOW, CYAN, RED): # the fringes are anti-aliased, so compare with a tolerance
|
||||||
|
assert count_near(img, colour) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_lights_proportionally():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, 50, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, YELLOW) > 0 and count_colour(img, DIM) > 0
|
||||||
|
lit, unlit = count_colour(img, YELLOW), count_colour(img, DIM)
|
||||||
|
assert abs(lit - unlit) <= lit * 0.15 # 5 of 10 segments
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_turns_red_when_hot():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, 90, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, RED) > 0 and count_colour(img, YELLOW) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_slanted_bar_none_is_all_dim():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.slanted_bar(d, 10, 10, None, 10, 10, 8, 2)
|
||||||
|
assert count_colour(img, DIM) > 0
|
||||||
|
assert count_colour(img, YELLOW) == 0 and count_colour(img, RED) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_is_sized_from_its_text_and_returns_its_box():
|
||||||
|
img, d = canvas(300, 60)
|
||||||
|
f = cyber.font(22)
|
||||||
|
short = cyber.tag(d, (10, 10), "HI", f)
|
||||||
|
long_ = cyber.tag(d, (10, 10), "HOME // SERVER", f)
|
||||||
|
assert (long_[2] - long_[0]) > (short[2] - short[0])
|
||||||
|
assert (long_[2] - long_[0]) >= d.textlength("HOME // SERVER", font=f)
|
||||||
|
assert count_colour(img, YELLOW) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_colour_can_be_changed():
|
||||||
|
img, d = canvas()
|
||||||
|
cyber.tag(d, (10, 10), "STARÉ", cyber.font(14), colour=RED)
|
||||||
|
assert count_colour(img, RED) > 0 and count_colour(img, YELLOW) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_fit_shortens_long_text_with_an_ellipsis():
|
||||||
|
img, d = canvas()
|
||||||
|
f = cyber.font(15)
|
||||||
|
text = cyber.fit(d, "A-VERY-LONG-CONTAINER-NAME-INDEED", f, 80)
|
||||||
|
assert text.endswith("…") and d.textlength(text, font=f) <= 80
|
||||||
|
assert cyber.fit(d, "SHORT", f, 80) == "SHORT"
|
||||||
@@ -22,3 +22,9 @@ def test_make_view_unknown_lists_valid_names():
|
|||||||
def test_make_view_empty_name_is_unknown():
|
def test_make_view_empty_name_is_unknown():
|
||||||
with pytest.raises(UnknownView):
|
with pytest.raises(UnknownView):
|
||||||
make_view("")
|
make_view("")
|
||||||
|
|
||||||
|
|
||||||
|
def test_server_view_polls_every_second_and_weather_every_quarter_hour():
|
||||||
|
import registry
|
||||||
|
assert registry.SERVER_REFRESH_S == 1
|
||||||
|
assert registry.WEATHER_REFRESH_S == 15 * 60
|
||||||
+47
-12
@@ -2,10 +2,10 @@ from datetime import datetime
|
|||||||
|
|
||||||
from PIL import ImageChops
|
from PIL import ImageChops
|
||||||
|
|
||||||
from lcdkit import INK
|
from cyber import DIM, RED, TEXT
|
||||||
from server_view import ServerView
|
from server_view import ServerView
|
||||||
from stats_data import Container, Proc, Stats
|
from stats_data import Container, Proc, Stats
|
||||||
from tests.helpers import count_colour
|
from tests.helpers import count_colour, count_near
|
||||||
|
|
||||||
NOW = datetime(2026, 10, 22, 14, 32, 8)
|
NOW = datetime(2026, 10, 22, 14, 32, 8)
|
||||||
|
|
||||||
@@ -49,10 +49,13 @@ def test_render_size_is_480x320():
|
|||||||
assert view(stats()).render(NOW).size == (480, 320)
|
assert view(stats()).render(NOW).size == (480, 320)
|
||||||
|
|
||||||
|
|
||||||
def test_frame_key_changes_every_five_seconds():
|
def test_frame_key_follows_the_data_not_the_clock():
|
||||||
v = view(stats())
|
p = StubPoller(stats(), version=1)
|
||||||
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 5)) == v.frame_key(datetime(2026, 10, 22, 14, 32, 9))
|
v = ServerView(p)
|
||||||
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 9)) != v.frame_key(datetime(2026, 10, 22, 14, 32, 10))
|
before = v.frame_key(datetime(2026, 10, 22, 14, 32, 5))
|
||||||
|
assert before == v.frame_key(datetime(2026, 10, 22, 14, 32, 40)) # the clock does not matter
|
||||||
|
p.version = 2
|
||||||
|
assert v.frame_key(datetime(2026, 10, 22, 14, 32, 5)) != before # new data does
|
||||||
|
|
||||||
|
|
||||||
def test_frame_key_changes_on_new_data_and_stale_flip():
|
def test_frame_key_changes_on_new_data_and_stale_flip():
|
||||||
@@ -89,14 +92,21 @@ def test_stale_tag_only_when_old():
|
|||||||
old = view(stats(), age=ServerView.STALE_AFTER + 5).render(NOW)
|
old = view(stats(), age=ServerView.STALE_AFTER + 5).render(NOW)
|
||||||
bbox = region_diff(fresh, old)
|
bbox = region_diff(fresh, old)
|
||||||
assert bbox is not None
|
assert bbox is not None
|
||||||
assert bbox[0] >= 360 and bbox[1] >= 12 and bbox[3] <= 40
|
assert bbox[0] >= 360 and bbox[1] >= 12 and bbox[3] <= 44 # only the top-right status corner changes
|
||||||
|
|
||||||
|
|
||||||
def test_bar_reflects_value():
|
def test_gauge_reflects_value():
|
||||||
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
idle = view(stats(cpu_pct=0.0)).render(NOW)
|
||||||
busy = view(stats(cpu_pct=100.0)).render(NOW)
|
busy = view(stats(cpu_pct=60.0)).render(NOW)
|
||||||
box = (72, 54, 232, 78) # the CPU bar
|
box = (24, 76, 246, 86) # the CPU gauge
|
||||||
assert count_colour(busy, INK, box) > count_colour(idle, INK, box) + 500
|
assert count_colour(busy, DIM, box) < count_colour(idle, DIM, box) - 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_hot_gauge_turns_red():
|
||||||
|
box = (24, 76, 246, 86)
|
||||||
|
calm = view(stats(cpu_pct=20.0)).render(NOW)
|
||||||
|
hot = view(stats(cpu_pct=95.0)).render(NOW)
|
||||||
|
assert count_colour(hot, RED, box) > count_colour(calm, RED, box) + 500
|
||||||
|
|
||||||
|
|
||||||
def test_no_docker_differs_from_container_list():
|
def test_no_docker_differs_from_container_list():
|
||||||
@@ -104,7 +114,7 @@ def test_no_docker_differs_from_container_list():
|
|||||||
missing = view(stats(containers=None)).render(NOW)
|
missing = view(stats(containers=None)).render(NOW)
|
||||||
bbox = region_diff(listed, missing)
|
bbox = region_diff(listed, missing)
|
||||||
assert bbox is not None
|
assert bbox is not None
|
||||||
assert bbox[1] >= 160 and bbox[2] <= 304 # only the docker panel changes
|
assert bbox[1] >= 176 and bbox[2] <= 322 # only the docker panel changes
|
||||||
|
|
||||||
|
|
||||||
def test_attention_containers_sort_first():
|
def test_attention_containers_sort_first():
|
||||||
@@ -113,3 +123,28 @@ def test_attention_containers_sort_first():
|
|||||||
first_rows = view(stats(containers=fine + (sick,))).render(NOW)
|
first_rows = view(stats(containers=fine + (sick,))).render(NOW)
|
||||||
sorted_ok = view(stats(containers=(sick,) + fine)).render(NOW)
|
sorted_ok = view(stats(containers=(sick,) + fine)).render(NOW)
|
||||||
assert region_diff(first_rows, sorted_ok) is None # input order does not matter
|
assert region_diff(first_rows, sorted_ok) is None # input order does not matter
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_container_gets_a_red_chip():
|
||||||
|
ok = view(stats(containers=containers(3))).render(NOW)
|
||||||
|
broken = view(stats(containers=containers(2) + (Container("zzz", "exited", None),))).render(NOW)
|
||||||
|
panel = (24, 196, 322, 300)
|
||||||
|
assert count_colour(broken, RED, panel) > count_colour(ok, RED, panel) + 100
|
||||||
|
|
||||||
|
|
||||||
|
def test_long_container_name_stays_in_its_column():
|
||||||
|
long_name = Container("an-extraordinarily-long-container-name-that-would-run-into-the-process-list", "running", "healthy")
|
||||||
|
img = view(stats(containers=(long_name,) + containers(2))).render(NOW)
|
||||||
|
process_column = (326, 196, 470, 300)
|
||||||
|
assert count_near(img, TEXT, 20, process_column) == 0 # container names are the only near-white text
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_chip_is_wide_enough_for_its_label():
|
||||||
|
import numpy as np
|
||||||
|
from cyber import INK
|
||||||
|
img = view(stats(containers=(Container("web", "running", "unhealthy"),))).render(NOW)
|
||||||
|
panel = np.asarray(img.crop((24, 196, 322, 300)).convert("RGB"))
|
||||||
|
ys, xs = np.where((panel == np.array(RED)).all(axis=2))
|
||||||
|
ink_ys, ink_xs = np.where((panel == np.array(INK)).all(axis=2)) # the label is drawn in INK on the chip
|
||||||
|
assert len(xs) > 0 and len(ink_xs) > 0
|
||||||
|
assert ink_xs.min() > xs.min() and ink_xs.max() < xs.max() # the label sits inside the chip, not past its edges
|
||||||
@@ -80,12 +80,14 @@ class FakeDocker:
|
|||||||
|
|
||||||
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
|
def __init__(self, path: str, body: bytes = b"[]", hang: bool = False):
|
||||||
self.release = threading.Event()
|
self.release = threading.Event()
|
||||||
|
self.requests = 0
|
||||||
outer = self
|
outer = self
|
||||||
|
|
||||||
class Handler(socketserver.StreamRequestHandler):
|
class Handler(socketserver.StreamRequestHandler):
|
||||||
def handle(self):
|
def handle(self):
|
||||||
while self.rfile.readline() not in (b"\r\n", b""):
|
while self.rfile.readline() not in (b"\r\n", b""):
|
||||||
pass
|
pass
|
||||||
|
outer.requests += 1
|
||||||
if hang:
|
if hang:
|
||||||
outer.release.wait(5)
|
outer.release.wait(5)
|
||||||
return
|
return
|
||||||
@@ -111,6 +113,7 @@ def docker_in(tmp_path, monkeypatch):
|
|||||||
def make(body=b"[]", hang=False):
|
def make(body=b"[]", hang=False):
|
||||||
s = FakeDocker("d.sock", body, hang)
|
s = FakeDocker("d.sock", body, hang)
|
||||||
servers.append(s)
|
servers.append(s)
|
||||||
|
make.server = s
|
||||||
return "d.sock"
|
return "d.sock"
|
||||||
|
|
||||||
yield make
|
yield make
|
||||||
@@ -159,6 +162,8 @@ def thermal(sys_root: Path, zones: dict[str, tuple[str, int]]):
|
|||||||
|
|
||||||
|
|
||||||
def make_reader(tmp_path, docker_sock="missing.sock", **kw):
|
def make_reader(tmp_path, docker_sock="missing.sock", **kw):
|
||||||
|
kw.setdefault("docker_every", 0.0)
|
||||||
|
kw.setdefault("proc_every", 0.0)
|
||||||
proc, sys_root = tmp_path / "proc", tmp_path / "sys"
|
proc, sys_root = tmp_path / "proc", tmp_path / "sys"
|
||||||
thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)})
|
thermal(sys_root, {"thermal_zone0": ("acpitz", 30000), "thermal_zone1": ("x86_pkg_temp", 41000)})
|
||||||
write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0),
|
write_proc(proc, "cpu 100 0 50 800 50 0 0 0 0 0", {10: pid_line(10, "postgres", 0), 11: pid_line(11, "postgres", 0),
|
||||||
@@ -239,3 +244,49 @@ def test_reader_missing_proc_files_give_none_not_error(tmp_path):
|
|||||||
s = reader.read()
|
s = reader.read()
|
||||||
assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7
|
assert (s.cpu_pct, s.mem_pct, s.disk_pct, s.load, s.temp_c, s.uptime_s, s.containers) == (None,) * 7
|
||||||
assert s.procs == ()
|
assert s.procs == ()
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClock:
|
||||||
|
def __init__(self):
|
||||||
|
self.t = 0.0
|
||||||
|
|
||||||
|
def __call__(self):
|
||||||
|
return self.t
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_asks_docker_only_every_docker_every_seconds(tmp_path, docker_in):
|
||||||
|
sock = docker_in((FIXTURES / "docker_containers.json").read_bytes())
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=sock, docker_every=5.0, clock=clock)
|
||||||
|
first = reader.read()
|
||||||
|
clock.t = 1.0
|
||||||
|
second = reader.read()
|
||||||
|
assert docker_in.server.requests == 1
|
||||||
|
assert second.containers == first.containers and second.containers is not None
|
||||||
|
clock.t = 5.5
|
||||||
|
reader.read()
|
||||||
|
assert docker_in.server.requests == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_caches_a_docker_failure_for_the_interval_too(tmp_path):
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, _ = make_reader(tmp_path, docker_sock=str(tmp_path / "nope.sock"), docker_every=5.0, clock=clock)
|
||||||
|
assert reader.read().containers is None
|
||||||
|
clock.t = 1.0
|
||||||
|
assert reader.read().containers is None # no new attempt, still reported as unavailable
|
||||||
|
|
||||||
|
|
||||||
|
def test_reader_ranks_processes_over_a_longer_window(tmp_path):
|
||||||
|
clock = FakeClock()
|
||||||
|
reader, proc = make_reader(tmp_path, proc_every=3.0, clock=clock)
|
||||||
|
assert reader.read().procs == () # first snapshot
|
||||||
|
clock.t = 1.0
|
||||||
|
write_proc(proc, "cpu 600 0 300 2400 100 0 0 0 0 0", {10: pid_line(10, "postgres", 10)})
|
||||||
|
assert reader.read().procs == () # window not over yet: nothing new to rank
|
||||||
|
clock.t = 3.5
|
||||||
|
write_proc(proc, "cpu 900 0 450 3600 150 0 0 0 0 0", {10: pid_line(10, "postgres", 60)})
|
||||||
|
s = reader.read()
|
||||||
|
# 60 ticks over a jiffy window of 5100 - 1000 = 4100 -> 1.46 %
|
||||||
|
assert [(p.name, round(p.cpu_pct, 2)) for p in s.procs] == [("postgres", 1.46)]
|
||||||
|
clock.t = 4.0
|
||||||
|
assert reader.read().procs == s.procs # between windows the last ranking stays on screen
|
||||||
Reference in new issue
Block a user