Compare commits
58
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b5e1d3362 | ||
|
|
4224ac7252 | ||
|
|
1d4de00603 | ||
|
|
7047198146 | ||
|
|
815a55a9fd | ||
|
|
a3c8086d52 | ||
|
|
b91b4c427d | ||
|
|
316576f1da | ||
|
|
1fb7ca3d72 | ||
|
|
190d711a2a | ||
|
|
9275a9e295 | ||
|
|
d26eb1d9a6 | ||
|
|
6c73848ba1 | ||
|
|
94d0caa09c | ||
|
|
5f8869b165 | ||
|
|
91f69d1dd3 | ||
|
|
1ace62b969 | ||
|
|
8067e91409 | ||
|
|
bd22b53672 | ||
|
|
ac1a6fca38 | ||
|
|
fee36954e5 | ||
|
|
6315556152 | ||
|
|
791d0f62ce | ||
|
|
a831087a02 | ||
|
|
ba96c59c50 | ||
|
|
5443223842 | ||
|
|
3c832f3f06 | ||
|
|
7aaf784bb5 | ||
|
|
8b97cc9b41 | ||
|
|
ed695328e8 | ||
|
|
04b46f8bd1 | ||
|
|
f53fc0929b | ||
|
|
4a9f072692 | ||
|
|
afce6b03f4 | ||
|
|
4004dee825 | ||
|
|
2d613ae274 | ||
|
|
a8113da12e | ||
|
|
211f7466f6 | ||
|
|
493651776c | ||
|
|
1e4706f5ba | ||
|
|
1059f12ee0 | ||
|
|
b098b64b22 | ||
|
|
f2601e40de | ||
|
|
0dc13965e5 | ||
|
|
948e794e8b | ||
|
|
e8562b58ce | ||
|
|
1db3fdeb2f | ||
|
|
c790ee24d3 | ||
|
|
c5c47b92f4 | ||
|
|
4ef4983d0d | ||
|
|
1c799101fa | ||
|
|
19a79bef86 | ||
|
|
12ee8f41d9 | ||
|
|
a44a1fc51e | ||
|
|
e4abc6eb88 | ||
|
|
34829e39fe | ||
|
|
98eb3fe33c | ||
|
|
b2c170acda |
@@ -0,0 +1,103 @@
|
||||
# adwaita
|
||||
|
||||
The desktop's theme as a module (novox/hq ADR 0208, research 026, to-be 42 phase 2, step 6): Adwaita
|
||||
for GTK, Qt, the portal and the cursor, dark by default. It claims no seat, because themes coexist.
|
||||
|
||||
- **Packages:** `gnome-themes-extra` (Adwaita-dark for GTK 2 and 3), `adwaita-icon-theme`,
|
||||
`adwaita-cursors`, `qt6ct`, `xdg-desktop-portal-gtk`.
|
||||
- **Environment** (ADR 0203), the five words today's `~/.xinitrc` exported plus the cursor:
|
||||
- `GTK_THEME=Adwaita:dark`;
|
||||
- `GTK2_RC_FILES=/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc`;
|
||||
- `QT_QPA_PLATFORMTHEME=qt6ct`;
|
||||
- `QT_STYLE_OVERRIDE=Fusion`;
|
||||
- `QT_SELECT=6`;
|
||||
- `XCURSOR_THEME=Adwaita`, `XCURSOR_SIZE=24`.
|
||||
- **Session code** (ADR 0208 §4):
|
||||
- in the `xinitrc` slot `normal`, the GSettings keys the portal serves (dark, the GTK and icon theme,
|
||||
the cursor, the UI and monospace fonts), set at every session start. This replaces the
|
||||
predecessor's `~/scripts/xdg-appearance`;
|
||||
- in the `xresources` slot `normal`, `Xcursor.theme` and `Xcursor.size`.
|
||||
|
||||
## What it owns
|
||||
|
||||
| path | class | from |
|
||||
|---|---|---|
|
||||
| `~/.config/gtk-3.0/settings.ini` | owned (the found file kept once) | [`config/gtk-settings.ini`](config/gtk-settings.ini) |
|
||||
| `~/.config/gtk-4.0/settings.ini` | owned | the same file |
|
||||
| `~/.config/qt6ct/qt6ct.conf` | owned | [`config/qt6ct.conf`](config/qt6ct.conf) |
|
||||
| `~/.config/xdg-desktop-portal/portals.conf` | owned | [`config/portals.conf`](config/portals.conf) |
|
||||
| `~/.icons/default/index.theme` | owned | [`config/cursor-index.theme`](config/cursor-index.theme): the cursor for programs that read neither `XCURSOR_THEME` nor the resources |
|
||||
|
||||
**`qt6ct.conf` is the mesh's now.** A change made in qt6ct's own window is replaced at the next push,
|
||||
and the window's saved geometry goes with it. The theme is this module's to say. Settings will make it
|
||||
the operator's (issue 168).
|
||||
|
||||
## What it improves
|
||||
|
||||
- **No package from the user repository.** Today's Qt style, `adwaita-dark` (`QT_STYLE_OVERRIDE` and
|
||||
qt6ct's `Adwaita-Dark`), comes from the user repository's `adwaita-qt5`/`adwaita-qt6-git`, a
|
||||
project that is no longer developed. The module uses Qt's own **Fusion** style with qt6ct's
|
||||
**`darker`** palette, both shipped with Qt and qt6ct. **This is the one visible change:** Qt
|
||||
programs keep a dark palette, drawn by Fusion instead of Adwaita-Qt.
|
||||
- **One Qt tool.** `qt5ct` is gone (installed on the desktop only, with a configuration on both).
|
||||
`QT_SELECT=6` and `qt6ct` cover the Qt 6 programs. A Qt 5 program gets Fusion through
|
||||
`QT_STYLE_OVERRIDE`, but not the palette.
|
||||
- **The fonts research 026/04 chose:** Inter 11 for GTK, Qt and GSettings' interface font, and
|
||||
JetBrains Mono Nerd Font for Qt's fixed font and GSettings' monospace. Today these are Noto Sans 12,
|
||||
Adwaita Sans 11 and nothing.
|
||||
- **The cursor said everywhere**: GTK's settings, GSettings, `XCURSOR_*`, the X resources and the
|
||||
default theme. Today only the resources and GSettings said it.
|
||||
- **The portal answers secrets.** `portals.conf` routes `org.freedesktop.impl.portal.Secret` to
|
||||
gnome-keyring. Today `adwaita_portal_check` shows no backend answering it: gtk does not implement
|
||||
it, and gnome-keyring's backend names only GNOME.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | | what |
|
||||
|---|---|---|
|
||||
| `adwaita_appearance` | r/a | dark or light as each audience sees it (GSettings, the portal's own answer, the GTK files, Qt's style and palette, the theme words in the user manager). `mode` switches GSettings for the session, and the answer says what follows live (programs asking the portal) and what stays dark (GTK 3 under `GTK_THEME`, the declared files) |
|
||||
| `adwaita_cursor` | r/a | the cursor in GSettings, the resources and the environment, and the cursor themes installed; set theme or size for new windows (GSettings, and the resources when a session runs) |
|
||||
| `adwaita_icons` | r | icon themes installed (where, what each inherits, whether it has cursors), and the one GSettings, GTK and Qt use |
|
||||
| `adwaita_portal_check` | r | the backends installed and what each implements, which `portals.conf` decides (the first that exists, in xdg-desktop-portal's order), the backend answering each interface, what runs on the bus, and the colour scheme the portal answers |
|
||||
|
||||
Each reaches GSettings, the portal and the user manager on the account's bus. Only the cursor's X
|
||||
resources need the session. From the user manager it reads only the theme's own words.
|
||||
|
||||
**The appearance is a session's choice.** A persistent dark or light, for the files too, is a setting
|
||||
and waits for issue 168. Until then the module's default is dark, and `mode` lasts until the next
|
||||
login.
|
||||
|
||||
## What it leaves found
|
||||
|
||||
`~/.config/qt5ct/`, `~/.config/gtk-3.0/bookmarks` and everything else in those directories,
|
||||
`~/scripts/xdg-appearance`, and the user repository's `adwaita-qt*` packages.
|
||||
|
||||
## The one-off migration (ADR 0182)
|
||||
|
||||
**Once `adwaita` is assigned:**
|
||||
|
||||
1. In `~/.xinitrc`, the theme exports and `~/scripts/xdg-appearance || true` go (see `xorg`'s list).
|
||||
2. Delete `~/scripts/xdg-appearance`.
|
||||
3. In `~/.Xresources`, delete the two `Xcursor` lines.
|
||||
4. Delete `~/.config/qt5ct/`.
|
||||
5. Remove the user repository's packages: `sudo pacman -Rns adwaita-qt5-git adwaita-qt6-git`
|
||||
(laptop), `sudo pacman -Rns adwaita-qt5 adwaita-qt6-git adwaita-dark qt5ct` (desktop). Check first
|
||||
that nothing else needs them (`pacman -Qi`).
|
||||
|
||||
## What changes when it is assigned
|
||||
|
||||
| | g14 | shanks |
|
||||
|---|---|---|
|
||||
| packages | none (all present) | the same |
|
||||
| GTK settings, `portals.conf` | the found files kept once, then the module's: adds the cursor and Inter, keeps Adwaita dark; `portals.conf` adds the Secret line | the same |
|
||||
| `qt6ct.conf` | Fusion with the `darker` palette, Inter and JetBrains Mono, instead of Adwaita-Dark with Noto Sans | the same |
|
||||
| `~/.icons/default/index.theme` | new | new |
|
||||
| environment | `QT_STYLE_OVERRIDE` becomes `Fusion`; `XCURSOR_*` added; the rest as `~/.xinitrc` exported them | the same |
|
||||
| running programs | **nothing**: settings are read at a program's start, and GSettings is set at the next login | the same |
|
||||
| next login | GSettings' fonts become Inter and JetBrains Mono. A secret request through the portal finds gnome-keyring | the same |
|
||||
|
||||
## Blockers
|
||||
|
||||
- **`fonts` first**, for Inter and JetBrains Mono. Without them, GTK and Qt fall back to the nearest
|
||||
installed face.
|
||||
- **Light is a session's choice only**, until settings (issue 168).
|
||||
@@ -0,0 +1,246 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adwaita/internal/desktop"
|
||||
)
|
||||
|
||||
type manifest struct {
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Claims []any `json:"claims"`
|
||||
Tools []string `json:"tools"`
|
||||
Environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
} `json:"environment"`
|
||||
Shell []struct {
|
||||
For, Slot, Code string
|
||||
} `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestItContributesTheThemesWordsAndClaimsNoSeat(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Claims != nil {
|
||||
t.Fatal("a theme is not a seat: several coexist")
|
||||
}
|
||||
want := map[string]string{"GTK_THEME": "Adwaita:dark", "GTK2_RC_FILES": "/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc",
|
||||
"QT_QPA_PLATFORMTHEME": "qt6ct", "QT_STYLE_OVERRIDE": "Fusion", "QT_SELECT": "6", "XCURSOR_THEME": "Adwaita", "XCURSOR_SIZE": "24"}
|
||||
if len(m.Environment.Variables) != len(want) {
|
||||
t.Fatalf("%v", m.Environment.Variables)
|
||||
}
|
||||
for k, v := range want {
|
||||
if m.Environment.Variables[k] != v {
|
||||
t.Errorf("%s=%q", k, m.Environment.Variables[k])
|
||||
}
|
||||
}
|
||||
served := map[string]bool{}
|
||||
for _, tool := range tools(adwaita{}) {
|
||||
served[tool.Name] = true
|
||||
}
|
||||
if len(served) != len(m.Tools) {
|
||||
t.Fatalf("%v %v", served, m.Tools)
|
||||
}
|
||||
for _, n := range m.Tools {
|
||||
if !served[n] {
|
||||
t.Errorf("%s", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSessionLinesSetGSettingsAndTheResourcesTheCursor(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if len(m.Shell) != 2 || m.Shell[0].For != "xresources" || m.Shell[1].For != "xinitrc" || m.Shell[0].Slot != "normal" || m.Shell[1].Slot != "normal" {
|
||||
t.Fatalf("%+v", m.Shell)
|
||||
}
|
||||
if m.Shell[0].Code != "! adwaita: the cursor, for X programs that take it from the resources.\nXcursor.theme: Adwaita\nXcursor.size: 24\n" {
|
||||
t.Fatalf("%q", m.Shell[0].Code)
|
||||
}
|
||||
x := m.Shell[1].Code
|
||||
for _, want := range []string{"color-scheme 'prefer-dark'", "gtk-theme 'Adwaita'", "icon-theme 'Adwaita'", "cursor-theme 'Adwaita'", "font-name 'Inter 11'", "monospace-font-name 'JetBrainsMono Nerd Font 11'"} {
|
||||
if !strings.Contains(x, want) {
|
||||
t.Errorf("lacks %s", want)
|
||||
}
|
||||
}
|
||||
for _, l := range strings.Split(strings.TrimSpace(x), "\n") {
|
||||
if !strings.HasPrefix(l, "#") && !strings.HasSuffix(l, "|| true") {
|
||||
t.Errorf("a session line that can stop the session's start: %q", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestItOwnsTheFilesItsSourcesHoldAndNoQt5Duplicate(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
sources := map[string]string{"gtk3": "gtk-settings.ini", "gtk4": "gtk-settings.ini", "qt6ct": "qt6ct.conf", "portals": "portals.conf", "cursor": "cursor-index.theme"}
|
||||
pkgs := []string{}
|
||||
for _, r := range m.Resources {
|
||||
id := r["id"].(string)
|
||||
if r["type"] == "package" {
|
||||
pkgs = append(pkgs, r["package"].(string))
|
||||
continue
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join("..", "..", "config", sources[id]))
|
||||
if r["content"] != string(raw) || r["into"] != nil || r["owner"] != "${machine:account}" {
|
||||
t.Errorf("%s is not config/%s, whole and the account's", id, sources[id])
|
||||
}
|
||||
if strings.Contains(r["path"].(string), "qt5ct") {
|
||||
t.Error("qt5ct: both workstations run Qt 6 programs through qt6ct; a second tool is a duplicate")
|
||||
}
|
||||
}
|
||||
if strings.Join(pkgs, ",") != "gnome-themes-extra,adwaita-icon-theme,adwaita-cursors,qt6ct,xdg-desktop-portal-gtk" {
|
||||
t.Fatalf("%v", pkgs)
|
||||
}
|
||||
qt := readINI(filepath.Join("..", "..", "config", "qt6ct.conf"))
|
||||
if qt["Appearance"]["style"] != "Fusion" || qt["Appearance"]["custom_palette"] != "true" || !strings.Contains(qt["Fonts"]["general"], "Inter,11") {
|
||||
t.Fatalf("%v", qt)
|
||||
}
|
||||
if _, err := os.Stat("/usr/share/qt6ct/colors"); err == nil {
|
||||
if _, err := os.Stat(qt["Appearance"]["color_scheme_path"]); err != nil {
|
||||
t.Fatalf("qt6ct ships no %s", qt["Appearance"]["color_scheme_path"])
|
||||
}
|
||||
}
|
||||
gtk := readINI(filepath.Join("..", "..", "config", "gtk-settings.ini"))["Settings"]
|
||||
if gtk["gtk-theme-name"] != "Adwaita" || gtk["gtk-application-prefer-dark-theme"] != "1" || gtk["gtk-font-name"] != "Inter 11" {
|
||||
t.Fatalf("%v", gtk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyFilesAreReadWithTheirComments(t *testing.T) {
|
||||
ini := ParseINI("# c\n[A]\nk = v\n; also a comment\n[B]\nx=1=2\n")
|
||||
if ini["A"]["k"] != "v" || ini["B"]["x"] != "1=2" || len(ini) != 2 {
|
||||
t.Fatalf("%v", ini)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThePortalsAnswerIsResolvedAsXdgDesktopPortalDoes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.WriteFile(filepath.Join(dir, "gtk.portal"), []byte("[portal]\nDBusName=org.freedesktop.impl.portal.desktop.gtk\nInterfaces=org.freedesktop.impl.portal.FileChooser;org.freedesktop.impl.portal.Settings;\nUseIn=gnome\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "gnome-keyring.portal"), []byte("[portal]\nDBusName=org.freedesktop.secrets\nInterfaces=org.freedesktop.impl.portal.Secret;\nUseIn=gnome\n"), 0o644)
|
||||
os.WriteFile(filepath.Join(dir, "kde.portal"), []byte("[portal]\nDBusName=org.freedesktop.impl.portal.desktop.kde\nInterfaces=org.freedesktop.impl.portal.FileChooser;\nUseIn=KDE\n"), 0o644)
|
||||
b := Backends([]string{dir})
|
||||
if len(b) != 3 || b[0].Name != "gnome-keyring" || len(b[1].Interfaces) != 2 {
|
||||
t.Fatalf("%+v", b)
|
||||
}
|
||||
got := Resolve(b, map[string]string{"default": "gtk", "org.freedesktop.impl.portal.Secret": "gnome-keyring"}, []string{"i3"})
|
||||
if got["org.freedesktop.impl.portal.FileChooser"] != "gtk" || got["org.freedesktop.impl.portal.Secret"] != "gnome-keyring" || got["org.freedesktop.impl.portal.Settings"] != "gtk" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
got = Resolve(b, map[string]string{"default": "gtk"}, []string{"i3"})
|
||||
if got["org.freedesktop.impl.portal.Secret"] != "(none)" {
|
||||
t.Fatalf("gtk does not implement secrets: %v", got)
|
||||
}
|
||||
got = Resolve(b, map[string]string{"default": "none;gtk"}, nil)
|
||||
if got["org.freedesktop.impl.portal.FileChooser"] != "(none)" {
|
||||
t.Fatalf("none stops the list: %v", got)
|
||||
}
|
||||
got = Resolve(b, nil, []string{"KDE"})
|
||||
if got["org.freedesktop.impl.portal.FileChooser"] != "kde" || got["org.freedesktop.impl.portal.Settings"] != "(none)" {
|
||||
t.Fatalf("with no configuration, UseIn decides: %v", got)
|
||||
}
|
||||
c := PortalConfigs("/h", []string{"i3", "GNOME"})
|
||||
if c[0] != "/h/.config/xdg-desktop-portal/i3-portals.conf" || c[1] != "/h/.config/xdg-desktop-portal/gnome-portals.conf" || c[2] != "/h/.config/xdg-desktop-portal/portals.conf" {
|
||||
t.Fatalf("%v", c[:3])
|
||||
}
|
||||
}
|
||||
|
||||
func TestThemesAreFoundOnceEachWithCursorsAndIcons(t *testing.T) {
|
||||
a, b := t.TempDir(), t.TempDir()
|
||||
os.MkdirAll(filepath.Join(a, "Adwaita", "cursors"), 0o755)
|
||||
os.MkdirAll(filepath.Join(b, "Adwaita"), 0o755)
|
||||
os.WriteFile(filepath.Join(b, "Adwaita", "index.theme"), []byte("[Icon Theme]\nName=Adwaita\nInherits=hicolor\nDirectories=16x16\n"), 0o644)
|
||||
os.MkdirAll(filepath.Join(b, "hicolor"), 0o755)
|
||||
os.WriteFile(filepath.Join(b, "hicolor", "index.theme"), []byte("[Icon Theme]\nName=Hicolor\nDirectories=16x16\n"), 0o644)
|
||||
os.MkdirAll(filepath.Join(b, "empty"), 0o755)
|
||||
got := Themes([]string{a, b})
|
||||
if len(got) != 2 || got[0].Name != "Adwaita" || !got[0].Cursors || got[0].Icons || got[0].Dir != filepath.Join(a, "Adwaita") || got[1].Name != "hicolor" {
|
||||
t.Fatalf("the first directory's Adwaita hides the second's: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
type fake struct {
|
||||
ran []string
|
||||
get map[string]string
|
||||
}
|
||||
|
||||
func (f *fake) desk() desktop.Desk {
|
||||
return desktop.Desk{
|
||||
Find: func() (*desktop.Session, error) { return nil, &desktop.NoSession{Reason: "none"} },
|
||||
Run: func(_ context.Context, env []string, _ []byte, name string, args ...string) desktop.Result {
|
||||
line := strings.Join(append([]string{name}, args...), " ")
|
||||
f.ran = append(f.ran, line)
|
||||
switch {
|
||||
case name == "gsettings" && args[0] == "get":
|
||||
return desktop.Result{Stdout: "'" + f.get[args[2]] + "'\n"}
|
||||
case name == "gsettings" && args[0] == "set":
|
||||
f.get[args[2]] = args[3]
|
||||
case name == "systemctl":
|
||||
return desktop.Result{Stdout: "GTK_THEME=Adwaita:dark\nNPM_TOKEN=secret\nXDG_CURRENT_DESKTOP=i3\n"}
|
||||
case name == "busctl" && args[1] == "call":
|
||||
return desktop.Result{Stdout: "v u 1\n"}
|
||||
}
|
||||
return desktop.Result{}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppearanceSwitchesGSettingsAndSaysWhatFollowsAndWhatStays(t *testing.T) {
|
||||
f := &fake{get: map[string]string{"color-scheme": "prefer-dark", "gtk-theme": "Adwaita"}}
|
||||
a := adwaita{d: f.desk(), home: t.TempDir()}
|
||||
got, err := a.appearance(context.Background(), desktop.Args{"mode": "light"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j := asJSON(got)
|
||||
if f.get["color-scheme"] != "prefer-light" || !strings.Contains(j, `"switched":"light"`) || !strings.Contains(j, "GTK_THEME=Adwaita:dark") || !strings.Contains(j, `"lasts"`) {
|
||||
t.Fatalf("%s", j)
|
||||
}
|
||||
if strings.Contains(j, "secret") || strings.Contains(j, "NPM_TOKEN") {
|
||||
t.Fatal("only the theme's words are read back from the user manager")
|
||||
}
|
||||
if _, err := a.appearance(context.Background(), desktop.Args{"mode": "blue"}); err == nil {
|
||||
t.Fatal("mode is dark or light")
|
||||
}
|
||||
got, _ = a.appearance(context.Background(), desktop.Args{})
|
||||
if strings.Contains(asJSON(got), "switched") {
|
||||
t.Fatal("reading changes nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestACursorThemeMustBeInstalledAndWithoutASessionOnlyGSettingsChanges(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.MkdirAll(filepath.Join(dir, "Adwaita", "cursors"), 0o755)
|
||||
f := &fake{get: map[string]string{}}
|
||||
a := adwaita{d: f.desk(), home: t.TempDir(), iconDirs: []string{dir}}
|
||||
if _, err := a.cursor(context.Background(), desktop.Args{"theme": "Bibata"}); err == nil {
|
||||
t.Fatal("a theme that is not installed")
|
||||
}
|
||||
got, err := a.cursor(context.Background(), desktop.Args{"theme": "Adwaita", "size": float64(32)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.get["cursor-theme"] != "Adwaita" || f.get["cursor-size"] != "32" || !strings.Contains(asJSON(got), "no graphical session") {
|
||||
t.Fatalf("%v %s", f.get, asJSON(got))
|
||||
}
|
||||
}
|
||||
|
||||
func asJSON(v any) string {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// adwaita's tools (novox/hq ADR 0208, research 026/05): appearance (dark or light for GTK, Qt and the
|
||||
// portal at once), cursor, icons and portal-check. The predecessor's appearance script is folded into
|
||||
// the first, and into the module's session line.
|
||||
//
|
||||
// None needs the display except setting the cursor's X resources: GSettings, the portal and the user
|
||||
// manager are reached on the account's own bus, which exists whenever the operator's user manager
|
||||
// runs.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"adwaita/internal/desktop"
|
||||
)
|
||||
|
||||
func main() {
|
||||
home := desktop.Home()
|
||||
a := adwaita{
|
||||
d: desktop.Machine("i3", "sway"), home: home,
|
||||
iconDirs: []string{filepath.Join(home, ".local", "share", "icons"), filepath.Join(home, ".icons"), "/usr/local/share/icons", "/usr/share/icons"},
|
||||
portalDirs: []string{"/usr/share/xdg-desktop-portal/portals"},
|
||||
uid: os.Getuid(),
|
||||
}
|
||||
if err := stdio.Serve("", tools(a)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func call(run func(ctx context.Context, a desktop.Args) (any, error)) func(map[string]any) (any, error) {
|
||||
return func(args map[string]any) (any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
||||
defer cancel()
|
||||
return run(ctx, desktop.Args(args))
|
||||
}
|
||||
}
|
||||
|
||||
func tools(a adwaita) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{
|
||||
Name: "adwaita_appearance",
|
||||
Description: "Dark or light, as each audience sees it now: GSettings (which the portal serves to " +
|
||||
"Electron, Firefox and flatpaks), the portal's own answer, the GTK settings files, Qt's palette " +
|
||||
"and the theme words in the user manager's environment. With mode, switch GSettings for the " +
|
||||
"running session and answer which audiences follow live and which keep the module's dark " +
|
||||
"default until it is a setting.",
|
||||
Input: desktop.Schema(map[string]any{"mode": desktop.Enum("switch to (optional)", "dark", "light")}),
|
||||
Run: call(a.appearance),
|
||||
},
|
||||
{
|
||||
Name: "adwaita_cursor",
|
||||
Description: "The cursor theme and size in force (GSettings, the X resources, XCURSOR_* in the user " +
|
||||
"manager) and the cursor themes installed. With theme and/or size, set them for windows opened " +
|
||||
"from now on; the module's defaults return at the next login.",
|
||||
Input: desktop.Schema(map[string]any{
|
||||
"theme": desktop.Str("an installed cursor theme"),
|
||||
"size": desktop.Int("pixels, 8 to 256"),
|
||||
}),
|
||||
Run: call(a.cursor),
|
||||
},
|
||||
{
|
||||
Name: "adwaita_icons",
|
||||
Description: "The icon themes installed (name, where, what each inherits, whether it carries cursors) " +
|
||||
"and the one GTK and Qt are set to use.",
|
||||
Input: desktop.Schema(map[string]any{}),
|
||||
Run: call(a.icons),
|
||||
},
|
||||
{
|
||||
Name: "adwaita_portal_check",
|
||||
Description: "Which xdg-desktop-portal backend answers which interface for this desktop: the backends " +
|
||||
"installed and what they implement, the portals.conf that decides (and which one won), the " +
|
||||
"resulting backend per interface, whether the portal and each backend are running on the " +
|
||||
"account's bus, and the colour scheme the portal answers.",
|
||||
Input: desktop.Schema(map[string]any{}),
|
||||
Run: call(a.portalCheck),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"adwaita/internal/desktop"
|
||||
)
|
||||
|
||||
type adwaita struct {
|
||||
d desktop.Desk
|
||||
home string
|
||||
iconDirs []string
|
||||
portalDirs []string
|
||||
uid int
|
||||
}
|
||||
|
||||
const iface = "org.gnome.desktop.interface"
|
||||
|
||||
// ParseINI reads a key file (GTK's settings.ini, qt6ct.conf, a .portal, index.theme): sections of
|
||||
// key=value, `#` and `;` comments.
|
||||
func ParseINI(text string) map[string]map[string]string {
|
||||
out := map[string]map[string]string{}
|
||||
section := ""
|
||||
sc := bufio.NewScanner(strings.NewReader(text))
|
||||
for sc.Scan() {
|
||||
l := strings.TrimSpace(sc.Text())
|
||||
if l == "" || strings.HasPrefix(l, "#") || strings.HasPrefix(l, ";") {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(l, "[") && strings.HasSuffix(l, "]") {
|
||||
section = l[1 : len(l)-1]
|
||||
continue
|
||||
}
|
||||
if k, v, ok := strings.Cut(l, "="); ok {
|
||||
if out[section] == nil {
|
||||
out[section] = map[string]string{}
|
||||
}
|
||||
out[section][strings.TrimSpace(k)] = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func readINI(path string) map[string]map[string]string {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return ParseINI(string(b))
|
||||
}
|
||||
|
||||
// gsetting is one GSettings value, unquoted.
|
||||
func (a adwaita) gsetting(ctx context.Context, schema, key string) (string, error) {
|
||||
r := a.d.AsUser(ctx, "gsettings", "get", schema, key)
|
||||
if !r.OK() {
|
||||
return "", r.Err()
|
||||
}
|
||||
return strings.Trim(strings.TrimSpace(r.Stdout), "'"), nil
|
||||
}
|
||||
|
||||
// themeWords are the words of the user manager's environment the theme is about; nothing else of it
|
||||
// is read back.
|
||||
var themeWords = []string{"GTK_THEME", "GTK2_RC_FILES", "QT_QPA_PLATFORMTHEME", "QT_STYLE_OVERRIDE", "QT_SELECT",
|
||||
"XCURSOR_THEME", "XCURSOR_SIZE", "XDG_CURRENT_DESKTOP"}
|
||||
|
||||
func (a adwaita) userEnvironment(ctx context.Context) map[string]string {
|
||||
r := a.d.AsUser(ctx, "systemctl", "--user", "show-environment")
|
||||
all := desktop.ParseProperties(r.Stdout)
|
||||
out := map[string]string{}
|
||||
for _, w := range themeWords {
|
||||
if v, ok := all[w]; ok {
|
||||
out[w] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var portalScheme = regexp.MustCompile(`^v u (\d)`)
|
||||
|
||||
// portalColourScheme asks the portal what it tells applications: 0 no preference, 1 dark, 2 light.
|
||||
func (a adwaita) portalColourScheme(ctx context.Context) string {
|
||||
r := a.d.AsUser(ctx, "busctl", "--user", "call", "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop",
|
||||
"org.freedesktop.portal.Settings", "ReadOne", "ss", "org.freedesktop.appearance", "color-scheme")
|
||||
m := portalScheme.FindStringSubmatch(strings.TrimSpace(r.Stdout))
|
||||
if !r.OK() || m == nil {
|
||||
return "unanswered"
|
||||
}
|
||||
return map[string]string{"0": "no-preference", "1": "dark", "2": "light"}[m[1]]
|
||||
}
|
||||
|
||||
func (a adwaita) appearance(ctx context.Context, args desktop.Args) (any, error) {
|
||||
mode := args.Opt("mode", "")
|
||||
if mode != "" && mode != "dark" && mode != "light" {
|
||||
return nil, fmt.Errorf("mode is dark or light")
|
||||
}
|
||||
if mode != "" {
|
||||
scheme := map[string]string{"dark": "prefer-dark", "light": "prefer-light"}[mode]
|
||||
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "color-scheme", scheme); !r.OK() {
|
||||
return nil, r.Err()
|
||||
}
|
||||
}
|
||||
scheme, err := a.gsetting(ctx, iface, "color-scheme")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("GSettings does not answer on the account's bus: %w", err)
|
||||
}
|
||||
gtkTheme, _ := a.gsetting(ctx, iface, "gtk-theme")
|
||||
gtk3 := readINI(filepath.Join(a.home, ".config", "gtk-3.0", "settings.ini"))["Settings"]
|
||||
gtk4 := readINI(filepath.Join(a.home, ".config", "gtk-4.0", "settings.ini"))["Settings"]
|
||||
qt := readINI(filepath.Join(a.home, ".config", "qt6ct", "qt6ct.conf"))["Appearance"]
|
||||
env := a.userEnvironment(ctx)
|
||||
answer := map[string]any{
|
||||
"gsettings": map[string]string{"color-scheme": scheme, "gtk-theme": gtkTheme},
|
||||
"portal": a.portalColourScheme(ctx),
|
||||
"gtk3": map[string]string{"theme": gtk3["gtk-theme-name"], "prefer-dark": gtk3["gtk-application-prefer-dark-theme"]},
|
||||
"gtk4": map[string]string{"theme": gtk4["gtk-theme-name"], "prefer-dark": gtk4["gtk-application-prefer-dark-theme"]},
|
||||
"qt": map[string]string{"style": qt["style"], "palette": filepath.Base(qt["color_scheme_path"])},
|
||||
"environment": env,
|
||||
}
|
||||
if mode != "" {
|
||||
var stays []string
|
||||
if strings.HasSuffix(env["GTK_THEME"], ":dark") && mode == "light" {
|
||||
stays = append(stays, "GTK 3 programs: GTK_THEME="+env["GTK_THEME"]+" in the environment pins them dark")
|
||||
}
|
||||
if mode == "light" {
|
||||
stays = append(stays, "the GTK settings files and Qt's palette, which the module declares dark")
|
||||
}
|
||||
answer["switched"] = mode
|
||||
answer["follows_live"] = "programs asking the portal: Electron, Chromium, Firefox, libadwaita and flatpaks"
|
||||
if len(stays) > 0 {
|
||||
answer["stays"] = stays
|
||||
}
|
||||
answer["lasts"] = "until the next login, which sets the module's default (dark) again; a persistent choice waits for settings (hq issue 168)"
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
// Theme is one installed icon or cursor theme.
|
||||
type Theme struct {
|
||||
Name string `json:"name"`
|
||||
Dir string `json:"dir"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Inherits []string `json:"inherits,omitempty"`
|
||||
Cursors bool `json:"cursors"`
|
||||
Icons bool `json:"icons"`
|
||||
}
|
||||
|
||||
// Themes lists the themes in dirs; a name found earlier hides the same name later, as lookups do.
|
||||
func Themes(dirs []string) []Theme {
|
||||
seen := map[string]bool{}
|
||||
var out []Theme
|
||||
for _, d := range dirs {
|
||||
entries, _ := os.ReadDir(d)
|
||||
for _, e := range entries {
|
||||
if !e.IsDir() && e.Type()&os.ModeSymlink == 0 || seen[e.Name()] {
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(d, e.Name())
|
||||
t := Theme{Name: e.Name(), Dir: dir}
|
||||
if info, err := os.Stat(filepath.Join(dir, "cursors")); err == nil && info.IsDir() {
|
||||
t.Cursors = true
|
||||
}
|
||||
if ini := readINI(filepath.Join(dir, "index.theme")); ini != nil {
|
||||
th := ini["Icon Theme"]
|
||||
t.Title = th["Name"]
|
||||
if th["Directories"] != "" {
|
||||
t.Icons = true
|
||||
}
|
||||
for _, i := range strings.Split(th["Inherits"], ",") {
|
||||
if i = strings.TrimSpace(i); i != "" {
|
||||
t.Inherits = append(t.Inherits, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !t.Cursors && !t.Icons && t.Title == "" {
|
||||
continue
|
||||
}
|
||||
seen[e.Name()] = true
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
var cursorName = regexp.MustCompile(`^[A-Za-z0-9._ -]{1,64}$`)
|
||||
|
||||
func (a adwaita) cursor(ctx context.Context, args desktop.Args) (any, error) {
|
||||
theme := args.Opt("theme", "")
|
||||
size, err := args.Whole("size", 0, 8, 256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cursors []string
|
||||
installed := map[string]bool{}
|
||||
for _, t := range Themes(a.iconDirs) {
|
||||
if t.Cursors {
|
||||
cursors = append(cursors, t.Name)
|
||||
installed[t.Name] = true
|
||||
}
|
||||
}
|
||||
changed := theme != "" || size != 0
|
||||
if theme != "" && (!cursorName.MatchString(theme) || !installed[theme]) {
|
||||
return nil, fmt.Errorf("%q is not an installed cursor theme; installed: %s", theme, strings.Join(cursors, ", "))
|
||||
}
|
||||
var resources []string
|
||||
if theme != "" {
|
||||
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "cursor-theme", theme); !r.OK() {
|
||||
return nil, r.Err()
|
||||
}
|
||||
resources = append(resources, "Xcursor.theme: "+theme)
|
||||
}
|
||||
if size != 0 {
|
||||
if r := a.d.AsUser(ctx, "gsettings", "set", iface, "cursor-size", strconv.Itoa(size)); !r.OK() {
|
||||
return nil, r.Err()
|
||||
}
|
||||
resources = append(resources, "Xcursor.size: "+strconv.Itoa(size))
|
||||
}
|
||||
answer := map[string]any{"installed": cursors}
|
||||
gTheme, _ := a.gsetting(ctx, iface, "cursor-theme")
|
||||
gSize, _ := a.gsetting(ctx, iface, "cursor-size")
|
||||
answer["gsettings"] = map[string]string{"cursor-theme": gTheme, "cursor-size": gSize}
|
||||
env := a.userEnvironment(ctx)
|
||||
answer["environment"] = map[string]string{"XCURSOR_THEME": env["XCURSOR_THEME"], "XCURSOR_SIZE": env["XCURSOR_SIZE"]}
|
||||
if s, err := a.d.Find(); err == nil {
|
||||
senv := s.Env(a.d.Base)
|
||||
if len(resources) > 0 {
|
||||
if r := a.d.Run(ctx, senv, []byte(strings.Join(resources, "\n")+"\n"), "xrdb", "-nocpp", "-merge", "-"); !r.OK() {
|
||||
return nil, r.Err()
|
||||
}
|
||||
}
|
||||
q := a.d.Run(ctx, senv, nil, "xrdb", "-query")
|
||||
x := map[string]string{}
|
||||
for _, l := range strings.Split(q.Stdout, "\n") {
|
||||
if k, v, ok := strings.Cut(l, ":"); ok && strings.HasPrefix(k, "Xcursor.") {
|
||||
x[k] = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
answer["x_resources"] = x
|
||||
} else {
|
||||
answer["x_resources"] = nil
|
||||
if changed {
|
||||
answer["note"] = "no graphical session: GSettings changed, the X resources not"
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
answer["lasts"] = "for windows opened from now on, until the next login"
|
||||
}
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
func (a adwaita) icons(ctx context.Context, args desktop.Args) (any, error) {
|
||||
var themes []Theme
|
||||
for _, t := range Themes(a.iconDirs) {
|
||||
if t.Icons {
|
||||
themes = append(themes, t)
|
||||
}
|
||||
}
|
||||
gtk3 := readINI(filepath.Join(a.home, ".config", "gtk-3.0", "settings.ini"))["Settings"]
|
||||
qt := readINI(filepath.Join(a.home, ".config", "qt6ct", "qt6ct.conf"))["Appearance"]
|
||||
g, _ := a.gsetting(ctx, iface, "icon-theme")
|
||||
return map[string]any{
|
||||
"installed": themes,
|
||||
"in_use": map[string]string{"gsettings": g, "gtk": gtk3["gtk-icon-theme-name"], "qt": qt["icon_theme"]},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Backend is one installed portal backend.
|
||||
type Backend struct {
|
||||
Name string `json:"name"`
|
||||
DBusName string `json:"dbus_name"`
|
||||
Interfaces []string `json:"interfaces"`
|
||||
UseIn []string `json:"use_in,omitempty"`
|
||||
Running bool `json:"running"`
|
||||
}
|
||||
|
||||
func splitList(v string) []string {
|
||||
var out []string
|
||||
for _, x := range strings.Split(v, ";") {
|
||||
if x = strings.TrimSpace(x); x != "" {
|
||||
out = append(out, x)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Backends reads the installed `.portal` files.
|
||||
func Backends(dirs []string) []Backend {
|
||||
var out []Backend
|
||||
for _, d := range dirs {
|
||||
files, _ := filepath.Glob(filepath.Join(d, "*.portal"))
|
||||
sort.Strings(files)
|
||||
for _, f := range files {
|
||||
p := readINI(f)["portal"]
|
||||
out = append(out, Backend{Name: strings.TrimSuffix(filepath.Base(f), ".portal"), DBusName: p["DBusName"],
|
||||
Interfaces: splitList(p["Interfaces"]), UseIn: splitList(p["UseIn"])})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// PortalConfigs are the files xdg-desktop-portal looks for, in its order (portals.conf(5)): for each
|
||||
// directory, `<desktop>-portals.conf` for each of the desktops named, then `portals.conf`. The first
|
||||
// that exists decides everything.
|
||||
func PortalConfigs(home string, desktops []string) []string {
|
||||
dirs := []string{
|
||||
filepath.Join(home, ".config", "xdg-desktop-portal"), "/etc/xdg/xdg-desktop-portal", "/etc/xdg-desktop-portal",
|
||||
filepath.Join(home, ".local", "share", "xdg-desktop-portal"), "/usr/local/share/xdg-desktop-portal", "/usr/share/xdg-desktop-portal",
|
||||
}
|
||||
var out []string
|
||||
for _, d := range dirs {
|
||||
for _, desk := range desktops {
|
||||
out = append(out, filepath.Join(d, strings.ToLower(desk)+"-portals.conf"))
|
||||
}
|
||||
out = append(out, filepath.Join(d, "portals.conf"))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Resolve says which backend answers each interface the backends implement, given the deciding
|
||||
// file's [preferred] section: an interface's own key first, else `default`; each a list of backend
|
||||
// names, the first one that implements the interface wins; `none` answers nothing, `*` any.
|
||||
// With no file, a backend whose UseIn names the desktop answers.
|
||||
func Resolve(backends []Backend, preferred map[string]string, desktops []string) map[string]string {
|
||||
out := map[string]string{}
|
||||
implements := func(b Backend, i string) bool {
|
||||
for _, x := range b.Interfaces {
|
||||
if x == i {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
var all []string
|
||||
seen := map[string]bool{}
|
||||
for _, b := range backends {
|
||||
for _, i := range b.Interfaces {
|
||||
if !seen[i] {
|
||||
seen[i] = true
|
||||
all = append(all, i)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(all)
|
||||
for _, i := range all {
|
||||
var want []string
|
||||
if preferred != nil {
|
||||
if v, ok := preferred[i]; ok {
|
||||
want = splitList(v)
|
||||
} else {
|
||||
want = splitList(preferred["default"])
|
||||
}
|
||||
} else {
|
||||
for _, b := range backends {
|
||||
for _, u := range b.UseIn {
|
||||
for _, d := range desktops {
|
||||
if strings.EqualFold(u, d) {
|
||||
want = append(want, b.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out[i] = "(none)"
|
||||
pick:
|
||||
for _, w := range want {
|
||||
if w == "none" {
|
||||
break
|
||||
}
|
||||
for _, b := range backends {
|
||||
if (w == "*" || w == b.Name) && implements(b, i) {
|
||||
out[i] = b.Name
|
||||
break pick
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a adwaita) portalCheck(ctx context.Context, args desktop.Args) (any, error) {
|
||||
env := a.userEnvironment(ctx)
|
||||
desktops := splitColon(env["XDG_CURRENT_DESKTOP"])
|
||||
backends := Backends(a.portalDirs)
|
||||
names := map[string]bool{}
|
||||
if r := a.d.AsUser(ctx, "busctl", "--user", "list", "--no-legend", "--no-pager"); r.OK() {
|
||||
for _, l := range strings.Split(r.Stdout, "\n") {
|
||||
if f := strings.Fields(l); len(f) > 1 && f[1] != "-" {
|
||||
names[f[0]] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range backends {
|
||||
backends[i].Running = names[backends[i].DBusName]
|
||||
}
|
||||
var decided string
|
||||
var preferred map[string]string
|
||||
looked := PortalConfigs(a.home, desktops)
|
||||
for _, f := range looked {
|
||||
if ini := readINI(f); ini != nil {
|
||||
decided, preferred = f, ini["preferred"]
|
||||
if preferred == nil {
|
||||
preferred = map[string]string{}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"desktop": env["XDG_CURRENT_DESKTOP"],
|
||||
"portal": map[string]bool{"running": names["org.freedesktop.portal.Desktop"]},
|
||||
"backends": backends,
|
||||
"decided_by": decided,
|
||||
"preferred": preferred,
|
||||
"answers": Resolve(backends, preferred, desktops),
|
||||
"colour_scheme": a.portalColourScheme(ctx),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func splitColon(v string) []string {
|
||||
var out []string
|
||||
for _, x := range strings.Split(v, ":") {
|
||||
if x = strings.TrimSpace(x); x != "" {
|
||||
out = append(out, x)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# Written by the mesh (module adwaita, novox/hq ADR 0208): the default cursor theme, for programs that
|
||||
# read neither XCURSOR_THEME nor the X resources.
|
||||
[Icon Theme]
|
||||
Name=Default
|
||||
Inherits=Adwaita
|
||||
@@ -0,0 +1,9 @@
|
||||
# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at
|
||||
# every push; adwaita_appearance switches dark and light for the running session.
|
||||
[Settings]
|
||||
gtk-theme-name=Adwaita
|
||||
gtk-icon-theme-name=Adwaita
|
||||
gtk-cursor-theme-name=Adwaita
|
||||
gtk-cursor-theme-size=24
|
||||
gtk-font-name=Inter 11
|
||||
gtk-application-prefer-dark-theme=1
|
||||
@@ -0,0 +1,11 @@
|
||||
# Written by the mesh (module adwaita, novox/hq ADR 0208). Replaced at every push.
|
||||
#
|
||||
# Which portal backend answers each interface. i3 is not a desktop xdg-desktop-portal knows, so with
|
||||
# no preference it uses whichever backend happens to be installed: fine while gtk is the only one,
|
||||
# wrong the day another arrives as somebody else's dependency. Named instead. gtk also serves
|
||||
# org.freedesktop.appearance (dark or light) from GSettings, which the session's start sets.
|
||||
[preferred]
|
||||
default=gtk
|
||||
# Secrets for sandboxed programs come from the keyring's backend. Without this line no backend answers
|
||||
# the interface: gtk does not implement it, and gnome-keyring's names only GNOME as its desktop.
|
||||
org.freedesktop.impl.portal.Secret=gnome-keyring
|
||||
@@ -0,0 +1,29 @@
|
||||
[Appearance]
|
||||
color_scheme_path=/usr/share/qt6ct/colors/darker.conf
|
||||
custom_palette=true
|
||||
icon_theme=Adwaita
|
||||
standard_dialogs=default
|
||||
style=Fusion
|
||||
|
||||
[Fonts]
|
||||
fixed="JetBrainsMono Nerd Font,11,-1,5,50,0,0,0,0,0"
|
||||
general="Inter,11,-1,5,50,0,0,0,0,0"
|
||||
|
||||
[Interface]
|
||||
activate_item_on_single_click=1
|
||||
buttonbox_layout=0
|
||||
cursor_flash_time=1000
|
||||
dialog_buttons_have_icons=1
|
||||
double_click_interval=400
|
||||
gui_effects=@Invalid()
|
||||
keyboard_scheme=2
|
||||
menus_have_icons=true
|
||||
show_shortcuts_in_context_menus=true
|
||||
stylesheets=@Invalid()
|
||||
toolbutton_style=4
|
||||
underline_shortcut=1
|
||||
wheel_scroll_lines=3
|
||||
|
||||
[Troubleshooting]
|
||||
force_raster_widgets=1
|
||||
ignored_applications=@Invalid()
|
||||
@@ -0,0 +1,5 @@
|
||||
module adwaita
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.7
|
||||
@@ -0,0 +1,2 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.7 h1:C0sTQmtTiyYH7bnqZb7PusXnqA37gKuT7Nqjn9gG47w=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.7/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
@@ -0,0 +1,160 @@
|
||||
package desktop
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Args reads a tool's arguments as JSON decoded them: strings, float64 numbers, booleans.
|
||||
type Args map[string]any
|
||||
|
||||
// Text is a required string, trimmed.
|
||||
func (a Args) Text(name string) (string, error) {
|
||||
v, ok := a[name].(string)
|
||||
if !ok || strings.TrimSpace(v) == "" {
|
||||
return "", fmt.Errorf("%s is required, as text", name)
|
||||
}
|
||||
return strings.TrimSpace(v), nil
|
||||
}
|
||||
|
||||
// Opt is an optional string, trimmed, or def.
|
||||
func (a Args) Opt(name, def string) string {
|
||||
if v, ok := a[name].(string); ok && strings.TrimSpace(v) != "" {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// Has is whether the caller gave the argument at all.
|
||||
func (a Args) Has(name string) bool {
|
||||
v, ok := a[name]
|
||||
return ok && v != nil
|
||||
}
|
||||
|
||||
// Bool is an optional boolean: its value, and whether it was given.
|
||||
func (a Args) Bool(name string) (bool, bool, error) {
|
||||
v, ok := a[name]
|
||||
if !ok || v == nil {
|
||||
return false, false, nil
|
||||
}
|
||||
b, isBool := v.(bool)
|
||||
if !isBool {
|
||||
return false, false, fmt.Errorf("%s is true or false", name)
|
||||
}
|
||||
return b, true, nil
|
||||
}
|
||||
|
||||
// Number is an optional number: its value, and whether it was given.
|
||||
func (a Args) Number(name string) (float64, bool, error) {
|
||||
v, ok := a[name]
|
||||
if !ok || v == nil {
|
||||
return 0, false, nil
|
||||
}
|
||||
f, isNum := v.(float64)
|
||||
if !isNum || math.IsNaN(f) || math.IsInf(f, 0) {
|
||||
return 0, false, fmt.Errorf("%s is a number", name)
|
||||
}
|
||||
return f, true, nil
|
||||
}
|
||||
|
||||
// Whole is an optional whole number within [lo, hi], or def.
|
||||
func (a Args) Whole(name string, def, lo, hi int) (int, error) {
|
||||
f, given, err := a.Number(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !given {
|
||||
return def, nil
|
||||
}
|
||||
if f != math.Trunc(f) || f < float64(lo) || f > float64(hi) {
|
||||
return 0, fmt.Errorf("%s is a whole number from %d to %d", name, lo, hi)
|
||||
}
|
||||
return int(f), nil
|
||||
}
|
||||
|
||||
// OneOf is an optional string that must be one of choices, or def.
|
||||
func (a Args) OneOf(name, def string, choices ...string) (string, error) {
|
||||
v := a.Opt(name, def)
|
||||
for _, c := range choices {
|
||||
if v == c {
|
||||
return v, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("%s is one of %s", name, strings.Join(choices, ", "))
|
||||
}
|
||||
|
||||
// Strings is an optional list of strings.
|
||||
func (a Args) Strings(name string) ([]string, error) {
|
||||
v, ok := a[name]
|
||||
if !ok || v == nil {
|
||||
return nil, nil
|
||||
}
|
||||
list, isList := v.([]any)
|
||||
if !isList {
|
||||
return nil, fmt.Errorf("%s is a list of text", name)
|
||||
}
|
||||
out := make([]string, 0, len(list))
|
||||
for _, x := range list {
|
||||
s, isText := x.(string)
|
||||
if !isText {
|
||||
return nil, fmt.Errorf("%s is a list of text", name)
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Home is the operator account's home: the runtime's word for it, else this process's.
|
||||
func Home() string {
|
||||
if h := os.Getenv("MESH_OPERATOR_HOME"); h != "" {
|
||||
return h
|
||||
}
|
||||
if h, err := os.UserHomeDir(); err == nil {
|
||||
return h
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
// InHome resolves a path the caller gave: `~/x` and a relative path are under the home. A path
|
||||
// that leaves the home through `..` is refused, so a tool that writes never writes outside it.
|
||||
func InHome(path string) (string, error) {
|
||||
home := Home()
|
||||
switch {
|
||||
case path == "~":
|
||||
path = home
|
||||
case strings.HasPrefix(path, "~/"):
|
||||
path = filepath.Join(home, path[2:])
|
||||
case !filepath.IsAbs(path):
|
||||
path = filepath.Join(home, path)
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
if path != home && !strings.HasPrefix(path, home+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("%s is outside the account's home", path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
// Schema builds a tool's input schema from property descriptions; required names those that must
|
||||
// be given. A property is a string unless its description object says otherwise.
|
||||
func Schema(props map[string]any, required ...string) map[string]any {
|
||||
s := map[string]any{"type": "object", "properties": props}
|
||||
if len(required) > 0 {
|
||||
s["required"] = required
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Str, Num, Flag, List and Enum describe one property.
|
||||
func Str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
|
||||
func Num(desc string) map[string]any { return map[string]any{"type": "number", "description": desc} }
|
||||
func Int(desc string) map[string]any { return map[string]any{"type": "integer", "description": desc} }
|
||||
func Flag(desc string) map[string]any { return map[string]any{"type": "boolean", "description": desc} }
|
||||
func List(desc string) map[string]any {
|
||||
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": desc}
|
||||
}
|
||||
func Enum(desc string, values ...string) map[string]any {
|
||||
return map[string]any{"type": "string", "enum": values, "description": desc}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package desktop
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The desktop modules that carry this package. Each builds alone, so each has its own copy; this
|
||||
// test, itself one of the copied files, holds them to one text wherever the siblings are present.
|
||||
var carriers = []string{"xorg", "lemurs", "i3", "xterm", "adwaita"}
|
||||
|
||||
func TestEveryDesktopModuleCarriesTheSameCopy(t *testing.T) {
|
||||
mine, err := filepath.Glob("*.go")
|
||||
if err != nil || len(mine) == 0 {
|
||||
t.Fatal("no files of this package found", err)
|
||||
}
|
||||
compared := 0
|
||||
for _, module := range carriers {
|
||||
dir := filepath.Join("..", "..", "..", module, "internal", "desktop")
|
||||
if _, err := os.Stat(dir); err != nil {
|
||||
continue
|
||||
}
|
||||
theirs, _ := filepath.Glob(filepath.Join(dir, "*.go"))
|
||||
if len(theirs) != len(mine) {
|
||||
t.Errorf("%s carries %d files of this package, this copy %d", module, len(theirs), len(mine))
|
||||
continue
|
||||
}
|
||||
for _, f := range mine {
|
||||
a, _ := os.ReadFile(f)
|
||||
b, err := os.ReadFile(filepath.Join(dir, f))
|
||||
if err != nil || !bytes.Equal(a, b) {
|
||||
t.Errorf("%s's copy of %s differs from this one: change every copy together", module, f)
|
||||
}
|
||||
}
|
||||
compared++
|
||||
}
|
||||
if compared == 0 {
|
||||
t.Log("no sibling copies beside this module")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package desktop
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Bounds on a command a tool runs: well below the runtime's 30 s call limit, and an answer that
|
||||
// fits in a tool's reply.
|
||||
const (
|
||||
DefaultTimeout = 10 * time.Second
|
||||
MostOutput = 256 << 10
|
||||
)
|
||||
|
||||
// Result is what one command did.
|
||||
type Result struct {
|
||||
Command []string `json:"command"`
|
||||
Code int `json:"exit_code"`
|
||||
Stdout string `json:"stdout,omitempty"`
|
||||
Stderr string `json:"stderr,omitempty"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
TimedOut bool `json:"timed_out,omitempty"`
|
||||
}
|
||||
|
||||
// OK is whether the command ran and exited 0.
|
||||
func (r Result) OK() bool { return r.Code == 0 && !r.TimedOut }
|
||||
|
||||
// Err is the command's failure as an error naming it and what it said, or nil.
|
||||
func (r Result) Err() error {
|
||||
if r.OK() {
|
||||
return nil
|
||||
}
|
||||
said := strings.TrimSpace(r.Stderr)
|
||||
if said == "" {
|
||||
said = strings.TrimSpace(r.Stdout)
|
||||
}
|
||||
if r.TimedOut {
|
||||
return fmt.Errorf("%s did not finish in time", strings.Join(r.Command, " "))
|
||||
}
|
||||
return fmt.Errorf("%s exited %d: %s", strings.Join(r.Command, " "), r.Code, said)
|
||||
}
|
||||
|
||||
// Runner runs a command with an environment and answers what it did. Tools take one, so their
|
||||
// tests replace the machine with a table of answers.
|
||||
type Runner func(ctx context.Context, env []string, stdin []byte, name string, args ...string) Result
|
||||
|
||||
// Exec is the machine's Runner: the command in its own process group, ended with everything it
|
||||
// started at the deadline, each stream cut at MostOutput.
|
||||
func Exec(ctx context.Context, env []string, stdin []byte, name string, args ...string) Result {
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, DefaultTimeout)
|
||||
defer cancel()
|
||||
}
|
||||
res := Result{Command: append([]string{name}, args...)}
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Env = env
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
if stdin != nil {
|
||||
cmd.Stdin = bytes.NewReader(stdin)
|
||||
}
|
||||
out, errb := &capped{}, &capped{}
|
||||
cmd.Stdout, cmd.Stderr = out, errb
|
||||
if err := cmd.Start(); err != nil {
|
||||
res.Code = 127
|
||||
res.Stderr = err.Error()
|
||||
return res
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
var err error
|
||||
select {
|
||||
case err = <-done:
|
||||
case <-ctx.Done():
|
||||
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
err = <-done
|
||||
res.TimedOut = true
|
||||
}
|
||||
res.Stdout, res.Stderr = out.String(), errb.String()
|
||||
res.Truncated = out.cut || errb.cut
|
||||
var exit *exec.ExitError
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.As(err, &exit):
|
||||
res.Code = exit.ExitCode()
|
||||
if res.Code < 0 {
|
||||
res.Code = 128
|
||||
}
|
||||
default:
|
||||
res.Code = 1
|
||||
if res.Stderr == "" {
|
||||
res.Stderr = err.Error()
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// capped keeps the first MostOutput bytes written to it. Its buffer is a field, not embedded: an
|
||||
// embedded bytes.Buffer brings ReadFrom along, and io.Copy would use it and never call Write.
|
||||
type capped struct {
|
||||
buf bytes.Buffer
|
||||
cut bool
|
||||
}
|
||||
|
||||
func (c *capped) Write(p []byte) (int, error) {
|
||||
if room := MostOutput - c.buf.Len(); room < len(p) {
|
||||
if room > 0 {
|
||||
c.buf.Write(p[:room])
|
||||
}
|
||||
c.cut = true
|
||||
return len(p), nil
|
||||
}
|
||||
return c.buf.Write(p)
|
||||
}
|
||||
|
||||
func (c *capped) String() string { return c.buf.String() }
|
||||
|
||||
// Desk is what a desktop tool needs: how to find the session, and how to run a command.
|
||||
type Desk struct {
|
||||
Find func() (*Session, error)
|
||||
Run Runner
|
||||
// Base is the environment a command starts from, before the session's words.
|
||||
Base []string
|
||||
}
|
||||
|
||||
// Machine is the real Desk, preferring the named processes as the session's.
|
||||
func Machine(prefer ...string) Desk {
|
||||
return Desk{
|
||||
Find: func() (*Session, error) { return Find(prefer...) },
|
||||
Run: Exec,
|
||||
Base: os.Environ(),
|
||||
}
|
||||
}
|
||||
|
||||
// InSession runs a command in the operator's session, or answers NoSession.
|
||||
func (d Desk) InSession(ctx context.Context, name string, args ...string) (Result, *Session, error) {
|
||||
s, err := d.Find()
|
||||
if err != nil {
|
||||
return Result{}, nil, err
|
||||
}
|
||||
return d.Run(ctx, s.Env(d.Base), nil, name, args...), s, nil
|
||||
}
|
||||
|
||||
// InSessionWith is InSession with standard input.
|
||||
func (d Desk) InSessionWith(ctx context.Context, stdin []byte, name string, args ...string) (Result, *Session, error) {
|
||||
s, err := d.Find()
|
||||
if err != nil {
|
||||
return Result{}, nil, err
|
||||
}
|
||||
return d.Run(ctx, s.Env(d.Base), stdin, name, args...), s, nil
|
||||
}
|
||||
|
||||
// Plain runs a command with the base environment: for what needs no session.
|
||||
func (d Desk) Plain(ctx context.Context, name string, args ...string) Result {
|
||||
return d.Run(ctx, d.Base, nil, name, args...)
|
||||
}
|
||||
|
||||
// AsUser runs a command with the account's own runtime directory and bus, and no display.
|
||||
func (d Desk) AsUser(ctx context.Context, name string, args ...string) Result {
|
||||
return d.Run(ctx, UserEnv(d.Base, os.Getuid()), nil, name, args...)
|
||||
}
|
||||
|
||||
// Launched is how a program was started in the session.
|
||||
type Launched struct {
|
||||
Unit string `json:"unit,omitempty"`
|
||||
PID int `json:"pid,omitempty"`
|
||||
How string `json:"how"`
|
||||
}
|
||||
|
||||
// Launch starts a program in the operator's session that outlives the call and the runtime.
|
||||
//
|
||||
// **Not as a child of this process.** The runtime is a system service; everything it starts is in
|
||||
// its control group, and the service manager ends that group whenever the runtime restarts — which
|
||||
// is every push that changes it. So the program is handed to the account's own service manager as a
|
||||
// transient unit (`systemd-run --user`), with the session's words set on it, and lives as long as the
|
||||
// operator's user manager does. Without a user manager it is started detached as a last resort, and
|
||||
// the answer says it will end with the runtime.
|
||||
func (d Desk) Launch(ctx context.Context, s *Session, name string, argv ...string) (Launched, error) {
|
||||
if len(argv) == 0 {
|
||||
return Launched{}, errors.New("nothing to launch")
|
||||
}
|
||||
env := s.Env(d.Base)
|
||||
unit := "mesh-" + name + "-" + token()
|
||||
args := []string{"--user", "--collect", "--quiet", "--unit=" + unit}
|
||||
for _, w := range []string{"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_SESSION_TYPE", "XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "I3SOCK", "SWAYSOCK"} {
|
||||
if v := lookup(env, w); v != "" {
|
||||
args = append(args, "--setenv="+w+"="+v)
|
||||
}
|
||||
}
|
||||
args = append(args, "--")
|
||||
args = append(args, argv...)
|
||||
res := d.Run(ctx, env, nil, "systemd-run", args...)
|
||||
if res.OK() {
|
||||
return Launched{Unit: unit, How: "a transient unit of the account's service manager; ends when it exits or when the operator logs out"}, nil
|
||||
}
|
||||
if s.Bus != "" {
|
||||
return Launched{}, res.Err()
|
||||
}
|
||||
cmd := exec.Command(argv[0], argv[1:]...)
|
||||
cmd.Env = env
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return Launched{}, err
|
||||
}
|
||||
pid := cmd.Process.Pid
|
||||
go func() { _ = cmd.Wait() }()
|
||||
return Launched{PID: pid, How: "detached from the runtime with no user manager to hand it to; it ends when the runtime restarts"}, nil
|
||||
}
|
||||
|
||||
func lookup(env []string, name string) string {
|
||||
for i := len(env) - 1; i >= 0; i-- {
|
||||
if k, v, ok := strings.Cut(env[i], "="); ok && k == name {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func token() string {
|
||||
b := make([]byte, 4)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
// Package desktop is how a desktop module's tools act in the operator's graphical session
|
||||
// (novox/hq ADR 0208, research 026/05).
|
||||
//
|
||||
// **One question, answered once for every desktop tool.** A tool runs inside the node's runtime: a
|
||||
// process of node-tools.service, started by the system's service manager as the operator account,
|
||||
// with no session around it — no DISPLAY, no XAUTHORITY, no session bus. The session it must act in
|
||||
// was started elsewhere, by the login manager, and the only place its values are written down is
|
||||
// the environment of the processes it started. So this package finds the session the way a person
|
||||
// would: it looks at the operator account's own processes, takes the one that is plainly the
|
||||
// session's (the window manager, or the oldest process carrying a display), confirms with logind
|
||||
// that its session is a live local one, and checks that the display's socket is really there.
|
||||
//
|
||||
// **Only the session's own words are read.** A session's processes also carry whatever its start
|
||||
// script exported — on the workstations that was a file of secrets — so the environment is filtered
|
||||
// to a fixed list of names while it is read, and nothing else ever leaves /proc.
|
||||
//
|
||||
// The D-Bus address handed on is the user manager's socket, `unix:path=$XDG_RUNTIME_DIR/bus`,
|
||||
// whenever it exists, because that is where the portal, the notifier and every user service
|
||||
// listen. A session started on a private bus (a stale session, measured on one workstation) is
|
||||
// reported as `session_bus` beside it, so the difference is visible rather than guessed at.
|
||||
//
|
||||
// The same copy of this package is vendored into every desktop module (xorg, lemurs, i3, xterm,
|
||||
// adwaita); the catalogue builds each module alone, so it cannot be imported across them. Change
|
||||
// every copy together — the modules' tests compare them.
|
||||
package desktop
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SessionWords are the only environment words read from a session's process: the ones that say
|
||||
// where the session is. Everything else in that environment is the operator's, and is never read.
|
||||
var SessionWords = []string{
|
||||
"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY",
|
||||
"XDG_SESSION_ID", "XDG_SESSION_TYPE", "XDG_SESSION_DESKTOP", "XDG_CURRENT_DESKTOP",
|
||||
"XDG_RUNTIME_DIR", "DBUS_SESSION_BUS_ADDRESS", "XDG_SEAT", "XDG_VTNR",
|
||||
"I3SOCK", "SWAYSOCK",
|
||||
}
|
||||
|
||||
// Session is the operator's running graphical session, as a tool needs it.
|
||||
type Session struct {
|
||||
UID int `json:"uid"`
|
||||
ID string `json:"session_id,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Display string `json:"display,omitempty"`
|
||||
WaylandDisplay string `json:"wayland_display,omitempty"`
|
||||
XAuthority string `json:"xauthority,omitempty"`
|
||||
RuntimeDir string `json:"runtime_dir"`
|
||||
Bus string `json:"bus,omitempty"`
|
||||
SessionBus string `json:"session_bus,omitempty"`
|
||||
Desktop string `json:"desktop,omitempty"`
|
||||
// FoundIn is the process whose environment named the session.
|
||||
FoundIn Process `json:"found_in"`
|
||||
// Active is logind's word on the session, when logind answered.
|
||||
Active *bool `json:"active,omitempty"`
|
||||
|
||||
words map[string]string
|
||||
}
|
||||
|
||||
// Process is one process the search looked at.
|
||||
type Process struct {
|
||||
PID int `json:"pid"`
|
||||
Command string `json:"command"`
|
||||
start uint64
|
||||
}
|
||||
|
||||
// NoSession is the answer when there is no graphical session to act in. Its text is JSON, so a tool
|
||||
// that returns it as its error still answers structured data.
|
||||
type NoSession struct {
|
||||
Reason string `json:"reason"`
|
||||
Looked []string `json:"looked"`
|
||||
}
|
||||
|
||||
func (e *NoSession) Error() string {
|
||||
b, _ := json.Marshal(map[string]any{"error": "no-graphical-session", "reason": e.Reason, "looked": e.Looked})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// IsNoSession is whether err says there is no session.
|
||||
func IsNoSession(err error) bool {
|
||||
var n *NoSession
|
||||
return errors.As(err, &n)
|
||||
}
|
||||
|
||||
// Finder holds where the search looks, so a test can point it at a tree of its own.
|
||||
type Finder struct {
|
||||
Proc string // the process table: /proc
|
||||
X11Sockets string // where X servers listen: /tmp/.X11-unix
|
||||
RuntimeBase string // the parent of every XDG_RUNTIME_DIR: /run/user
|
||||
UID int // whose session
|
||||
// Prefer names the processes that are the session's own, best first: the session's holder.
|
||||
Prefer []string
|
||||
// Logind answers `loginctl show-session` for one id; nil skips the check.
|
||||
Logind func(id string) (map[string]string, error)
|
||||
}
|
||||
|
||||
// DefaultFinder is the machine's: the account this process runs as, or — when it runs as root — the
|
||||
// operator account the runtime names (MESH_OPERATOR_ACCOUNT).
|
||||
func DefaultFinder(prefer ...string) Finder {
|
||||
uid := os.Getuid()
|
||||
if uid == 0 {
|
||||
if name := os.Getenv("MESH_OPERATOR_ACCOUNT"); name != "" {
|
||||
if u, err := user.Lookup(name); err == nil {
|
||||
if n, err := strconv.Atoi(u.Uid); err == nil {
|
||||
uid = n
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return Finder{
|
||||
Proc: "/proc", X11Sockets: "/tmp/.X11-unix", RuntimeBase: "/run/user",
|
||||
UID: uid, Prefer: prefer, Logind: loginctl,
|
||||
}
|
||||
}
|
||||
|
||||
// Find is the operator's session on this machine, preferring a process named in prefer.
|
||||
func Find(prefer ...string) (*Session, error) {
|
||||
return DefaultFinder(prefer...).Find()
|
||||
}
|
||||
|
||||
type candidate struct {
|
||||
proc Process
|
||||
words map[string]string
|
||||
rank int
|
||||
logind map[string]string
|
||||
}
|
||||
|
||||
// Find looks for the session.
|
||||
func (f Finder) Find() (*Session, error) {
|
||||
entries, err := os.ReadDir(f.Proc)
|
||||
if err != nil {
|
||||
return nil, &NoSession{Reason: "the process table cannot be read: " + err.Error(), Looked: []string{f.Proc}}
|
||||
}
|
||||
looked := []string{fmt.Sprintf("the processes of uid %d in %s", f.UID, f.Proc)}
|
||||
var found []candidate
|
||||
stale := 0
|
||||
for _, e := range entries {
|
||||
pid, err := strconv.Atoi(e.Name())
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
dir := filepath.Join(f.Proc, e.Name())
|
||||
info, err := os.Stat(dir)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if st, ok := info.Sys().(*syscall.Stat_t); !ok || int(st.Uid) != f.UID {
|
||||
continue
|
||||
}
|
||||
words := readWords(filepath.Join(dir, "environ"))
|
||||
if words["DISPLAY"] == "" && words["WAYLAND_DISPLAY"] == "" {
|
||||
continue
|
||||
}
|
||||
if !f.reachable(words) {
|
||||
stale++
|
||||
continue
|
||||
}
|
||||
found = append(found, candidate{proc: Process{PID: pid, Command: comm(dir), start: startTime(dir)}, words: words})
|
||||
}
|
||||
if len(found) == 0 {
|
||||
reason := fmt.Sprintf("no process of uid %d carries a display", f.UID)
|
||||
if stale > 0 {
|
||||
reason = fmt.Sprintf("%d process(es) of uid %d name a display whose socket is gone: the session they belonged to has ended", stale, f.UID)
|
||||
}
|
||||
return nil, &NoSession{Reason: reason, Looked: append(looked, f.X11Sockets, f.RuntimeBase)}
|
||||
}
|
||||
|
||||
// logind's word on each session the candidates name, asked once per session.
|
||||
asked := map[string]map[string]string{}
|
||||
for i := range found {
|
||||
id := found[i].words["XDG_SESSION_ID"]
|
||||
if f.Logind == nil || id == "" {
|
||||
found[i].rank = 1
|
||||
continue
|
||||
}
|
||||
props, done := asked[id]
|
||||
if !done {
|
||||
props, _ = f.Logind(id)
|
||||
asked[id] = props
|
||||
}
|
||||
found[i].logind = props
|
||||
switch {
|
||||
case props == nil:
|
||||
found[i].rank = 1
|
||||
case props["Remote"] == "yes":
|
||||
found[i].rank = 3
|
||||
case props["Active"] == "yes" && props["State"] != "closing":
|
||||
found[i].rank = 0
|
||||
case props["State"] == "closing":
|
||||
found[i].rank = 3
|
||||
default:
|
||||
found[i].rank = 2
|
||||
}
|
||||
}
|
||||
if f.Logind != nil {
|
||||
looked = append(looked, "logind's sessions")
|
||||
}
|
||||
preferred := func(c candidate) int {
|
||||
for i, p := range f.Prefer {
|
||||
if c.proc.Command == p {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return len(f.Prefer)
|
||||
}
|
||||
sort.SliceStable(found, func(i, j int) bool {
|
||||
a, b := found[i], found[j]
|
||||
if a.rank != b.rank {
|
||||
return a.rank < b.rank
|
||||
}
|
||||
if pa, pb := preferred(a), preferred(b); pa != pb {
|
||||
return pa < pb
|
||||
}
|
||||
if a.proc.start != b.proc.start {
|
||||
return a.proc.start < b.proc.start
|
||||
}
|
||||
return a.proc.PID < b.proc.PID
|
||||
})
|
||||
best := found[0]
|
||||
if best.rank == 3 {
|
||||
return nil, &NoSession{Reason: "the only sessions found are remote or closing", Looked: looked}
|
||||
}
|
||||
return f.session(best), nil
|
||||
}
|
||||
|
||||
func (f Finder) session(c candidate) *Session {
|
||||
w := c.words
|
||||
s := &Session{
|
||||
UID: f.UID, ID: w["XDG_SESSION_ID"], Display: w["DISPLAY"], WaylandDisplay: w["WAYLAND_DISPLAY"],
|
||||
XAuthority: w["XAUTHORITY"], RuntimeDir: w["XDG_RUNTIME_DIR"], FoundIn: c.proc, words: w,
|
||||
}
|
||||
s.Desktop = w["XDG_CURRENT_DESKTOP"]
|
||||
if s.Desktop == "" {
|
||||
s.Desktop = w["XDG_SESSION_DESKTOP"]
|
||||
}
|
||||
switch {
|
||||
case w["XDG_SESSION_TYPE"] != "":
|
||||
s.Type = w["XDG_SESSION_TYPE"]
|
||||
case s.WaylandDisplay != "":
|
||||
s.Type = "wayland"
|
||||
default:
|
||||
s.Type = "x11"
|
||||
}
|
||||
if s.RuntimeDir == "" {
|
||||
s.RuntimeDir = filepath.Join(f.RuntimeBase, strconv.Itoa(f.UID))
|
||||
}
|
||||
if isSocket(filepath.Join(s.RuntimeDir, "bus")) {
|
||||
s.Bus = "unix:path=" + filepath.Join(s.RuntimeDir, "bus")
|
||||
}
|
||||
if own := w["DBUS_SESSION_BUS_ADDRESS"]; own != "" && own != s.Bus {
|
||||
s.SessionBus = own
|
||||
}
|
||||
if c.logind != nil {
|
||||
active := c.logind["Active"] == "yes"
|
||||
s.Active = &active
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// reachable is whether the display a process names is still served: the X server's socket, or the
|
||||
// Wayland compositor's. A process outliving its session still carries the session's words.
|
||||
func (f Finder) reachable(w map[string]string) bool {
|
||||
if d := w["WAYLAND_DISPLAY"]; d != "" {
|
||||
path := d
|
||||
if !filepath.IsAbs(d) {
|
||||
dir := w["XDG_RUNTIME_DIR"]
|
||||
if dir == "" {
|
||||
dir = filepath.Join(f.RuntimeBase, strconv.Itoa(f.UID))
|
||||
}
|
||||
path = filepath.Join(dir, d)
|
||||
}
|
||||
if isSocket(path) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
n, ok := DisplayNumber(w["DISPLAY"])
|
||||
return ok && isSocket(filepath.Join(f.X11Sockets, "X"+strconv.Itoa(n)))
|
||||
}
|
||||
|
||||
// DisplayNumber is the server number of a local X display (":1", ":1.0", "unix:1"); a display on
|
||||
// another host — an ssh session's forwarded one — is not the local session and answers false.
|
||||
func DisplayNumber(display string) (int, bool) {
|
||||
host, rest, ok := strings.Cut(display, ":")
|
||||
if !ok || (host != "" && host != "unix") {
|
||||
return 0, false
|
||||
}
|
||||
num, _, _ := strings.Cut(rest, ".")
|
||||
n, err := strconv.Atoi(num)
|
||||
if err != nil || n < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// Word is one of the session's words as its process had it ("" when it had none).
|
||||
func (s *Session) Word(name string) string { return s.words[name] }
|
||||
|
||||
// Env is base with the session's words in place of whatever base said for them.
|
||||
func (s *Session) Env(base []string) []string {
|
||||
drop := map[string]bool{}
|
||||
for _, w := range SessionWords {
|
||||
drop[w] = true
|
||||
}
|
||||
out := make([]string, 0, len(base)+8)
|
||||
for _, kv := range base {
|
||||
k, _, _ := strings.Cut(kv, "=")
|
||||
if !drop[k] {
|
||||
out = append(out, kv)
|
||||
}
|
||||
}
|
||||
bus := s.Bus
|
||||
if bus == "" {
|
||||
bus = s.SessionBus
|
||||
}
|
||||
for _, kv := range [][2]string{
|
||||
{"DISPLAY", s.Display}, {"WAYLAND_DISPLAY", s.WaylandDisplay}, {"XAUTHORITY", s.XAuthority},
|
||||
{"XDG_RUNTIME_DIR", s.RuntimeDir}, {"DBUS_SESSION_BUS_ADDRESS", bus},
|
||||
{"XDG_SESSION_TYPE", s.Type}, {"XDG_SESSION_ID", s.ID},
|
||||
{"XDG_CURRENT_DESKTOP", s.words["XDG_CURRENT_DESKTOP"]},
|
||||
{"XDG_SESSION_DESKTOP", s.words["XDG_SESSION_DESKTOP"]},
|
||||
{"I3SOCK", s.words["I3SOCK"]}, {"SWAYSOCK", s.words["SWAYSOCK"]},
|
||||
} {
|
||||
if kv[1] != "" {
|
||||
out = append(out, kv[0]+"="+kv[1])
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// UserEnv is base with the account's own runtime directory and bus, for a tool that talks to the
|
||||
// user manager or the session bus and needs no display — it works with no session at all.
|
||||
func UserEnv(base []string, uid int) []string {
|
||||
dir := filepath.Join("/run/user", strconv.Itoa(uid))
|
||||
out := make([]string, 0, len(base)+2)
|
||||
for _, kv := range base {
|
||||
k, _, _ := strings.Cut(kv, "=")
|
||||
if k != "XDG_RUNTIME_DIR" && k != "DBUS_SESSION_BUS_ADDRESS" {
|
||||
out = append(out, kv)
|
||||
}
|
||||
}
|
||||
return append(out, "XDG_RUNTIME_DIR="+dir, "DBUS_SESSION_BUS_ADDRESS=unix:path="+filepath.Join(dir, "bus"))
|
||||
}
|
||||
|
||||
// readWords reads a process's environment and keeps only SessionWords.
|
||||
func readWords(path string) map[string]string {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
keep := map[string]bool{}
|
||||
for _, w := range SessionWords {
|
||||
keep[w] = true
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, kv := range bytes.Split(raw, []byte{0}) {
|
||||
k, v, ok := bytes.Cut(kv, []byte{'='})
|
||||
if ok && keep[string(k)] {
|
||||
out[string(k)] = string(v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func comm(dir string) string {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "comm"))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// startTime is field 22 of /proc/<pid>/stat: when the process started, in clock ticks since boot.
|
||||
// Read after the command's closing parenthesis, because the command may hold spaces.
|
||||
func startTime(dir string) uint64 {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "stat"))
|
||||
if err != nil {
|
||||
return ^uint64(0)
|
||||
}
|
||||
i := bytes.LastIndexByte(b, ')')
|
||||
if i < 0 {
|
||||
return ^uint64(0)
|
||||
}
|
||||
fields := strings.Fields(string(b[i+1:]))
|
||||
// fields[0] is the state, field 3 of the line; start time is field 22.
|
||||
if len(fields) < 20 {
|
||||
return ^uint64(0)
|
||||
}
|
||||
n, err := strconv.ParseUint(fields[19], 10, 64)
|
||||
if err != nil {
|
||||
return ^uint64(0)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func isSocket(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && info.Mode()&os.ModeSocket != 0
|
||||
}
|
||||
|
||||
// loginctl asks logind about one session, by its property lines.
|
||||
func loginctl(id string) (map[string]string, error) {
|
||||
cmd := exec.Command("loginctl", "show-session", id, "-p", "Active", "-p", "State", "-p", "Remote", "-p", "Type", "-p", "Class")
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
done := make(chan error, 1)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
return nil, errors.New("loginctl did not answer in 3s")
|
||||
}
|
||||
return ParseProperties(out.String()), nil
|
||||
}
|
||||
|
||||
// ParseProperties reads `Key=Value` lines, as loginctl and systemctl show print them.
|
||||
func ParseProperties(text string) map[string]string {
|
||||
out := map[string]string{}
|
||||
sc := bufio.NewScanner(strings.NewReader(text))
|
||||
for sc.Scan() {
|
||||
if k, v, ok := strings.Cut(sc.Text(), "="); ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package desktop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A machine in a directory: a process table, the X servers' socket directory and a runtime base.
|
||||
type fakeMachine struct {
|
||||
t *testing.T
|
||||
proc, x11, runtime string
|
||||
uid int
|
||||
}
|
||||
|
||||
func newMachine(t *testing.T) *fakeMachine {
|
||||
root, err := os.MkdirTemp("", "desk")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(root) })
|
||||
m := &fakeMachine{t: t, proc: filepath.Join(root, "p"), x11: filepath.Join(root, "x"), runtime: filepath.Join(root, "r"), uid: os.Getuid()}
|
||||
for _, d := range []string{m.proc, m.x11, filepath.Join(m.runtime, strconv.Itoa(m.uid))} {
|
||||
if err := os.MkdirAll(d, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *fakeMachine) socket(path string) {
|
||||
l, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
m.t.Fatal(err)
|
||||
}
|
||||
m.t.Cleanup(func() { l.Close() })
|
||||
}
|
||||
|
||||
func (m *fakeMachine) process(pid int, comm string, start int, env ...string) {
|
||||
dir := filepath.Join(m.proc, strconv.Itoa(pid))
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
m.t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(dir, "environ"), []byte(strings.Join(env, "\x00")+"\x00"), 0o600)
|
||||
os.WriteFile(filepath.Join(dir, "comm"), []byte(comm+"\n"), 0o644)
|
||||
// pid (comm) state ppid pgrp session tty tpgid flags minflt cminflt majflt cmajflt utime stime
|
||||
// cutime cstime priority nice threads itrealvalue starttime ...
|
||||
stat := strconv.Itoa(pid) + " (" + comm + ") S 1 1 1 0 -1 0 0 0 0 0 0 0 0 0 20 0 1 0 " + strconv.Itoa(start) + " 0 0"
|
||||
os.WriteFile(filepath.Join(dir, "stat"), []byte(stat), 0o644)
|
||||
}
|
||||
|
||||
func (m *fakeMachine) finder(logind func(string) (map[string]string, error), prefer ...string) Finder {
|
||||
return Finder{Proc: m.proc, X11Sockets: m.x11, RuntimeBase: m.runtime, UID: m.uid, Prefer: prefer, Logind: logind}
|
||||
}
|
||||
|
||||
func active(id string) (map[string]string, error) {
|
||||
return map[string]string{"Active": "yes", "State": "active", "Remote": "no", "Type": "x11"}, nil
|
||||
}
|
||||
|
||||
func TestTheSessionIsFoundInTheWindowManagersEnvironmentAndOnlyItsWordsAreRead(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
m.socket(filepath.Join(m.x11, "X1"))
|
||||
run := filepath.Join(m.runtime, strconv.Itoa(m.uid))
|
||||
m.socket(filepath.Join(run, "bus"))
|
||||
m.process(100, "lemurs-child", 5, "DISPLAY=:1", "XDG_SESSION_ID=1")
|
||||
m.process(200, "i3", 10, "DISPLAY=:1", "XAUTHORITY=/home/op/.Xauthority", "XDG_SESSION_ID=1",
|
||||
"XDG_SESSION_TYPE=x11", "XDG_CURRENT_DESKTOP=i3", "XDG_RUNTIME_DIR="+run,
|
||||
"DBUS_SESSION_BUS_ADDRESS=unix:path=/tmp/dbus-private", "NPM_TOKEN=secret", "OPENAI_API_KEY=secret")
|
||||
m.process(300, "zsh", 50, "TERM=xterm") // no display: not a candidate
|
||||
|
||||
s, err := m.finder(active, "i3").Find()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.FoundIn.PID != 200 || s.Display != ":1" || s.XAuthority != "/home/op/.Xauthority" || s.ID != "1" || s.Type != "x11" || s.Desktop != "i3" {
|
||||
t.Fatalf("session: %+v", s)
|
||||
}
|
||||
if s.Bus != "unix:path="+filepath.Join(run, "bus") || s.SessionBus != "unix:path=/tmp/dbus-private" {
|
||||
t.Fatalf("the user manager's bus first, the session's private one reported beside it: %q %q", s.Bus, s.SessionBus)
|
||||
}
|
||||
if s.Active == nil || !*s.Active {
|
||||
t.Fatal("logind's word is carried")
|
||||
}
|
||||
env := strings.Join(s.Env([]string{"PATH=/usr/bin", "DISPLAY=:9", "HOME=/home/op"}), "\n")
|
||||
for _, want := range []string{"PATH=/usr/bin", "HOME=/home/op", "DISPLAY=:1", "XAUTHORITY=/home/op/.Xauthority", "DBUS_SESSION_BUS_ADDRESS=unix:path=" + filepath.Join(run, "bus"), "XDG_RUNTIME_DIR=" + run} {
|
||||
if !strings.Contains(env, want) {
|
||||
t.Errorf("env lacks %s:\n%s", want, env)
|
||||
}
|
||||
}
|
||||
if strings.Contains(env, ":9") || strings.Contains(env, "secret") || strings.Contains(env, "NPM_TOKEN") {
|
||||
t.Fatalf("the base's display is replaced and no other word of the session's process passes:\n%s", env)
|
||||
}
|
||||
b, _ := json.Marshal(s)
|
||||
if strings.Contains(string(b), "secret") {
|
||||
t.Fatal("the answer carries a word outside the session's")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWithoutAPreferenceTheOldestProcessOfTheLiveSessionWins(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
m.socket(filepath.Join(m.x11, "X0"))
|
||||
m.process(410, "xterm", 90, "DISPLAY=:0", "XDG_SESSION_ID=3")
|
||||
m.process(400, "openbox", 20, "DISPLAY=:0", "XDG_SESSION_ID=3")
|
||||
s, err := m.finder(nil).Find()
|
||||
if err != nil || s.FoundIn.PID != 400 {
|
||||
t.Fatalf("%+v %v", s, err)
|
||||
}
|
||||
if s.RuntimeDir != filepath.Join(m.runtime, strconv.Itoa(m.uid)) || s.Bus != "" {
|
||||
t.Fatalf("an absent runtime directory word falls back to the account's, and no bus socket means no bus: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestALeftoverProcessOfAnEndedSessionIsNotTheSession(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
m.process(500, "i3", 10, "DISPLAY=:2", "XDG_SESSION_ID=7") // no X2 socket
|
||||
_, err := m.finder(active, "i3").Find()
|
||||
if !IsNoSession(err) || !strings.Contains(err.Error(), "socket is gone") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
var answer map[string]any
|
||||
if json.Unmarshal([]byte(err.Error()), &answer) != nil || answer["error"] != "no-graphical-session" {
|
||||
t.Fatalf("the refusal is structured: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoProcessWithADisplayIsAClearNoSession(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
m.process(600, "sshd", 1, "SSH_CONNECTION=x")
|
||||
_, err := m.finder(active).Find()
|
||||
if !IsNoSession(err) || !strings.Contains(err.Error(), "no process of uid") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnActiveLocalSessionBeatsAnInactiveOneAndARemoteOneIsRefused(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
m.socket(filepath.Join(m.x11, "X0"))
|
||||
m.socket(filepath.Join(m.x11, "X1"))
|
||||
m.process(700, "i3", 5, "DISPLAY=:0", "XDG_SESSION_ID=a")
|
||||
m.process(800, "i3", 9, "DISPLAY=:1", "XDG_SESSION_ID=b")
|
||||
logind := func(id string) (map[string]string, error) {
|
||||
if id == "a" {
|
||||
return map[string]string{"Active": "no", "State": "online", "Remote": "no"}, nil
|
||||
}
|
||||
return map[string]string{"Active": "yes", "State": "active", "Remote": "no"}, nil
|
||||
}
|
||||
s, err := m.finder(logind, "i3").Find()
|
||||
if err != nil || s.FoundIn.PID != 800 || s.Display != ":1" {
|
||||
t.Fatalf("the active session: %+v %v", s, err)
|
||||
}
|
||||
remote := func(string) (map[string]string, error) {
|
||||
return map[string]string{"Active": "yes", "Remote": "yes"}, nil
|
||||
}
|
||||
if _, err := m.finder(remote).Find(); !IsNoSession(err) {
|
||||
t.Fatalf("a remote session is not the operator's desktop: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWaylandSessionIsFoundByItsCompositorsSocket(t *testing.T) {
|
||||
m := newMachine(t)
|
||||
run := filepath.Join(m.runtime, strconv.Itoa(m.uid))
|
||||
m.socket(filepath.Join(run, "wayland-1"))
|
||||
m.process(900, "sway", 3, "WAYLAND_DISPLAY=wayland-1", "XDG_RUNTIME_DIR="+run, "SWAYSOCK=/run/x.sock")
|
||||
s, err := m.finder(nil, "sway").Find()
|
||||
if err != nil || s.Type != "wayland" || s.WaylandDisplay != "wayland-1" {
|
||||
t.Fatalf("%+v %v", s, err)
|
||||
}
|
||||
if !strings.Contains(strings.Join(s.Env(nil), " "), "SWAYSOCK=/run/x.sock") {
|
||||
t.Fatal("the compositor's socket word passes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestADisplayOnAnotherHostIsNotTheLocalSession(t *testing.T) {
|
||||
for d, want := range map[string]bool{":0": true, ":1.0": true, "unix:2": true, "localhost:10.0": false, "host:0": false, "": false, ":x": false} {
|
||||
if _, ok := DisplayNumber(d); ok != want {
|
||||
t.Errorf("%q: %v", d, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestACommandIsBoundedAndItsFailureNamed(t *testing.T) {
|
||||
r := Exec(context.Background(), os.Environ(), []byte("hello"), "cat")
|
||||
if !r.OK() || r.Stdout != "hello" {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
r = Exec(context.Background(), os.Environ(), nil, "sh", "-c", "echo no >&2; exit 3")
|
||||
if r.OK() || r.Code != 3 || !strings.Contains(r.Err().Error(), "exited 3: no") {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
r = Exec(context.Background(), os.Environ(), nil, "no-such-program-here")
|
||||
if r.OK() || r.Code != 127 {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
r = Exec(context.Background(), os.Environ(), nil, "sh", "-c", "head -c 400000 /dev/zero")
|
||||
if !r.Truncated || len(r.Stdout) != MostOutput {
|
||||
t.Fatalf("cut at %d: %d %v", MostOutput, len(r.Stdout), r.Truncated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArgumentsAreReadStrictly(t *testing.T) {
|
||||
a := Args{"name": " x ", "n": float64(3), "f": 1.5, "b": true, "l": []any{"a", "b"}}
|
||||
if v, err := a.Text("name"); err != nil || v != "x" {
|
||||
t.Fatal(v, err)
|
||||
}
|
||||
if _, err := a.Text("missing"); err == nil {
|
||||
t.Fatal("a missing required text")
|
||||
}
|
||||
if n, err := a.Whole("n", 0, 1, 5); err != nil || n != 3 {
|
||||
t.Fatal(n, err)
|
||||
}
|
||||
if _, err := a.Whole("f", 0, 0, 5); err == nil {
|
||||
t.Fatal("1.5 is not whole")
|
||||
}
|
||||
if _, err := a.Whole("n", 0, 4, 5); err == nil {
|
||||
t.Fatal("out of range")
|
||||
}
|
||||
if b, given, err := a.Bool("b"); !b || !given || err != nil {
|
||||
t.Fatal("bool")
|
||||
}
|
||||
if _, _, err := a.Bool("name"); err == nil {
|
||||
t.Fatal("text is not a bool")
|
||||
}
|
||||
if l, err := a.Strings("l"); err != nil || len(l) != 2 {
|
||||
t.Fatal(l, err)
|
||||
}
|
||||
if _, err := a.OneOf("name", "", "y", "z"); err == nil {
|
||||
t.Fatal("not one of")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPathIsKeptInsideTheHome(t *testing.T) {
|
||||
t.Setenv("MESH_OPERATOR_HOME", "/home/op")
|
||||
for in, want := range map[string]string{"~/a.png": "/home/op/a.png", "b/c": "/home/op/b/c", "/home/op/d": "/home/op/d", "~": "/home/op"} {
|
||||
if got, err := InHome(in); err != nil || got != want {
|
||||
t.Errorf("%s: %s %v", in, got, err)
|
||||
}
|
||||
}
|
||||
for _, out := range []string{"/etc/passwd", "~/../other", "../x"} {
|
||||
if _, err := InHome(out); err == nil {
|
||||
t.Errorf("%s was accepted", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropertiesAreParsed(t *testing.T) {
|
||||
p := ParseProperties("Active=yes\nState=active\nDisplay=\n")
|
||||
if p["Active"] != "yes" || p["State"] != "active" || p["Display"] != "" {
|
||||
t.Fatal(p)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"module": "adwaita",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager"
|
||||
],
|
||||
"tools": [
|
||||
"adwaita_appearance",
|
||||
"adwaita_cursor",
|
||||
"adwaita_icons",
|
||||
"adwaita_portal_check"
|
||||
],
|
||||
"environment": {
|
||||
"variables": {
|
||||
"GTK_THEME": "Adwaita:dark",
|
||||
"GTK2_RC_FILES": "/usr/share/themes/Adwaita-dark/gtk-2.0/gtkrc",
|
||||
"QT_QPA_PLATFORMTHEME": "qt6ct",
|
||||
"QT_STYLE_OVERRIDE": "Fusion",
|
||||
"QT_SELECT": "6",
|
||||
"XCURSOR_THEME": "Adwaita",
|
||||
"XCURSOR_SIZE": "24"
|
||||
}
|
||||
},
|
||||
"shell": [
|
||||
{
|
||||
"for": "xresources",
|
||||
"slot": "normal",
|
||||
"code": "! adwaita: the cursor, for X programs that take it from the resources.\nXcursor.theme: Adwaita\nXcursor.size: 24\n"
|
||||
},
|
||||
{
|
||||
"for": "xinitrc",
|
||||
"slot": "normal",
|
||||
"code": "# The appearance (module adwaita): GSettings is where the portal reads dark or light, and the portal is\n# the only way it reaches Electron, Chromium, Firefox and flatpaks. Set at every session start to the\n# module's default; adwaita_appearance switches it for a session.\ngsettings set org.gnome.desktop.interface color-scheme 'prefer-dark' || true\ngsettings set org.gnome.desktop.interface gtk-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface icon-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface cursor-theme 'Adwaita' || true\ngsettings set org.gnome.desktop.interface cursor-size 24 || true\ngsettings set org.gnome.desktop.interface font-name 'Inter 11' || true\ngsettings set org.gnome.desktop.interface monospace-font-name 'JetBrainsMono Nerd Font 11' || true\n"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "package-gnome-themes-extra",
|
||||
"type": "package",
|
||||
"package": "gnome-themes-extra"
|
||||
},
|
||||
{
|
||||
"id": "package-adwaita-icon-theme",
|
||||
"type": "package",
|
||||
"package": "adwaita-icon-theme"
|
||||
},
|
||||
{
|
||||
"id": "package-adwaita-cursors",
|
||||
"type": "package",
|
||||
"package": "adwaita-cursors"
|
||||
},
|
||||
{
|
||||
"id": "package-qt6ct",
|
||||
"type": "package",
|
||||
"package": "qt6ct"
|
||||
},
|
||||
{
|
||||
"id": "package-xdg-desktop-portal-gtk",
|
||||
"type": "package",
|
||||
"package": "xdg-desktop-portal-gtk"
|
||||
},
|
||||
{
|
||||
"id": "gtk3",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.config/gtk-3.0/settings.ini",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at\n# every push; adwaita_appearance switches dark and light for the running session.\n[Settings]\ngtk-theme-name=Adwaita\ngtk-icon-theme-name=Adwaita\ngtk-cursor-theme-name=Adwaita\ngtk-cursor-theme-size=24\ngtk-font-name=Inter 11\ngtk-application-prefer-dark-theme=1\n"
|
||||
},
|
||||
{
|
||||
"id": "gtk4",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.config/gtk-4.0/settings.ini",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208), for GTK 3 and GTK 4 alike. Replaced at\n# every push; adwaita_appearance switches dark and light for the running session.\n[Settings]\ngtk-theme-name=Adwaita\ngtk-icon-theme-name=Adwaita\ngtk-cursor-theme-name=Adwaita\ngtk-cursor-theme-size=24\ngtk-font-name=Inter 11\ngtk-application-prefer-dark-theme=1\n"
|
||||
},
|
||||
{
|
||||
"id": "qt6ct",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.config/qt6ct/qt6ct.conf",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "[Appearance]\ncolor_scheme_path=/usr/share/qt6ct/colors/darker.conf\ncustom_palette=true\nicon_theme=Adwaita\nstandard_dialogs=default\nstyle=Fusion\n\n[Fonts]\nfixed=\"JetBrainsMono Nerd Font,11,-1,5,50,0,0,0,0,0\"\ngeneral=\"Inter,11,-1,5,50,0,0,0,0,0\"\n\n[Interface]\nactivate_item_on_single_click=1\nbuttonbox_layout=0\ncursor_flash_time=1000\ndialog_buttons_have_icons=1\ndouble_click_interval=400\ngui_effects=@Invalid()\nkeyboard_scheme=2\nmenus_have_icons=true\nshow_shortcuts_in_context_menus=true\nstylesheets=@Invalid()\ntoolbutton_style=4\nunderline_shortcut=1\nwheel_scroll_lines=3\n\n[Troubleshooting]\nforce_raster_widgets=1\nignored_applications=@Invalid()\n"
|
||||
},
|
||||
{
|
||||
"id": "portals",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.config/xdg-desktop-portal/portals.conf",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208). Replaced at every push.\n#\n# Which portal backend answers each interface. i3 is not a desktop xdg-desktop-portal knows, so with\n# no preference it uses whichever backend happens to be installed: fine while gtk is the only one,\n# wrong the day another arrives as somebody else's dependency. Named instead. gtk also serves\n# org.freedesktop.appearance (dark or light) from GSettings, which the session's start sets.\n[preferred]\ndefault=gtk\n# Secrets for sandboxed programs come from the keyring's backend. Without this line no backend answers\n# the interface: gtk does not implement it, and gnome-keyring's names only GNOME as its desktop.\norg.freedesktop.impl.portal.Secret=gnome-keyring\n"
|
||||
},
|
||||
{
|
||||
"id": "cursor",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.icons/default/index.theme",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "# Written by the mesh (module adwaita, novox/hq ADR 0208): the default cursor theme, for programs that\n# read neither XCURSOR_THEME nor the X resources.\n[Icon Theme]\nName=Default\nInherits=Adwaita\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/adwaita-tools",
|
||||
"binary": "adwaita-tools",
|
||||
"loads": [
|
||||
"adwaita-tools"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
// The consumer's scheduled run: take the ACCESS token the mesh delivered and write it where the
|
||||
// Claude CLI reads it, access-token-only (novox/hq ADR 0050). The refresh token is never here to
|
||||
// strip — the manager holds it, and a holder's delivery has only ever been the access token.
|
||||
//
|
||||
// What the host delivers, per the manifest:
|
||||
// secrets.model-access -> a file holding the sealed-then-unsealed ACCESS token (the host opened it
|
||||
// with this node's private key; this process reads plaintext).
|
||||
// binds.model-access -> a JSON file of the non-secret facts the licence serves (which licence,
|
||||
// model, and — when the control plane carries them — grant expiry/scopes).
|
||||
//
|
||||
// Runs as `mesh-tools run` (no broker) on a schedule, so it is idempotent: same token in, same file
|
||||
// out.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { deliver, type DeliveredGrant } from "../credentials.js";
|
||||
import { readAccountUuid, check } from "../identity.js";
|
||||
|
||||
function required(name: string): string {
|
||||
const v = process.env[name];
|
||||
if (!v) throw new Error(`${name} is not set — the consumer runtime was deployed without it`);
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Read optional non-secret grant metadata (expiry, scopes, subscription) from the bound facts file. */
|
||||
function readBoundMeta(path: string | undefined): Partial<DeliveredGrant> {
|
||||
if (!path) return {};
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
|
||||
return {
|
||||
expiresAt: typeof raw.expiresAt === "number" ? raw.expiresAt : null,
|
||||
refreshTokenExpiresAt: typeof raw.refreshTokenExpiresAt === "number" ? raw.refreshTokenExpiresAt : null,
|
||||
scopes: Array.isArray(raw.scopes) ? (raw.scopes as string[]) : null,
|
||||
subscriptionType: typeof raw.subscriptionType === "string" ? raw.subscriptionType : null,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function main(): void {
|
||||
const accessToken = readFileSync(required("MESH_MODEL_ACCESS_SECRET_FILE"), "utf8").trim();
|
||||
if (!accessToken) {
|
||||
// Nothing was delivered — which reads exactly like a credential that never arrived, so it is
|
||||
// said rather than written as an empty file the CLI would take for a login it should not do.
|
||||
throw new Error("[anthropic-consumer] the delivered access token is empty; nothing was written");
|
||||
}
|
||||
|
||||
const meta = readBoundMeta(process.env.MESH_MODEL_ACCESS_BIND_FILE);
|
||||
const grant: DeliveredGrant = { accessToken, ...meta };
|
||||
|
||||
const target = process.env.MESH_CLAUDE_CREDENTIALS_FILE ?? `${homedir()}/.claude/.credentials.json`;
|
||||
deliver(target, grant);
|
||||
console.error(`[anthropic-consumer] wrote an access-token-only credential to ${target}`);
|
||||
|
||||
// The mis-binding guard, best-effort and fail-closed. The expected account uuid is not yet plumbed
|
||||
// (identity.ts TODO), so this reports what it can see rather than acting on it — it never delivers
|
||||
// to a wrong account because it never learns one to deliver to.
|
||||
const identityFile = process.env.MESH_CLAUDE_IDENTITY_FILE ?? `${homedir()}/.claude.json`;
|
||||
const found = readAccountUuid(identityFile);
|
||||
const expected = process.env.MESH_MODEL_ACCESS_ACCOUNT_UUID ?? null;
|
||||
const verdict = check(found, expected);
|
||||
if (verdict.state === "wrong-account") {
|
||||
throw new Error(
|
||||
`[anthropic-consumer] the CLI is logged in as ${verdict.found}, not the licensed ${verdict.expected}; refusing`,
|
||||
);
|
||||
}
|
||||
console.error(`[anthropic-consumer] identity check: ${verdict.state}`);
|
||||
}
|
||||
|
||||
function homedir(): string {
|
||||
return process.env.HOME ?? "/root";
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,82 +0,0 @@
|
||||
// Writing the access token where the Claude CLI reads it — the consumer half of model-access
|
||||
// (novox/hq ADR 0050). A node holds an ACCESS token and nothing else: it cannot rotate, so it is
|
||||
// never given a refresh token, and this enforces that on every write.
|
||||
//
|
||||
// The file shape and the strip are ported byte-exact from the mature implementation (see the port
|
||||
// map): `~/.claude/.credentials.json` → `{ claudeAiOauth: { accessToken, expiresAt,
|
||||
// refreshTokenExpiresAt?, scopes?, subscriptionType? } }`, and the refresh token is deleted, not
|
||||
// merely omitted, so a full grant left by an interactive login is stripped back to access-only.
|
||||
|
||||
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
/** The access-token-only grant the mesh delivered — what the manager submitted, minus the refresh. */
|
||||
export interface DeliveredGrant {
|
||||
readonly accessToken: string;
|
||||
readonly expiresAt?: number | null;
|
||||
readonly refreshTokenExpiresAt?: number | null;
|
||||
readonly scopes?: string[] | null;
|
||||
readonly subscriptionType?: string | null;
|
||||
}
|
||||
|
||||
interface ClaudeOauth {
|
||||
accessToken?: string;
|
||||
expiresAt?: number;
|
||||
refreshTokenExpiresAt?: number;
|
||||
scopes?: string[];
|
||||
subscriptionType?: string;
|
||||
refreshToken?: string;
|
||||
}
|
||||
|
||||
interface Credentials {
|
||||
claudeAiOauth?: ClaudeOauth;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** Read the existing credentials file, or an empty object if there is none or it is unreadable. */
|
||||
function readLocal(path: string): Credentials {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8")) as Credentials;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overlay the delivered grant onto whatever is on disk, then STRIP the refresh token — the node
|
||||
* carve-out. Returns the object to write, so the strip is testable without touching a file.
|
||||
*/
|
||||
export function applyGrant(local: Credentials, grant: DeliveredGrant): Credentials {
|
||||
const oauth = local.claudeAiOauth ?? {};
|
||||
const next: Credentials = {
|
||||
...local,
|
||||
claudeAiOauth: {
|
||||
...oauth,
|
||||
accessToken: grant.accessToken,
|
||||
...(grant.expiresAt != null ? { expiresAt: grant.expiresAt } : {}),
|
||||
...(grant.refreshTokenExpiresAt != null
|
||||
? { refreshTokenExpiresAt: grant.refreshTokenExpiresAt }
|
||||
: {}),
|
||||
...(grant.scopes ? { scopes: grant.scopes } : {}),
|
||||
...(grant.subscriptionType ? { subscriptionType: grant.subscriptionType } : {}),
|
||||
},
|
||||
};
|
||||
// A node NEVER holds a refresh token: delete it, so a full grant on disk is reduced to access-only.
|
||||
delete next.claudeAiOauth!.refreshToken;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Atomic write-then-rename at 0600 — a partial credentials file must never be read as a whole one. */
|
||||
export function writeCredentials(path: string, creds: Credentials): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(creds, null, 2), { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
|
||||
/** Read, overlay, strip, write — the whole consumer credential update, in one call. */
|
||||
export function deliver(path: string, grant: DeliveredGrant): Credentials {
|
||||
const next = applyGrant(readLocal(path), grant);
|
||||
writeCredentials(path, next);
|
||||
return next;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
// The mis-binding guard (novox/hq ADR 0050, port map §identity). Account identity is NOT in the
|
||||
// token or any API — it lives in a sibling CLI state file, `~/.claude.json` →
|
||||
// `oauthAccount.accountUuid`. The guard compares the account the CLI is actually logged in as to the
|
||||
// account the licence was recorded against, and FAILS CLOSED: an absent file or an unrecorded licence
|
||||
// account refuses rather than guesses, because delivering an access token to the wrong account is the
|
||||
// exact fault this exists to catch.
|
||||
//
|
||||
// **Partial first cut, FLAGGED.** Reading the sibling file is implemented; the licence's recorded
|
||||
// account uuid is not yet plumbed from the control plane to the consumer (the bound `model.json` does
|
||||
// not carry it today). So `check` returns `licence-not-adopted` when no expected uuid is supplied,
|
||||
// which is the fail-closed answer, and the wiring of the expected uuid is a TODO below.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export type IdentityVerdict =
|
||||
| { state: "verified"; accountUuid: string }
|
||||
| { state: "no-identity-file" }
|
||||
| { state: "licence-not-adopted" }
|
||||
| { state: "wrong-account"; found: string; expected: string };
|
||||
|
||||
interface ClaudeJson {
|
||||
oauthAccount?: { accountUuid?: string; emailAddress?: string; organizationUuid?: string };
|
||||
}
|
||||
|
||||
/** Read `oauthAccount.accountUuid` from `~/.claude.json`, or null if the file or field is absent. */
|
||||
export function readAccountUuid(path: string): string | null {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(path, "utf8")) as ClaudeJson;
|
||||
return raw.oauthAccount?.accountUuid ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare the CLI's logged-in account to the one the licence was recorded against. Pure over its
|
||||
* inputs so the fail-closed logic is tested without a filesystem.
|
||||
*
|
||||
* TODO(novox/hq ADR 0050, Phase C): plumb `expected` — the licence's recorded account uuid — from the
|
||||
* control plane into the consumer's bound `model.json`, then adopt-on-first-sight or refuse per the
|
||||
* port map's five states. Until then only the two safe verdicts are reachable: verified when an
|
||||
* expected uuid is provided and matches, refuse otherwise.
|
||||
*/
|
||||
export function check(found: string | null, expected: string | null): IdentityVerdict {
|
||||
if (found === null) return { state: "no-identity-file" };
|
||||
if (!expected) return { state: "licence-not-adopted" };
|
||||
if (found === expected) return { state: "verified", accountUuid: found };
|
||||
return { state: "wrong-account", found, expected };
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
{
|
||||
"module": "anthropic-consumer",
|
||||
"version": "1",
|
||||
"slug": "claude",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"requires": [
|
||||
"model-access"
|
||||
],
|
||||
"binds": {
|
||||
"model-access": "${dir:state}/model.json"
|
||||
},
|
||||
"secrets": {
|
||||
"model-access": "${dir:state}/access-token"
|
||||
},
|
||||
"emits": [
|
||||
"usage.session"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "claude-home",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/anthropic-consumer/claude",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "out",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "apply",
|
||||
"type": "process",
|
||||
"name": "anthropic-consumer-apply",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"apply/index.js"
|
||||
],
|
||||
"schedule": "*/5 * * * *",
|
||||
"env": {
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "${dir:state}/access-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "${dir:state}/model.json",
|
||||
"MESH_CLAUDE_CREDENTIALS_FILE": "${dir:state}/claude/.credentials.json",
|
||||
"MESH_CLAUDE_IDENTITY_FILE": "${dir:state}/claude/.claude.json"
|
||||
}
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"apply/index.js",
|
||||
"usage/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"usage/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLAUDE_PROJECTS_DIR": "${dir:state}/claude/projects",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "${dir:state}/out/session-usage.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-anthropic-consumer",
|
||||
"version": "0.1.0",
|
||||
"description": "anthropic-consumer — the consumer side of model-access (ADR 0050): writes the delivered access token to ~/.claude/.credentials.json (access-token-only) and reports session-grain usage from the CLI transcripts (ADR 0054).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { applyGrant, deliver } from "../credentials.ts";
|
||||
|
||||
test("applyGrant strips the refresh token a full grant on disk left behind", () => {
|
||||
const local = { claudeAiOauth: { accessToken: "at-old", refreshToken: "rt-must-not-survive" } };
|
||||
const next = applyGrant(local, { accessToken: "at-new", expiresAt: 123 });
|
||||
assert.equal(next.claudeAiOauth!.accessToken, "at-new");
|
||||
assert.equal(next.claudeAiOauth!.expiresAt, 123);
|
||||
assert.ok(!("refreshToken" in next.claudeAiOauth!), "a node held onto a refresh token");
|
||||
});
|
||||
|
||||
test("deliver writes the port-map shape, access-token-only, and never a refresh token", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "anthropic-consumer-"));
|
||||
const path = join(dir, ".credentials.json");
|
||||
// A prior interactive login left a full grant on disk.
|
||||
writeFileSync(path, JSON.stringify({ claudeAiOauth: { accessToken: "at-old", refreshToken: "rt-login" } }));
|
||||
|
||||
deliver(path, { accessToken: "at-delivered", expiresAt: 999, subscriptionType: "max" });
|
||||
|
||||
const raw = readFileSync(path, "utf8");
|
||||
const creds = JSON.parse(raw);
|
||||
assert.equal(creds.claudeAiOauth.accessToken, "at-delivered");
|
||||
assert.equal(creds.claudeAiOauth.expiresAt, 999);
|
||||
assert.equal(creds.claudeAiOauth.subscriptionType, "max");
|
||||
assert.doesNotMatch(raw, /rt-login/, "the refresh token is still on disk");
|
||||
assert.ok(!("refreshToken" in creds.claudeAiOauth));
|
||||
});
|
||||
@@ -1,48 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { foldTranscript } from "../transcript.ts";
|
||||
|
||||
// A captured-shape transcript: two assistant turns and a user line, exactly the fields the port map
|
||||
// names. Not imagined — the field names match the mature implementation's parse.
|
||||
const TRANSCRIPT = [
|
||||
JSON.stringify({ type: "user", timestamp: "2026-01-01T00:00:00Z", cwd: "/work/app", gitBranch: "main" }),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
timestamp: "2026-01-01T00:00:01Z",
|
||||
costUSD: 0.01,
|
||||
message: {
|
||||
model: "claude-opus-4-8",
|
||||
usage: { input_tokens: 100, cache_creation_input_tokens: 20, cache_read_input_tokens: 5, output_tokens: 40 },
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
type: "assistant",
|
||||
timestamp: "2026-01-01T00:00:02Z",
|
||||
costUSD: 0.02,
|
||||
message: { model: "claude-opus-4-8", usage: { input_tokens: 200, output_tokens: 60 } },
|
||||
}),
|
||||
"", // a half-written trailing line is ordinary and must not be fatal.
|
||||
].join("\n");
|
||||
|
||||
test("a transcript sums per-session token counts, cost, and metadata", () => {
|
||||
const s = foldTranscript("session-abc", TRANSCRIPT);
|
||||
assert.equal(s.sessionId, "session-abc");
|
||||
assert.equal(s.turns, 2);
|
||||
assert.equal(s.inputTokens, 300);
|
||||
assert.equal(s.cacheCreationTokens, 20);
|
||||
assert.equal(s.cacheReadTokens, 5);
|
||||
assert.equal(s.outputTokens, 100);
|
||||
assert.equal(Math.round(s.costUSD * 100) / 100, 0.03);
|
||||
assert.equal(s.model, "claude-opus-4-8");
|
||||
assert.equal(s.gitBranch, "main");
|
||||
assert.equal(s.cwd, "/work/app");
|
||||
assert.equal(s.startedAt, "2026-01-01T00:00:00Z");
|
||||
assert.equal(s.lastActive, "2026-01-01T00:00:02Z");
|
||||
});
|
||||
|
||||
test("a malformed line is skipped, not fatal", () => {
|
||||
const s = foldTranscript("s", 'not json\n{"type":"assistant","message":{"usage":{"output_tokens":7}}}');
|
||||
assert.equal(s.outputTokens, 7);
|
||||
assert.equal(s.turns, 1);
|
||||
});
|
||||
@@ -1,113 +0,0 @@
|
||||
// Session-grain usage from the CLI's own transcripts (novox/hq ADR 0054). The mature implementation
|
||||
// reads `~/.claude/projects/<projDir>/<sessionId>.jsonl` and sums the token counts each assistant
|
||||
// message reports; this ports the token extraction and DROPS the per-message account-attribution
|
||||
// timeline — the nox (node,module) session has a fixed licence binding (port map "don't-map" #3), so
|
||||
// there is nothing to attribute per message.
|
||||
//
|
||||
// The fields are ported from the port map: assistant lines carry
|
||||
// `message.usage.{input_tokens,cache_creation_input_tokens,cache_read_input_tokens,output_tokens}`,
|
||||
// `costUSD`, `message.model`, `timestamp`; user lines carry `cwd`, `gitBranch`.
|
||||
|
||||
import { createInterface } from "node:readline";
|
||||
import { createReadStream } from "node:fs";
|
||||
|
||||
/** One session's totals — the session-grain usage row ADR 0054 fixes. */
|
||||
export interface SessionUsage {
|
||||
sessionId: string;
|
||||
model: string | null;
|
||||
gitBranch: string | null;
|
||||
cwd: string | null;
|
||||
turns: number;
|
||||
inputTokens: number;
|
||||
cacheCreationTokens: number;
|
||||
cacheReadTokens: number;
|
||||
outputTokens: number;
|
||||
costUSD: number;
|
||||
startedAt: string | null;
|
||||
lastActive: string | null;
|
||||
}
|
||||
|
||||
interface Line {
|
||||
type?: string;
|
||||
timestamp?: string;
|
||||
cwd?: string;
|
||||
gitBranch?: string;
|
||||
costUSD?: number;
|
||||
message?: {
|
||||
model?: string;
|
||||
usage?: {
|
||||
input_tokens?: number;
|
||||
cache_creation_input_tokens?: number;
|
||||
cache_read_input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function empty(sessionId: string): SessionUsage {
|
||||
return {
|
||||
sessionId,
|
||||
model: null,
|
||||
gitBranch: null,
|
||||
cwd: null,
|
||||
turns: 0,
|
||||
inputTokens: 0,
|
||||
cacheCreationTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
costUSD: 0,
|
||||
startedAt: null,
|
||||
lastActive: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Fold one transcript line into a session's running totals. Pure, so it is tested on fixtures. */
|
||||
export function foldLine(acc: SessionUsage, raw: string): SessionUsage {
|
||||
const line = parse(raw);
|
||||
if (!line) return acc;
|
||||
|
||||
if (line.timestamp) {
|
||||
if (!acc.startedAt || line.timestamp < acc.startedAt) acc.startedAt = line.timestamp;
|
||||
if (!acc.lastActive || line.timestamp > acc.lastActive) acc.lastActive = line.timestamp;
|
||||
}
|
||||
if (line.type === "user") {
|
||||
if (line.cwd) acc.cwd = line.cwd;
|
||||
if (line.gitBranch) acc.gitBranch = line.gitBranch;
|
||||
}
|
||||
if (line.type === "assistant") {
|
||||
acc.turns += 1;
|
||||
const u = line.message?.usage ?? {};
|
||||
acc.inputTokens += u.input_tokens ?? 0;
|
||||
acc.cacheCreationTokens += u.cache_creation_input_tokens ?? 0;
|
||||
acc.cacheReadTokens += u.cache_read_input_tokens ?? 0;
|
||||
acc.outputTokens += u.output_tokens ?? 0;
|
||||
acc.costUSD += line.costUSD ?? 0;
|
||||
if (!acc.model && line.message?.model) acc.model = line.message.model;
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
function parse(raw: string): Line | null {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return null;
|
||||
try {
|
||||
return JSON.parse(trimmed) as Line;
|
||||
} catch {
|
||||
// A malformed line is skipped, never fatal: a transcript is an append-only log the CLI owns, and
|
||||
// a half-written last line is ordinary.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sum a whole transcript string into one session's usage — the tested core of the streaming read. */
|
||||
export function foldTranscript(sessionId: string, text: string): SessionUsage {
|
||||
return text.split("\n").reduce(foldLine, empty(sessionId));
|
||||
}
|
||||
|
||||
/** Stream one `<sessionId>.jsonl` file line by line, so a large transcript never loads whole. */
|
||||
export async function readSessionFile(path: string, sessionId: string): Promise<SessionUsage> {
|
||||
const acc = empty(sessionId);
|
||||
const rl = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
|
||||
for await (const line of rl) foldLine(acc, line);
|
||||
return acc;
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"credentials.ts",
|
||||
"transcript.ts",
|
||||
"identity.ts",
|
||||
"apply/index.ts",
|
||||
"usage/index.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
// Session-grain usage emission (novox/hq ADR 0054). On a schedule, read every transcript under
|
||||
// `~/.claude/projects/*/<sessionId>.jsonl`, sum its tokens, and emit one session-grain usage event
|
||||
// per session. The consumer IS the (node,module) session's fixed binding, so no per-message account
|
||||
// attribution is done — just the totals (port map "don't-map" #3).
|
||||
//
|
||||
// Runs in the node's runtime (novox/hq ADR 0198), every five minutes, so events are emitted through
|
||||
// the runtime as this module; the totals are also written to a file so the reading is observable
|
||||
// without one.
|
||||
|
||||
import { readdirSync, statSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
|
||||
import { readSessionFile, type SessionUsage } from "../transcript.js";
|
||||
|
||||
/** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local
|
||||
* to the producer (the normalisation lives in the adapter), so nothing here couples to the SDK. */
|
||||
interface UsageRow {
|
||||
licence: string;
|
||||
consumer: string;
|
||||
period: string;
|
||||
metric: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** The licence this session's usage is charged to. The model-access binding names it; failing that,
|
||||
* the deployed env; failing that, "unknown" — a reading is never dropped for want of a licence. */
|
||||
function boundLicence(): string {
|
||||
const bindFile = process.env.MESH_MODEL_ACCESS_BIND_FILE;
|
||||
if (bindFile) {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(bindFile, "utf8")) as { licence?: unknown };
|
||||
if (typeof raw.licence === "string" && raw.licence) return raw.licence;
|
||||
} catch {
|
||||
// A missing or unreadable bind file is not fatal — fall through to the env, then to "unknown".
|
||||
}
|
||||
}
|
||||
return process.env.MESH_ANTHROPIC_LICENCE || "unknown";
|
||||
}
|
||||
|
||||
/** Normalise one session reading into ADR 0054 rows: one row per metric, a row omitted when its
|
||||
* number is not finite. `consumer` is node/module/session — the session grain. */
|
||||
function sessionRows(licence: string, node: string, module: string, r: SessionUsage): UsageRow[] {
|
||||
const consumer = `${node}/${module}/${r.sessionId}`;
|
||||
const rows: UsageRow[] = [];
|
||||
const add = (metric: string, value: number): void => {
|
||||
if (Number.isFinite(value)) rows.push({ licence, consumer, period: "session", metric, value });
|
||||
};
|
||||
add("input_tokens", r.inputTokens);
|
||||
add("output_tokens", r.outputTokens);
|
||||
add("cache_creation_tokens", r.cacheCreationTokens);
|
||||
add("cache_read_tokens", r.cacheReadTokens);
|
||||
add("cost_usd", r.costUSD);
|
||||
return rows;
|
||||
}
|
||||
|
||||
function projectsDir(): string {
|
||||
return process.env.MESH_CLAUDE_PROJECTS_DIR ?? `${process.env.HOME ?? "/root"}/.claude/projects`;
|
||||
}
|
||||
|
||||
/** Every `<sessionId>.jsonl` under the projects tree, with the project directory it sits in. */
|
||||
function transcripts(root: string): { path: string; sessionId: string }[] {
|
||||
const found: { path: string; sessionId: string }[] = [];
|
||||
let projects: string[];
|
||||
try {
|
||||
projects = readdirSync(root);
|
||||
} catch {
|
||||
return found; // no projects yet is not a failure — there is simply nothing to report.
|
||||
}
|
||||
for (const proj of projects) {
|
||||
const dir = join(root, proj);
|
||||
let entries: string[];
|
||||
try {
|
||||
if (!statSync(dir).isDirectory()) continue;
|
||||
entries = readdirSync(dir);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
for (const file of entries) {
|
||||
if (!file.endsWith(".jsonl")) continue;
|
||||
found.push({ path: join(dir, file), sessionId: file.replace(/\.jsonl$/, "") });
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const module = process.env.MESH_MODULE ?? "anthropic-consumer";
|
||||
const node = process.env.MESH_NODE ?? "unknown";
|
||||
|
||||
const readings: SessionUsage[] = [];
|
||||
for (const t of transcripts(projectsDir())) {
|
||||
try {
|
||||
readings.push(await readSessionFile(t.path, t.sessionId));
|
||||
} catch (err) {
|
||||
console.error(`[anthropic-consumer] could not read ${t.path}: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Emit ADR-0054 rows, not a vendor-shaped body: the consumer of module.*.usage.* is the
|
||||
// vendor-neutral model-usage store, so the session→row normalisation is done HERE. The full
|
||||
// SessionUsage rides as `raw`, so model, branch, cwd and timestamps are not lost.
|
||||
const licence = boundLicence();
|
||||
for (const r of readings) {
|
||||
await emitUsage({ rows: sessionRows(licence, node, module, r), raw: r });
|
||||
}
|
||||
|
||||
if (process.env.MESH_ANTHROPIC_USAGE_OUT) {
|
||||
atomicWrite(process.env.MESH_ANTHROPIC_USAGE_OUT, JSON.stringify(readings, null, 2));
|
||||
}
|
||||
console.error(`[anthropic-consumer] reported ${readings.length} session(s)`);
|
||||
}
|
||||
|
||||
function atomicWrite(path: string, content: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.tmp`;
|
||||
writeFileSync(tmp, content, { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
|
||||
/** Emit best-effort through the runtime: a reading that could not be announced is still in the file. */
|
||||
async function emitUsage(body: Record<string, unknown>): Promise<void> {
|
||||
try {
|
||||
await emit("usage.session", body);
|
||||
} catch (err) {
|
||||
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// The cadence the scheduled container had: once at start, then every five minutes. Not awaited, so the
|
||||
// runtime's handshake is answered while a long first reading is still under way.
|
||||
const EVERY_MS = 5 * 60 * 1000;
|
||||
const tick = (): void => {
|
||||
void main().catch((err) => console.error(`[anthropic-consumer] usage reading failed: ${err}`));
|
||||
};
|
||||
tick();
|
||||
setInterval(tick, EVERY_MS);
|
||||
@@ -1,35 +0,0 @@
|
||||
// Adoption: the ONE time an operator's refresh token enters the mesh, and it enters already sealed.
|
||||
//
|
||||
// The refresh token is read here, on the MANAGER NODE, sealed to that node's PUBLIC sealing key, and
|
||||
// only the sealed box leaves this process (novox/hq ADR 0050). The control plane stores that box via
|
||||
// `licence set-grant` without ever seeing the refresh token in the clear — the same bound every
|
||||
// delivery keeps. This is the counterpart to `refresh/index.js`: adoption seals the first box, refresh
|
||||
// re-seals a rotated one; both use the very anonymous box (`crypto_box_seal`) the mesh seals every
|
||||
// credential with, so the HOST unseals the stored box to mount the cleartext back — this module is
|
||||
// never given a private key and opens nothing.
|
||||
//
|
||||
// MESH_ANTHROPIC_ADOPT_TOKEN_FILE the operator's refresh token, read once and never written out
|
||||
// MESH_MODEL_ACCESS_BIND_FILE the manager holder's bound facts, carrying manager_public_key
|
||||
// MESH_ANTHROPIC_GRANT_OUT where the sealed box is written, for `licence set-grant`
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { seal } from "../sealedbox.js";
|
||||
import { managerPublicKey, writeSealedGrant } from "../grantfile.js";
|
||||
|
||||
function required(name: string): string {
|
||||
const v = process.env[name];
|
||||
if (!v) throw new Error(`${name} is not set — adoption needs it`);
|
||||
return v;
|
||||
}
|
||||
|
||||
const refreshToken = readFileSync(required("MESH_ANTHROPIC_ADOPT_TOKEN_FILE"), "utf8").trim();
|
||||
if (!refreshToken) throw new Error("[anthropic-manager] there is no refresh token to adopt");
|
||||
|
||||
// The node's PUBLIC sealing key, delivered by the mesh in the manager holder's bound facts. Public,
|
||||
// so it is safe to hand a module; the private half stays with the host, which is what opens the box.
|
||||
const nodePub = managerPublicKey(required("MESH_MODEL_ACCESS_BIND_FILE"));
|
||||
|
||||
const sealed = seal(new Uint8Array(Buffer.from(refreshToken, "utf8")), nodePub);
|
||||
writeSealedGrant(required("MESH_ANTHROPIC_GRANT_OUT"), sealed, nodePub);
|
||||
console.error("[anthropic-manager] sealed the refresh token to this node's key; only the host opens it");
|
||||
@@ -1,135 +0,0 @@
|
||||
// The only file that talks to Anthropic — the vendor half of the refreshable-grant adapter
|
||||
// (novox/hq ADR 0050). Isolated exactly as cloudflare-dns isolates its registrar call, so the
|
||||
// vendor is swappable and the one place a token endpoint is reached is auditable.
|
||||
//
|
||||
// Two endpoints, and they are different hosts (port-map "don't-map" #1): the TOKEN host mints a new
|
||||
// access token from the refresh token; the USAGE host reports utilisation against an access token.
|
||||
|
||||
/** The token endpoint, overridable so the lab can point the whole flow at a stub without a vendor. */
|
||||
export function tokenEndpoint(env = process.env): string {
|
||||
return env.MESH_ANTHROPIC_TOKEN_ENDPOINT ?? "https://platform.claude.com/v1/oauth/token";
|
||||
}
|
||||
|
||||
/** The usage endpoint, likewise overridable for the lab. */
|
||||
export function usageEndpoint(env = process.env): string {
|
||||
return env.MESH_ANTHROPIC_USAGE_ENDPOINT ?? "https://api.anthropic.com/api/oauth/usage";
|
||||
}
|
||||
|
||||
// The OAuth client id is a hard-won constant, ported byte-exact from the mature implementation: a
|
||||
// metadata URL in its place yields 400. It is not a secret (it identifies the public Claude Code
|
||||
// client), so it lives in code.
|
||||
const CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
|
||||
|
||||
/** The vendor's token response, snake_case as the wire has it. */
|
||||
export interface RefreshedGrant {
|
||||
readonly access_token?: string;
|
||||
readonly refresh_token?: string;
|
||||
readonly expires_in?: number;
|
||||
readonly refresh_token_expires_in?: number;
|
||||
readonly scopes?: string[];
|
||||
readonly subscription_type?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange a refresh token for a fresh grant. Returns null on any non-ok response, surfacing the
|
||||
* OAuth error body (invalid_grant/invalid_client/…) — the difference between "the token is dead" and
|
||||
* "the endpoint was unreachable", which a bare status hides.
|
||||
*/
|
||||
export async function refreshGrant(
|
||||
refreshToken: string,
|
||||
env = process.env,
|
||||
): Promise<RefreshedGrant | null> {
|
||||
const resp = await fetch(tokenEndpoint(env), {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: refreshToken,
|
||||
client_id: CLIENT_ID,
|
||||
}),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const body = await resp.text().catch(() => "<unreadable>");
|
||||
console.error(
|
||||
`[anthropic-manager] token refresh failed: ${resp.status} ${resp.statusText} — ${body.slice(0, 400)}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return (await resp.json()) as RefreshedGrant;
|
||||
}
|
||||
|
||||
/** The vendor's usage response — utilisation percentages against several windows. */
|
||||
export interface UsageLimits {
|
||||
readonly five_hour?: { utilization: number; resets_at?: string };
|
||||
readonly seven_day?: { utilization: number; resets_at?: string };
|
||||
readonly seven_day_sonnet?: { utilization: number; resets_at?: string };
|
||||
readonly seven_day_opus?: { utilization: number; resets_at?: string };
|
||||
readonly extra_usage?: { utilization: number };
|
||||
readonly [key: string]: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read utilisation for an access token. Never refreshes here (a 401 is just reported): a second
|
||||
* refresh source racing the first is the fault the mature implementation warns against.
|
||||
*/
|
||||
export async function readUsage(accessToken: string, env = process.env): Promise<UsageLimits | null> {
|
||||
const resp = await fetch(usageEndpoint(env), {
|
||||
headers: { authorization: `Bearer ${accessToken}` },
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const body = await resp.text().catch(() => "");
|
||||
console.error(`[anthropic-manager] usage endpoint returned ${resp.status}: ${body.slice(0, 200)}`);
|
||||
return null;
|
||||
}
|
||||
return (await resp.json()) as UsageLimits;
|
||||
}
|
||||
|
||||
/** The licence-grain reading ADR 0054 fixes, flattened from the vendor's windows. */
|
||||
export interface UsageReading {
|
||||
readonly sessionPct: number | null;
|
||||
readonly sessionResetsAt: string | null;
|
||||
readonly weeklyPct: number | null;
|
||||
readonly sonnetPct: number | null;
|
||||
readonly extraPct: number | null;
|
||||
readonly raw: UsageLimits;
|
||||
}
|
||||
|
||||
export function flattenUsage(u: UsageLimits): UsageReading {
|
||||
return {
|
||||
sessionPct: u.five_hour?.utilization ?? null,
|
||||
sessionResetsAt: u.five_hour?.resets_at ?? null,
|
||||
weeklyPct: u.seven_day?.utilization ?? null,
|
||||
sonnetPct: u.seven_day_sonnet?.utilization ?? null,
|
||||
extraPct: u.extra_usage?.utilization ?? null,
|
||||
raw: u,
|
||||
};
|
||||
}
|
||||
|
||||
/** The access-token-only grant a holder is delivered — the port-map credential-file shape's fields. */
|
||||
export interface AccessGrant {
|
||||
readonly accessToken: string;
|
||||
readonly expiresAt: number | null;
|
||||
readonly refreshTokenExpiresAt: number | null;
|
||||
readonly scopes: string[] | null;
|
||||
readonly subscriptionType: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a vendor refresh into what the manager submits: the access-token-only grant for holders, and
|
||||
* the rotated refresh token if the vendor sent one. Never clobbers a good grant from an empty
|
||||
* response — no access_token means the caller keeps what it had.
|
||||
*/
|
||||
export function grantFromRefresh(r: RefreshedGrant, nowMs: number): { access: AccessGrant; rotatedRefresh: string | null } | null {
|
||||
if (!r.access_token) return null;
|
||||
return {
|
||||
access: {
|
||||
accessToken: r.access_token,
|
||||
expiresAt: typeof r.expires_in === "number" ? nowMs + r.expires_in * 1000 : null,
|
||||
refreshTokenExpiresAt:
|
||||
typeof r.refresh_token_expires_in === "number" ? nowMs + r.refresh_token_expires_in * 1000 : null,
|
||||
scopes: r.scopes ?? null,
|
||||
subscriptionType: r.subscription_type ?? null,
|
||||
},
|
||||
rotatedRefresh: r.refresh_token ?? null,
|
||||
};
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Reading the manager node's PUBLIC sealing key out of the bound facts the mesh delivers, and
|
||||
// writing a sealed refresh token in the wire shape mesh-controller reads.
|
||||
//
|
||||
// **The public key is delivered, not derived.** The manager module holds no node key of its own
|
||||
// (novox/hq ADR 0050) — it is deliberately never given one. To seal a refresh token to this node it
|
||||
// needs the node's PUBLIC sealing key, and mesh-controller puts that in the manager holder's bound facts
|
||||
// (`serves.manager_public_key`), safe to disclose because it is public. Both adoption and every
|
||||
// rotation read it from there.
|
||||
|
||||
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
/** The manager node's public sealing key, from the bound facts file the mesh delivers. */
|
||||
export function managerPublicKey(boundFile: string): string {
|
||||
const raw = JSON.parse(readFileSync(boundFile, "utf8")) as { serves?: Record<string, unknown> };
|
||||
const key = raw.serves?.["manager_public_key"];
|
||||
if (typeof key !== "string" || key === "") {
|
||||
throw new Error(
|
||||
"the bound facts carry no manager_public_key — this node is not the licence's manager, or " +
|
||||
"the manager holder has not been delivered yet",
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
/** Write a sealed refresh token in the {sealed, manager_key} wire shape mesh-controller reads. */
|
||||
export function writeSealedGrant(path: string, sealed: string, managerKey: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.tmp`;
|
||||
writeFileSync(tmp, JSON.stringify({ sealed, manager_key: managerKey }), { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
{
|
||||
"module": "anthropic-manager",
|
||||
"version": "1",
|
||||
"slug": "anthmgr",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"requires": [
|
||||
"model-access"
|
||||
],
|
||||
"binds": {
|
||||
"model-access": "${dir:mesh-state}/model.json"
|
||||
},
|
||||
"secrets": {
|
||||
"model-access": "${dir:mesh-state}/refresh-token"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"emits": [
|
||||
"usage.read"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "out",
|
||||
"type": "directory",
|
||||
"path": "${dir:mesh-state}/out",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "refresh",
|
||||
"type": "container",
|
||||
"name": "mesh-anthropic-manager-refresh",
|
||||
"image": "mesh-runtime-anthropic-manager@sha256:0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"network": "host",
|
||||
"schedule": "*/5 * * * *",
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/anthropic-manager/dist/refresh/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_ANTHROPIC_LICENCE": "personal",
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "/run/state/refresh-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "/run/state/model.json",
|
||||
"MESH_ANTHROPIC_ACCESS_OUT": "/run/state/out/access-token",
|
||||
"MESH_ANTHROPIC_GRANT_OUT": "/run/state/out/grant.json",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "/run/state/out/usage.json",
|
||||
"MESH_TOOLS_MAIN": "/app/dist/main.js"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-anthropic-manager",
|
||||
"version": "0.1.0",
|
||||
"description": "anthropic-manager — the manager side of the model-access refreshable-grant (ADR 0050): opens the refresh token on the manager node alone, refreshes it against Anthropic's OAuth endpoint, and submits back only the access token and the re-sealed refresh envelope.",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0",
|
||||
"tweetnacl": "^1.0.3",
|
||||
"tweetnacl-sealedbox-js": "^1.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
// The manager's scheduled run (novox/hq ADR 0050/0053). It is the whole of the carve-out in one
|
||||
// place, and it runs on the MANAGER NODE, never in the control plane:
|
||||
//
|
||||
// 1. read the refresh token as CLEARTEXT — the host unsealed the stored box with THIS node's private
|
||||
// key and mounted it at the module's bound secret path, exactly as it delivers any credential.
|
||||
// This module holds no node key and opens nothing itself;
|
||||
// 2. call the vendor's OAuth token endpoint to mint a fresh access token (and maybe a rotated
|
||||
// refresh token);
|
||||
// 3. if the vendor rotated the refresh token, SEAL the new one to this node's PUBLIC sealing key
|
||||
// (delivered in the bound facts) with the same anonymous box the mesh seals every credential with;
|
||||
// 4. hand the control plane back ONLY the access token in the clear + the opaque re-sealed box —
|
||||
// never the refresh token — which it seals per consumer holder and stores;
|
||||
// 5. poll usage with the fresh access token and record the licence-grain reading.
|
||||
//
|
||||
// mesh-controller receives the products of steps 3–4 through `licence submit-refresh` (access token +
|
||||
// sealed box). The refresh token never leaves this process except as ciphertext, and it never had to
|
||||
// be opened here at all — the host did that.
|
||||
//
|
||||
// This runs as `mesh-tools run`, which connects no broker, so the outputs are written to files the
|
||||
// host mounts; the submit itself (the transport to mesh-controller) is done by the caller invoking
|
||||
// `mesh-controller licence submit-refresh`. In the lab that caller is the scenario; in production it is
|
||||
// an authenticated call the manager node makes. The transport is the one part stubbed here — FLAGGED
|
||||
// — because a cross-node authenticated command surface is out of this module's scope.
|
||||
|
||||
import { readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import { readEnv } from "@novox/mesh-sdk/primitives";
|
||||
|
||||
import { seal } from "../sealedbox.js";
|
||||
import { managerPublicKey, writeSealedGrant } from "../grantfile.js";
|
||||
import { refreshGrant, grantFromRefresh, readUsage, flattenUsage, type UsageReading } from "../client.js";
|
||||
|
||||
/** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local
|
||||
* to the producer (the normalisation lives in the adapter), so nothing here couples to the SDK. */
|
||||
interface UsageRow {
|
||||
licence: string;
|
||||
consumer: string;
|
||||
period: string;
|
||||
metric: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** Normalise a licence-grain reading into ADR 0054 rows: one utilization row per window, a row
|
||||
* omitted when its percentage is absent. `consumer` is the holding module — the licence grain. */
|
||||
function licenceRows(licence: string, consumer: string, reading: UsageReading): UsageRow[] {
|
||||
const rows: UsageRow[] = [];
|
||||
const add = (period: string, pct: number | null): void => {
|
||||
if (pct !== null && pct !== undefined && Number.isFinite(pct)) {
|
||||
rows.push({ licence, consumer, period, metric: "utilization", value: pct });
|
||||
}
|
||||
};
|
||||
add("5h", reading.sessionPct);
|
||||
add("7d", reading.weeklyPct);
|
||||
add("extra", reading.extraPct);
|
||||
return rows;
|
||||
}
|
||||
|
||||
function required(name: string): string {
|
||||
const v = process.env[name];
|
||||
if (!v) throw new Error(`${name} is not set — the manager runtime was deployed without it`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function atomicWrite(path: string, content: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.tmp`;
|
||||
writeFileSync(tmp, content, { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const licence = process.env.MESH_ANTHROPIC_LICENCE ?? "unknown";
|
||||
|
||||
// Step 1: the refresh token as cleartext, unsealed and mounted by the HOST. No open here.
|
||||
const refreshToken = readFileSync(required("MESH_MODEL_ACCESS_SECRET_FILE"), "utf8").trim();
|
||||
if (!refreshToken) {
|
||||
// Nothing was delivered — the manager has not adopted a refresh token yet, or the push has not
|
||||
// landed. Said rather than treated as an empty token the vendor would reject obscurely.
|
||||
throw new Error("[anthropic-manager] no refresh token was delivered; adopt one first");
|
||||
}
|
||||
|
||||
// The node's PUBLIC sealing key, to re-seal a rotated refresh token. Public, delivered in the facts.
|
||||
const nodePub = managerPublicKey(required("MESH_MODEL_ACCESS_BIND_FILE"));
|
||||
|
||||
// Step 2: the vendor call.
|
||||
const refreshed = await refreshGrant(refreshToken);
|
||||
if (!refreshed) {
|
||||
// A dead endpoint or a rejected token: nothing to publish, and we do not clobber a good grant.
|
||||
throw new Error(`[anthropic-manager] the refresh of ${licence} produced no grant`);
|
||||
}
|
||||
const grant = grantFromRefresh(refreshed, Date.now());
|
||||
if (!grant) {
|
||||
throw new Error(`[anthropic-manager] the refresh of ${licence} returned no access token`);
|
||||
}
|
||||
|
||||
// Step 3: re-seal the rotated refresh token, if the vendor rotated it. Nothing to store otherwise.
|
||||
if (grant.rotatedRefresh) {
|
||||
const sealed = seal(new Uint8Array(Buffer.from(grant.rotatedRefresh, "utf8")), nodePub);
|
||||
if (process.env.MESH_ANTHROPIC_GRANT_OUT) {
|
||||
writeSealedGrant(process.env.MESH_ANTHROPIC_GRANT_OUT, sealed, nodePub);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: the access token in the clear, for the control plane to seal per consumer holder. This is
|
||||
// all it ever receives that is not ciphertext.
|
||||
atomicWrite(required("MESH_ANTHROPIC_ACCESS_OUT"), grant.access.accessToken);
|
||||
|
||||
console.error(
|
||||
`[anthropic-manager] refreshed ${licence}: access token minted` +
|
||||
(grant.rotatedRefresh ? ", refresh token rotated and re-sealed" : ", refresh token unchanged"),
|
||||
);
|
||||
|
||||
// Step 5: licence-grain usage, best-effort — a usage read failing must not fail the refresh.
|
||||
try {
|
||||
const usage = await readUsage(grant.access.accessToken);
|
||||
if (usage) {
|
||||
const reading = flattenUsage(usage);
|
||||
if (process.env.MESH_ANTHROPIC_USAGE_OUT) {
|
||||
atomicWrite(
|
||||
process.env.MESH_ANTHROPIC_USAGE_OUT,
|
||||
JSON.stringify({ licence, grain: "licence", ...reading }),
|
||||
);
|
||||
}
|
||||
// Emit ADR-0054 rows, not a vendor-shaped body: the consumer of module.*.usage.* is the
|
||||
// vendor-neutral model-usage store, so the normalisation is done HERE. The node names the
|
||||
// holding module; with MESH_NODE unset the consumer is the module alone.
|
||||
const node = readEnv("MESH_NODE", "");
|
||||
const consumer = node ? `${node}/anthropic-manager` : "anthropic-manager";
|
||||
await emitUsage({ rows: licenceRows(licence, consumer, reading), raw: usage });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[anthropic-manager] usage poll for ${licence} failed: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a usage event best-effort by shelling out to the sibling mesh-tools `emit` primitive, which
|
||||
* is the one path that wires a broker from a run-once/scheduled step (which itself connects none).
|
||||
* A broker hiccup must never fail a refresh that already happened.
|
||||
*/
|
||||
async function emitUsage(body: Record<string, unknown>): Promise<void> {
|
||||
const main = process.env.MESH_TOOLS_MAIN ?? "/app/dist/main.js";
|
||||
const { spawn } = await import("node:child_process");
|
||||
await new Promise<void>((resolve) => {
|
||||
const child = spawn(process.execPath, [main, "emit", "usage.read", JSON.stringify(body)], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
child.on("exit", () => resolve());
|
||||
child.on("error", (err) => {
|
||||
console.error(`[anthropic-manager] could not emit usage: ${err}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -1,57 +0,0 @@
|
||||
// A NaCl `crypto_box_seal`, byte-compatible with Go's `box.SealAnonymous`, over the audited
|
||||
// `tweetnacl-sealedbox-js`.
|
||||
//
|
||||
// **Why this file exists, and why it is exactly this.** novox/hq ADR 0050's refreshable-grant
|
||||
// carve-out delivers the refresh token to the manager module the way the mesh delivers every other
|
||||
// credential: sealed to the node's key, and unsealed by the *host* — never by the module. The host
|
||||
// unseals with Go's `golang.org/x/crypto/nacl/box.OpenAnonymous` (mesh-host
|
||||
// internal/identity/sealing.go), and mesh-controller seals with `box.SealAnonymous`
|
||||
// (mesh-controller internal/secrets/seal.go). Both are NaCl `crypto_box_seal`:
|
||||
//
|
||||
// sealed = ephemeralPub(32) ‖ crypto_box(msg, nonce, recipientPub, ephemeralSecret)
|
||||
// nonce = blake2b( ephemeralPub ‖ recipientPub , 24 bytes, unkeyed )
|
||||
//
|
||||
// When the vendor rotates the refresh token, the manager module must store the new one back the
|
||||
// same way — sealed to the manager node's own sealing key — so mesh-controller keeps it without ever
|
||||
// reading it and the host can later unseal it to deliver the cleartext again. That reseal happens
|
||||
// here, on the manager node, in TypeScript. It therefore has to produce the *identical* byte format
|
||||
// Go's `Open` accepts, or the host would refuse the delivery.
|
||||
//
|
||||
// **The crypto is not ours.** `tweetnacl-sealedbox-js` is `crypto_box_seal` built on the audited
|
||||
// TweetNaCl (`tweetnacl`) and blakejs — the same construction, and the same libraries, the mesh used
|
||||
// to validate this seal during Phase C. It generates the ephemeral X25519 key pair, derives the
|
||||
// nonce as `blake2b(ephemeralPub ‖ recipientPub, 24)`, and produces `ephemeralPub ‖ box`. That is
|
||||
// exactly what Go's `box.OpenAnonymous` opens: the wire format is unchanged from the hand-transcribed
|
||||
// version this replaces — only the implementation is now a maintained, reviewed dependency rather
|
||||
// than a copy of TweetNaCl and blakejs carried inline. The module runtime image bundles it
|
||||
// (package.json dependencies; novox/hq ADR 0052).
|
||||
//
|
||||
// **How it is kept honest.** A cross-language test seals a fixture here and opens it in Go
|
||||
// (mesh-controller internal/secrets/sealedbox_xcheck_test.go); the fixture is regenerated from this
|
||||
// `seal()`. A drift between this seal and Go's box surfaces there as a seal Go cannot open, not as a
|
||||
// refresh token silently mangled in production.
|
||||
//
|
||||
// This module SEALS only. It never opens — opening is the host's job, with the node private key the
|
||||
// module is deliberately never given.
|
||||
|
||||
// A default import, not `{ seal }`: the library is a CommonJS UMD bundle, and Node's ESM loader
|
||||
// cannot statically see its named exports — only its default, which is the whole module object.
|
||||
import sealedbox from "tweetnacl-sealedbox-js";
|
||||
|
||||
const RAW_KEY_LEN = 32;
|
||||
|
||||
/**
|
||||
* Seal a value to a node's public sealing key, producing what Go's `box.OpenAnonymous` opens.
|
||||
*
|
||||
* @param value the plaintext (e.g. a rotated refresh token)
|
||||
* @param recipientPublicB64 the node's raw 32-byte X25519 public key, standard base64
|
||||
* @returns standard-base64( ephemeralPub ‖ box )
|
||||
*/
|
||||
export function seal(value: Uint8Array, recipientPublicB64: string): string {
|
||||
const recipientPub = Buffer.from(recipientPublicB64, "base64");
|
||||
if (recipientPub.length !== RAW_KEY_LEN) {
|
||||
throw new Error(`a sealing public key is 32 bytes, not ${recipientPub.length}`);
|
||||
}
|
||||
const sealed = sealedbox.seal(value, new Uint8Array(recipientPub));
|
||||
return Buffer.from(sealed).toString("base64");
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { grantFromRefresh, flattenUsage } from "../client.ts";
|
||||
|
||||
test("an empty refresh response never clobbers a good grant", () => {
|
||||
assert.equal(grantFromRefresh({}, 1000), null);
|
||||
});
|
||||
|
||||
test("a refresh with an access token yields an access-token-only grant and epoch expiry", () => {
|
||||
const out = grantFromRefresh(
|
||||
{ access_token: "at-new", expires_in: 3600, refresh_token: "rt-rotated", subscription_type: "pro" },
|
||||
1_000_000,
|
||||
);
|
||||
assert.ok(out);
|
||||
assert.equal(out!.access.accessToken, "at-new");
|
||||
assert.equal(out!.access.expiresAt, 1_000_000 + 3600 * 1000);
|
||||
assert.equal(out!.access.subscriptionType, "pro");
|
||||
// The rotated refresh token is reported separately, for the manager to re-seal — never put in the
|
||||
// holder grant.
|
||||
assert.equal(out!.rotatedRefresh, "rt-rotated");
|
||||
assert.ok(!("refreshToken" in (out!.access as object)));
|
||||
});
|
||||
|
||||
test("a refresh that did not rotate the refresh token reports none to re-seal", () => {
|
||||
const out = grantFromRefresh({ access_token: "at-new" }, 0);
|
||||
assert.ok(out);
|
||||
assert.equal(out!.rotatedRefresh, null);
|
||||
});
|
||||
|
||||
test("usage flattens the vendor windows to the ADR 0054 grain", () => {
|
||||
const r = flattenUsage({
|
||||
five_hour: { utilization: 42, resets_at: "2026-01-01T00:00:00Z" },
|
||||
seven_day: { utilization: 10 },
|
||||
seven_day_sonnet: { utilization: 5 },
|
||||
extra_usage: { utilization: 1 },
|
||||
});
|
||||
assert.equal(r.sessionPct, 42);
|
||||
assert.equal(r.sessionResetsAt, "2026-01-01T00:00:00Z");
|
||||
assert.equal(r.weeklyPct, 10);
|
||||
assert.equal(r.sonnetPct, 5);
|
||||
assert.equal(r.extraPct, 1);
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { generateKeyPairSync } from "node:crypto";
|
||||
|
||||
import { seal } from "../sealedbox.ts";
|
||||
|
||||
// The definitive proof that this seal interoperates with Go's box.OpenAnonymous (the host's Unseal
|
||||
// and mesh-controller's secrets.Seal/Open) is a cross-language test in mesh-controller
|
||||
// (internal/secrets/sealedbox_xcheck_test.go), which opens a fixture this module's seal() produced.
|
||||
// These tests hold the TypeScript side: the output has the crypto_box_seal shape, and it is
|
||||
// randomised so a rotation that changed nothing looks nothing like one that changed everything.
|
||||
|
||||
/** A node public key as the mesh records it: raw 32-byte X25519, standard base64. */
|
||||
function aNodePublicKey(): string {
|
||||
const kp = generateKeyPairSync("x25519");
|
||||
const x = (kp.publicKey.export({ format: "jwk" }) as { x: string }).x;
|
||||
return Buffer.from(x, "base64url").toString("base64");
|
||||
}
|
||||
|
||||
test("a seal has the crypto_box_seal shape: ephemeralPub(32) + tag(16) + ciphertext(len)", () => {
|
||||
const pub = aNodePublicKey();
|
||||
const msg = Buffer.from("rt-a-refresh-token", "utf8");
|
||||
const blob = Buffer.from(seal(new Uint8Array(msg), pub), "base64");
|
||||
// 32 (ephemeral public key) + 16 (Poly1305 tag) + message length.
|
||||
assert.equal(blob.length, 32 + 16 + msg.length);
|
||||
});
|
||||
|
||||
test("two seals of the same value differ — a fresh ephemeral key each time", () => {
|
||||
const pub = aNodePublicKey();
|
||||
const msg = new Uint8Array(Buffer.from("rt-a-refresh-token", "utf8"));
|
||||
assert.notEqual(seal(msg, pub), seal(msg, pub));
|
||||
});
|
||||
|
||||
test("a public key that is not 32 bytes is refused before anything is sealed", () => {
|
||||
assert.throws(() => seal(new Uint8Array([1, 2, 3]), Buffer.from("short").toString("base64")));
|
||||
});
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"tweetnacl-sealedbox-js.d.ts",
|
||||
"sealedbox.ts",
|
||||
"grantfile.ts",
|
||||
"client.ts",
|
||||
"adopt/index.ts",
|
||||
"refresh/index.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// Ambient types for `tweetnacl-sealedbox-js` (crypto_box_seal), which ships without its own.
|
||||
// The library is a small UMD bundle over `tweetnacl` and `blakejs`; only `seal` is used here.
|
||||
declare module "tweetnacl-sealedbox-js" {
|
||||
/** crypto_box_seal: returns ephemeralPub(32) ‖ box, sealed to `recipientPublicKey`. */
|
||||
export function seal(message: Uint8Array, recipientPublicKey: Uint8Array): Uint8Array;
|
||||
/** crypto_box_seal_open: returns the plaintext, or null if it does not open. */
|
||||
export function open(
|
||||
sealed: Uint8Array,
|
||||
recipientPublicKey: Uint8Array,
|
||||
recipientSecretKey: Uint8Array,
|
||||
): Uint8Array | null;
|
||||
export const overheadLength: number;
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
# asus-zephyrus-g14
|
||||
|
||||
The hardware module for the **ASUS ROG Zephyrus G14** laptop: its vendor daemon and platform
|
||||
profiles, the hybrid GPU's mode and driver options, suspend, the lid and power key, low battery,
|
||||
the backlights, the vendor keys and the touchpad (novox/hq research 027/03 *Power management on
|
||||
the laptop*, research 026/05, to-be 42 phase 3).
|
||||
|
||||
## Why this name
|
||||
|
||||
A module is named after the hardware model, never the node (novox/hq ADR 0112; research 026/03:
|
||||
no flavors, no machine names). `asus-zephyrus-g14` is the model family exactly as the firmware
|
||||
reports it (`/sys/class/dmi/id/product_family` = `ROG Zephyrus G14`). The module's code checks that
|
||||
value and its switcher does nothing on any other model, and `zephyrus_check` reports it.
|
||||
|
||||
A wider name such as `asus-rog-laptop` would promise what this module cannot keep. Its contents
|
||||
belong to this family: the vendor-key scan codes, the eDP panel beside an NVIDIA dGPU, and the NVIDIA
|
||||
D3 workaround. A second G14 is assigned the same module. Another ROG model gets its own.
|
||||
|
||||
Written against the GA403 (2024, Ryzen 8945HS, RTX 4070 Laptop, hybrid). Older G14 years have the same
|
||||
daemons and probably the same keys. Their GPU options are unverified.
|
||||
|
||||
## What it owns
|
||||
|
||||
| | what | how |
|
||||
|---|---|---|
|
||||
| package | `asusctl` (asusd + client) | the distribution's package (`extra`). The machine was found with a local build of 6.4.0. The host only asserts *present*, so the switch to 6.5.0 from `extra` happens at the next `pacman -Syu` (or `pacman -S asusctl`). `zephyrus_check` flags a local build |
|
||||
| package | `upower`, `playerctl` | what the low-battery drop-in and the media keys use. `xinput` is the `xorg` module's (one package, one module on a node) |
|
||||
| service | `asusd` running (static unit: no boot state to declare), `supergfxd` running and enabled | |
|
||||
| archive | `/usr/local/lib/asus-zephyrus-g14/bin/` | the module's scripts, from `files/bin` (below) |
|
||||
| file ×2 | `~/.config/i3/config.d/10-asus.conf`, `20-g14.conf` | the laptop's lines in i3: the keys the firmware sends as ordinary presses (Fn+F6, Fn+F9), the keyboard-backlight notifier, the panel as primary, the touchpad key. The paths are adopted, because a second file binding the same keys makes i3's configuration check fail, and the `i3` module's watcher then reloads nothing |
|
||||
| file ×4 | `asus-zephyrus-g14-touchpad-resume.service`, and a drop-in `asus-zephyrus-g14-touchpad.conf` on each sleep service | the touchpad's settings once more after a resume (below) |
|
||||
| file | `/etc/modprobe.d/g14-nvidia-power.conf` | `NVreg_DynamicPowerManagement=0x00` (runtime D3 off: the ACPI D-Notifier hang) and `NVreg_PreserveVideoMemoryAllocations=1`. The path is adopted (ADR 0182) |
|
||||
| file | `/etc/modprobe.d/video-brightness-switch.conf` | `video.brightness_switch_enabled=0`, so the ACPI video driver does not also move a backlight on the keys. The file was on the machine and owned by nothing |
|
||||
| file ×3 | `systemd-{suspend,hibernate,suspend-then-hibernate}.service.d/asus-zephyrus-g14-nvidia.conf` | `Wants=` the matching `nvidia-*` sleep units and `nvidia-resume` (see *suspend units* below) |
|
||||
| file | `nvidia-powerd.service.d/asus-zephyrus-g14.conf` | `ConditionKernelCommandLine=zephyrus.nvidia-powerd`: Dynamic Boost runs only when the operator opts in at boot |
|
||||
| file | `/etc/systemd/logind.conf.d/power.conf` | the power key and the lid suspend, on battery, on mains and docked. `systemd-logind` is reloaded, never restarted |
|
||||
| file | `/etc/udev/rules.d/90-backlight.rules` | backlights writable by the `video` group. `systemd-udevd` is reloaded |
|
||||
| file | `triggerhappy.service.d/asus-zephyrus-g14.conf` | `thd … --user ${machine:account}`: the triggers run as the operator's account (below) |
|
||||
| file | `/etc/triggerhappy/triggers.d/asus-g14.conf` | the vendor keys: media (`KEY_PROG1/3/4`), panel brightness, touchpad (`KEY_F21`). The path is adopted, because two trigger files would fire every key twice |
|
||||
| file | `/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf` | low battery at 15/10/7 %; at 7 % **suspend**, not power off. A drop-in over the package's own file |
|
||||
| file | `/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf` | tap to click, natural scrolling, acceleration 0.15, as an X input class |
|
||||
|
||||
**What it does not own, on purpose:**
|
||||
|
||||
- `/etc/asusd/*.ron` belong to asusd, which rewrites them whenever a setting changes. RON is not a
|
||||
format the host writes into (ADR 0102 speaks JSON and marked blocks). Owning the file whole would
|
||||
repeat the predecessor's freeze: the measured file already differs from the one the predecessor
|
||||
shipped. The settings the module needs are set through asusd, by its code (below).
|
||||
- `/etc/supergfxd.conf` and `/etc/modprobe.d/supergfxd.conf` belong to supergfxd, which writes both.
|
||||
- The swap file, its unit and the swap partition are the machine's swap layout (research 027,
|
||||
question 3). They are not this module's, nor `memory-pressure`'s.
|
||||
- **Places.** The screen layouts for named places (`$mod+Alt+1…7`, `~/.screenlayout/`,
|
||||
`~/scripts/.screenlayouts/@*.sh`) name where the operator works, which no module may (ADR 0112).
|
||||
They are the operator's own lines until autorandr profiles replace them (the `xorg` module).
|
||||
- **The monitor-hotplug wizard** (`/etc/udev/rules.d/91-monitor-hotplug.rules`,
|
||||
`~/scripts/.screenlayouts/monitor-wizard.sh`) is any laptop's, not this model's. The predecessor said
|
||||
so itself (its `laptop` flavor). It is the display server's to replace with autorandr's own hotplug
|
||||
handling. Until then it stays as found, and it still calls the predecessor's `as-user`.
|
||||
- **The screenshot script** (`~/.config/i3/scripts/screenshot.sh`) is any machine's. The `i3` module
|
||||
binds it too. This module only binds the key the firmware sends for it.
|
||||
- **The bar's battery block.** It belongs here (a block that follows this model's hardware), but the
|
||||
bar has no way in yet (`i3status-rust` README). Once ADR 0210's contributions reach the bar seat,
|
||||
this module contributes it.
|
||||
|
||||
**Requires `x11-display`.** The i3 lines and the session scripts need a display, so the module is
|
||||
assigned where the display server is.
|
||||
|
||||
## Software outside the distribution (ADR 0205, research 027 question 1)
|
||||
|
||||
`supergfxctl` (5.2.7, from the asus-linux repository, which is no longer configured) and
|
||||
`triggerhappy` (AUR) are **kept as found, and depended on**. The module declares no package for
|
||||
either, because the host installs from the official repositories only. It declares their services
|
||||
(`supergfxd` running, `triggerhappy` running), so on a machine without them the host refuses the
|
||||
service by name: *does not exist on this machine*. The refusal is loud, never a silent pass.
|
||||
`zephyrus_check` names both as foreign.
|
||||
|
||||
This module does not choose between the options of research 027 question 1. Under the starting
|
||||
position (P2: the build machine builds AUR packages into a repository the mesh serves), both become
|
||||
`package` resources here, and a fresh G14 installs them. **Until P2 exists, a fresh G14 is blocked
|
||||
on installing these two by hand.** ADR 0205's vendored archive (P1) does not fit: supergfxctl is a
|
||||
daemon with a system-bus policy and udev rules, and triggerhappy is C.
|
||||
|
||||
A later option for the keys: the module's own Go code could read the vendor keys from evdev, which
|
||||
the operator's account may do through the `input` group. That would retire triggerhappy entirely.
|
||||
It is not done here, because it would put the keys behind the node's runtime, and the runtime
|
||||
restarts a bundle that dies only on its next call (below).
|
||||
|
||||
## The long-running code: the profile switcher (ADR 0198)
|
||||
|
||||
The module's Go bundle serves the tools and runs the platform-profile switcher in the same process.
|
||||
The node's runtime launches the bundle at the runtime's start. It replaces the predecessor's
|
||||
`auto-profile`, a user unit that woke every five seconds, on battery too.
|
||||
|
||||
- **Policy** (constants until settings exist, issue 168): battery → `Quiet`; mains → `Balanced`;
|
||||
mains with the CPU at or above 50 % for 3 samples of 10 s → `Performance`, back to `Balanced` after
|
||||
3 samples at or below 20 %. Between the lines nothing moves (hysteresis). iowait counts as idle.
|
||||
- **Woken by events, not a poll.** The kernel's power-supply uevents (netlink, group 1) wake the
|
||||
switcher. Any account may listen on that group, and it needs no daemon, bus client or dependency;
|
||||
upower re-announces the same changes but would need a D-Bus client in the bundle. The CPU is
|
||||
sampled only on mains, every 10 s, because only there does the answer depend on it. On battery,
|
||||
a safety re-read every 5 minutes covers an event lost across a suspend. If the uevent socket
|
||||
cannot be opened, the switcher polls every 10 s and says so in `zephyrus_profile_policy`.
|
||||
- **The battery decides the source.** A battery that is *discharging* means battery, whatever any
|
||||
adapter says. The predecessor took any `online` file reading 1 as mains, and on this model the USB-C
|
||||
ports report `online`. Batteries of `scope=Device` (a mouse, a headset) are ignored.
|
||||
- **It acts on a change of its decision, never to restore one.** A profile someone chose by hand (the
|
||||
profile key, asusctl, `zephyrus_profile`) stays until the power source changes or the load crosses
|
||||
a line. The predecessor re-asserted its choice every five seconds, which made the profile key
|
||||
useless. **Starting is not a decision**: the runtime restarts the bundle on every push that changes
|
||||
one, and a push must not reset the operator's profile.
|
||||
- **A hold.** `zephyrus_profile` holds the profile it sets for 60 min (`hold_minutes`). A change of
|
||||
power source ends the hold.
|
||||
- **One assertion at start:** through asusctl, the charge limit (80 %) and asusd's own on-mains and
|
||||
on-battery profiles (`Balanced`, `Quiet`), each read first and set only if it differs. asusd's own
|
||||
switching on a change of power source then agrees with the switcher's. A limit set later with
|
||||
`zephyrus_charge_limit` stands until the bundle next starts. For a one-off full charge, use its
|
||||
`oneshot`.
|
||||
- **Events:** `profile.switched` (`profile`, `from`, `reason`, `source`), published through the
|
||||
runtime.
|
||||
|
||||
No root is involved. asusd's and supergfxd's bus policies admit the `users` and `wheel` groups, and the
|
||||
runtime runs as the operator's account. The one write that may escalate is the panel's backlight,
|
||||
when the udev rule has not run yet. It uses `sudo -n` and never prompts. Every command is bounded at
|
||||
20 s.
|
||||
|
||||
**Known limit.** The runtime restarts a launched bundle that exits *on its next tool call*, not at
|
||||
once (mesh-tools `launch.ts`), so a crashed switcher stays down until a tool is called. ADR 0198 §1
|
||||
says *started again when it exits*. The switcher recovers from a panic and reports it in
|
||||
`zephyrus_profile_policy` and `zephyrus_check`, but a crash of the process is the runtime's to restart.
|
||||
|
||||
## The vendor keys and the scripts
|
||||
|
||||
triggerhappy opens the input devices as root, then **drops to the operator's account with its groups**
|
||||
(`initgroups`: `input`, `video`). The packaged unit already drops to `nobody`, and the module's drop-in
|
||||
names the account instead. The predecessor replaced the packaged unit with one that ran every trigger
|
||||
as root, then `su`-ed to a named person with a hard-coded uid and display, and sourced a file of
|
||||
secrets on the way (research 027 question 2). Now:
|
||||
|
||||
- `zephyrus-session CMD…`: runs a command in the account's graphical session. It sets the account's
|
||||
own bus (`/run/user/<uid>/bus`) and takes the display and its authority from the session's window
|
||||
manager's own environment, as the desktop modules' session finder does. If i3 is not running, it
|
||||
asks logind, and then any process of the account that has a display. Nothing is sourced.
|
||||
triggerhappy's `--user` changes the user and its groups and nothing else: the triggers start with
|
||||
the service's bare environment, which is why every key that needs the session goes through this.
|
||||
- `zephyrus-media play-pause | next | previous`: the media keys through MPRIS, with a notification of
|
||||
what happened and a lock against the key's own repeat.
|
||||
- `zephyrus-display primary | order`: the internal panel as the primary output, and the display key's
|
||||
workspace split (odd workspaces on the panel, even ones on the first external output). The panel is
|
||||
found as the connected `eDP` output. The predecessor named `eDP-1` and used `jq`. This reads i3's
|
||||
answer without it.
|
||||
- `zephyrus-kbd-notify`: the keyboard backlight's level, shown when UPower says it changed. One
|
||||
instance per session, because i3 runs its `exec` lines again on an in-place restart.
|
||||
- `zephyrus-backlight + | - | N`: the panel in 5 % steps, never below 1 %. **The panel is the
|
||||
backlight under the eDP connector**, because this model also registers `nvidia_0`, which moves
|
||||
nothing. The predecessor named `amdgpu_bl1` literally.
|
||||
- `zephyrus-notify ID TEXT`: one replacing notification, through `busctl` (the service manager's
|
||||
client, so no libnotify).
|
||||
- `zephyrus-touchpad reset | toggle`: bound to the touchpad key (`KEY_F21`).
|
||||
|
||||
**Media keys** go to MPRIS through `playerctl`. The predecessor's fallback to a media server's local
|
||||
API needed a token from the secrets file, and is dropped until a module can be handed a secret
|
||||
(research 027 question 2). A player that does not speak MPRIS is told as "Media: no player".
|
||||
|
||||
## The touchpad: an input class instead of a sleep hook
|
||||
|
||||
The predecessor re-ran `xinput` from `/etc/systemd/system-sleep/` after every resume, as a named person
|
||||
on a guessed display, because settings made with `xinput` are lost when the device initialises again.
|
||||
An X input class is applied by X **every time the device appears**: at login, on hotplug and after a
|
||||
resume. So the cause is fixed. The class matches any touchpad on the machine, which is the model's, so it
|
||||
holds across G14 years whose touchpads differ. It takes effect at the next X start.
|
||||
`zephyrus-touchpad reset` stays as the manual form, on the touchpad key and `$mod+Shift+x`.
|
||||
|
||||
**And a backstop after resume.** A resume that does not initialise the device again does not make X
|
||||
apply the class either, and the predecessor's i3 file says the touchpad "sometimes needs re-init after
|
||||
sleep". So `asus-zephyrus-g14-touchpad-resume.service` runs `zephyrus-touchpad reset` as the account,
|
||||
two seconds after the machine is awake. It is never enabled. Each sleep service `Wants=` it through a
|
||||
drop-in, and it is ordered `After=` them, which is how `nvidia-resume` is started too.
|
||||
`zephyrus_check` says whether the sleep wants it.
|
||||
|
||||
## Suspend units without enabling them
|
||||
|
||||
`nvidia-suspend`, `-hibernate`, `-suspend-then-hibernate` and `-resume` are enabled with links in the
|
||||
sleep services' `.wants` directories. The mesh makes no links (ADR 0012). The host's service shape
|
||||
cannot declare them either: it may only say *running* or *stopped*, and *running* on a one-shot that
|
||||
last failed would start `nvidia-sleep.sh suspend` with the machine awake. So the module asks for them
|
||||
from the other side: a drop-in on each sleep service that `Wants=` them. The units' own
|
||||
`Before=`/`After=` order them. The found links stay and are harmless.
|
||||
|
||||
`suspend-then-hibernate` now also gets `nvidia-suspend-then-hibernate`, which the machine lacked.
|
||||
|
||||
The drop-ins take effect at the service manager's next `daemon-reload`. In the same apply, the restart
|
||||
of `triggerhappy` (whose drop-in changes) performs one.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | r/a | what |
|
||||
|---|---|---|
|
||||
| `zephyrus_brightness` | r/a | panel (percent or ±step, floor 1 %) and keyboard (off/low/med/high, 0-3, ±) through asusd |
|
||||
| `zephyrus_battery` | r | charge, energy in Wh, health (full ÷ design), cycles (the firmware reports 0, and this is said), limit, watts, hours left |
|
||||
| `zephyrus_charge_limit` | r/a | 20-100 through asusd; `oneshot` |
|
||||
| `zephyrus_gpu_mode` | r/a | mode, supported modes, dGPU power, the pending mode and action; says that asusd switches the mode on every change of power source |
|
||||
| `zephyrus_profile` | r/a | active, on-mains and on-battery profile, kernel platform profile; set with a hold |
|
||||
| `zephyrus_thermals` | r | every hwmon temperature and fan, the hottest, the dGPU's temperature **only when it is awake** (nvidia-smi wakes a suspended GPU) |
|
||||
| `zephyrus_power_draw` | r | battery flow, APU package power (PPT), dGPU draw when awake, power source and why |
|
||||
| `zephyrus_profile_policy` | r | what the switcher would choose now and why: source, recent load against the thresholds, decision, hold, last switch, what woke it, what it asserted at start, and whether the predecessor's switcher still runs |
|
||||
| `zephyrus_fan_curves` | r | asusd's curves per profile and fan |
|
||||
| `zephyrus_keys` | r | every custom key: each triggerhappy trigger, the module's i3 lines and the keys the firmware handles; what runs and the file it is in. Warns when one key is in two trigger files, which fires it twice |
|
||||
| `zephyrus_check` | r | every expectation: model, packages (local or foreign), daemons, nvidia-powerd, sleep units, the NVIDIA options **in force** (`/proc/driver/nvidia/params`), charge limit, one authority each over the profile and the GPU mode, predecessor leftovers; the touchpad resume unit wanted by the sleep; triggerhappy running as the operator's account; any trigger, udev rule or sleep hook still naming `as-user`. It also lists what it did not check |
|
||||
|
||||
`profile` is a candidate verb for a future `node-power-profile` seat (research 027/03). That seat has
|
||||
no record yet, so this is the module's own tool.
|
||||
|
||||
## Found on the laptop, 2026-10-04 (read-only)
|
||||
|
||||
- **Two authorities over the GPU mode.** `asusd.ron` has `ac_command: "supergfxctl -m Hybrid"` and
|
||||
`bat_command: "supergfxctl -m Integrated"`, so asusd switches the GPU mode on every change of power
|
||||
source. **supergfxd 5.2.7 cannot read logind's sessions** (`manager is an invalid variant`, every
|
||||
boot), so a switch that needs a logout times out. `zephyrus_check` reports both. The fix is the
|
||||
operator's, in asusd's file: clear both commands, or update supergfxctl once it can be packaged.
|
||||
- **`brightness.conf` did nothing.** `HandleBrightnessKey` is not a logind key, and logind logs
|
||||
*Unknown key … ignoring* at every start. The module does not carry it. The brightness keys were
|
||||
always triggerhappy's, with the ACPI video switch off.
|
||||
- **Two profile switchers** would run at once until `auto-profile` is stopped (below).
|
||||
- **asusctl is a local build** (6.4.0, *Unknown Packager*) beside a foreign `asusctl-debug`.
|
||||
|
||||
## When assigned to the laptop: what changes
|
||||
|
||||
1. `/usr/local/lib/asus-zephyrus-g14/` appears (seven scripts).
|
||||
2. Written over found files (each original kept once by the host): `g14-nvidia-power.conf` and
|
||||
`video-brightness-switch.conf` (same options, so no change until the next boot either),
|
||||
`logind.conf.d/power.conf` (same keys; logind reloaded), `90-backlight.rules` (same effect;
|
||||
udevd reloaded), `triggers.d/asus-g14.conf` (now the module's scripts), and i3's `10-asus.conf` and
|
||||
`20-g14.conf` (the module's lines; the `i3` module's watcher checks and reloads them).
|
||||
3. New: the three sleep drop-ins (behaviour gained: `nvidia-suspend-then-hibernate`), the
|
||||
nvidia-powerd drop-in (no effect while it is masked), the triggerhappy drop-in, the UPower drop-in
|
||||
(same values as today), the touchpad input class (at the next X start), and the resume unit with
|
||||
its three drop-ins.
|
||||
4. `daemon-reload` and a `triggerhappy` restart. thd now runs as the account and the keys run the
|
||||
module's scripts. `upower` restarts.
|
||||
5. Packages, asusd and supergfxd: already as declared, so nothing changes. asusctl stays the local
|
||||
6.4.0 until the next upgrade.
|
||||
6. The node runtime restarts with the new bundle. The switcher asserts the limit (80, already) and
|
||||
asusd's profiles (Balanced and Quiet, already), so it sets nothing. It takes the current decision
|
||||
as applied and acts from the first event on.
|
||||
|
||||
## Predecessor files this module makes redundant — the operator removes them once (ADR 0182)
|
||||
|
||||
**On the laptop:**
|
||||
|
||||
1. `systemctl --user disable --now auto-profile.service`, then delete
|
||||
`~/.config/systemd/user/auto-profile.service` and `~/scripts/auto-profile`. **Do this right after
|
||||
the push**, or two switchers run at once.
|
||||
2. **Before the push, keep the place layouts.** The module writes `20-g14.conf` over the found file,
|
||||
and the found file carries the seven `$mod+Alt+1…7` layout bindings, which name places. Move them,
|
||||
and the `exec … ~/.screenlayout/@default.sh` line, to a file of your own in the same directory,
|
||||
e.g. `~/.config/i3/config.d/90-layouts.conf`. i3 reads it the same way, and it stays yours until
|
||||
autorandr profiles replace it. The host keeps the found `20-g14.conf` once in any case.
|
||||
3. `~/scripts/asus-bright`, `~/scripts/asusctl-kbd-bright`, `~/scripts/xrandr-bright`,
|
||||
`~/scripts/media-control`, `~/scripts/xinput-reset-touchpad`,
|
||||
`~/scripts/.screenlayouts/orden-workspaces.sh` and `~/.config/i3/scripts/kbd-brightness-notify.sh`:
|
||||
no trigger and no line of the module's uses them any more.
|
||||
**Keep `~/scripts/as-user`** while `/etc/udev/rules.d/91-monitor-hotplug.rules` exists: that rule
|
||||
still runs the monitor wizard through it. `zephyrus_check` names every place that still calls it.
|
||||
4. `/etc/systemd/system/triggerhappy.service`: the predecessor's replacement of the packaged unit. The
|
||||
module's drop-in works over either, so delete it and `systemctl daemon-reload` to return to the
|
||||
packaged unit (`Type=notify`, socket).
|
||||
5. `/etc/systemd/logind.conf.d/brightness.conf`: the unknown key, which does nothing.
|
||||
6. `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`, if it is still there: replaced by the input
|
||||
class and the resume unit. (It was already gone on 2026-10-04.)
|
||||
7. `/etc/UPower/UPower.conf`: the predecessor's replacement of the package's file. Its values are now
|
||||
the module's drop-in. Restore the package's copy (`rm` it, then `pacman -S upower`).
|
||||
8. Optional: `systemctl disable nvidia-suspend nvidia-resume nvidia-hibernate` (the drop-ins carry them
|
||||
now), `/etc/asusd/*.ron-old` and `fan_curves.ron.bak`, the foreign `asusctl-debug` package, and
|
||||
`pacman -S asusctl` for the distribution's build.
|
||||
|
||||
**Stays the machine's:** `/swapfile` and `/etc/systemd/system/swapfile.swap` (the swap layout),
|
||||
`/etc/udev/rules.d/91-monitor-hotplug.rules` (the display's, phase 2), and the place layouts.
|
||||
|
||||
**On the desktop** (the predecessor's G14 flavor reached it; part was removed on 2026-10-04): none of
|
||||
this module applies there. Still present and to be deleted:
|
||||
`/etc/systemd/logind.conf.d/brightness.conf`, `/etc/systemd/system-sleep/xinput-reset-touchpad.sh`,
|
||||
`~/scripts/xinput-reset-touchpad`, `~/scripts/xrandr-bright` and
|
||||
`~/.config/i3/scripts/kbd-brightness-notify.sh`.
|
||||
|
||||
## The predecessor, file by file
|
||||
|
||||
The predecessor carried this model in its desktop module's `g14` and `laptop` flavors, and in a
|
||||
`g14-power` module. Every model-specific file of the desktop module, and where it is now:
|
||||
|
||||
| predecessor file | now |
|
||||
|---|---|
|
||||
| `i3-asus.conf` → `config.d/10-asus.conf` | **this module**, the same path; the scripts it calls are the module's |
|
||||
| `i3-g14.conf` → `config.d/20-g14.conf` | **this module**, the same path. The place layouts in it are the operator's own file (migration, step 2) |
|
||||
| `g14-triggerhappy-asus-g14.conf` | **this module**, the same path; the triggers run the module's scripts |
|
||||
| `g14-triggerhappy.service` (a replacement of the packaged unit) | **retired**: a drop-in over the packaged unit (`--user`) |
|
||||
| `as-user` | **retired**: thd runs as the account, and `zephyrus-session` finds the session. Kept on the machine while the monitor wizard's udev rule calls it |
|
||||
| `asus-bright` | **this module**: `zephyrus-backlight`, the panel found by its connector |
|
||||
| `media-control` (bound by the `g14` triggers) | **this module**: `zephyrus-media`, without the fallback that needed a secret |
|
||||
| `xinput-reset-touchpad` | **this module**: the input class, `zephyrus-touchpad`, and the resume unit |
|
||||
| `g14-system-sleep-xinput-reset-touchpad.sh` | **this module**: the input class, and the resume unit that the sleep services want |
|
||||
| `kbd-brightness-notify.sh` | **this module**: `zephyrus-kbd-notify`, one instance per session |
|
||||
| `asusctl-kbd-bright` | **retired**: the keyboard keys are the firmware's, and `zephyrus_brightness` sets it by hand |
|
||||
| `xrandr-bright` | **retired**: a software dimming; the panel's backlight is `zephyrus-backlight` |
|
||||
| `screenlayout-orden-workspaces.sh` | **this module**: `zephyrus-display order`, on Fn+F9 |
|
||||
| `screenlayout-*.sh` (six named places) | **the operator's**, until autorandr profiles (the `xorg` module) replace them |
|
||||
| `g14-90-backlight.rules` | **this module**, the same path |
|
||||
| `g14-logind-brightness.conf` | **retired**: an unknown logind key that did nothing |
|
||||
| `laptop-monitor-wizard.sh`, `laptop-91-monitor-hotplug.rules` | **any laptop's, not this module's**: kept as found, for the `xorg` module's autorandr to replace |
|
||||
| `bottom-bar.g14.toml` (the battery block) | **waits**: this module's, once the bar takes contributions (ADR 0210) |
|
||||
| `razer-basilisk-battery-percentage` | **not this model's**: a mouse. No module carries it (`i3status-rust` README) |
|
||||
| `screenshot.sh` | **not this model's**: any machine's script, which the `i3` module binds too; this module binds Fn+F6 to it |
|
||||
| package `triggerhappy` | **depended on, kept as found** (outside the distribution, above) |
|
||||
|
||||
`g14-power`'s pieces (the NVIDIA options, logind, UPower, the sleep units, `auto-profile`) are in
|
||||
*What it owns* and the switcher above. Its memory guard is the `memory-pressure` module's.
|
||||
|
||||
## What the predecessor paid for, and what this module does about it
|
||||
|
||||
- **One file for every machine overwrote what each machine needed** (the predecessor's split of its i3
|
||||
configuration into a base, an ASUS and a G14 layer, 2026-03). Here the model's lines are this
|
||||
module's files, and nothing else writes them.
|
||||
- **The layers silently stopped applying.** The predecessor's chain *laptop → g14* was stated in two
|
||||
places, and the one its installer read lacked it. For weeks the G14 received only its 21
|
||||
G14-tagged files, and the 49 base and laptop files were never seeded. Validation and the pipeline
|
||||
both reported success (2026-08, found at a cutover). Here a module is one manifest. Its tests assert
|
||||
that every trigger runs a script it ships, and `zephyrus_check` and `zephyrus_keys` read back what is
|
||||
on the machine.
|
||||
- **A hook wrote asusd's own files with sudo,** because configuration sync might not run on install
|
||||
(2026-04), and froze them. asusd rewrites those files whenever a setting changes. Here the module
|
||||
sets asusd through its client and never writes the RON files.
|
||||
- **A profile daemon fought the profile key.** The predecessor turned asusd's own switching off and
|
||||
re-asserted its choice every five seconds (2026-03). Here the switcher acts on a change of its
|
||||
decision, never to restore one.
|
||||
- **The overnight freeze** was an ACPI power-source event hanging the NVIDIA GPU in runtime D3
|
||||
(2026-06). It is fixed by the driver options, which `zephyrus_check` reads from the running driver
|
||||
rather than from the file.
|
||||
- **A unit restarted about 73,000 times, unnoticed** (2026-06). Here every expectation is in
|
||||
`zephyrus_check`, and so is a list of what it did not check.
|
||||
- **The vendor keys ran as root and `su`-ed to a named person** on a guessed display, sourcing a file
|
||||
of secrets. Here thd drops to the account, and nothing is sourced.
|
||||
- **The touchpad lost its settings after a resume,** because `xinput` settings vanish when the device
|
||||
initialises again. Here an input class re-applies them, with the resume unit as a backstop.
|
||||
|
||||
## Tests
|
||||
|
||||
`go test ./...` in this directory. Every tool runs against a tree standing in for `/sys`, `/proc` and
|
||||
`/etc`, and an injected runner answering with what asusctl 6.4 and supergfxctl 5.2 said on the laptop.
|
||||
The tests cover:
|
||||
|
||||
- the power-source rule;
|
||||
- battery arithmetic from `charge_*`;
|
||||
- the eDP panel choice;
|
||||
- brightness bounds;
|
||||
- the policy's sustain, relax and hysteresis, with iowait counted as idle;
|
||||
- the switcher: no act at start, one switch per change of source, a published event, boost from
|
||||
samples, holds, retry after failure, start-up assertions only where they differ, inert on another
|
||||
model;
|
||||
- the uevent filter;
|
||||
- the manifest: tools listed equal tools served, no machine named, triggers exist, every key runs a
|
||||
shipped executable script, every script passes `bash -n`;
|
||||
- `zephyrus_keys` over the module's own triggers and i3 lines, and a key in two trigger files;
|
||||
- the checks for `as-user`, triggerhappy's account and the resume unit.
|
||||
|
||||
## The vendor keys are a contribution (changed 2026-10-04, novox/hq ADR 0212)
|
||||
|
||||
The trigger file and triggerhappy's service drop-in are no longer this module's. The `triggerhappy`
|
||||
module holds `node-hotkeys`, owns the daemon, and reads only the mesh's trigger file. This module
|
||||
contributes its eight trigger lines (media, panel brightness, touchpad) to that seat, so it depends
|
||||
on a hotkey holder being assigned beside it. Its keys still run this module's own scripts.
|
||||
`zephyrus_keys` reads the trigger directory as before.
|
||||
|
||||
## The touchpad after waking, and the lid, move to the power module (changed 2026-10-04, novox/hq ADR 0211)
|
||||
|
||||
The touchpad resume unit and its three drop-ins on the sleep services are gone. The reset is now this
|
||||
module's contribution to `node-power`'s `after-wake` moment, so the module depends on the power
|
||||
module. `logind.conf.d/power.conf` is the power module's. This laptop's values (suspend on the power
|
||||
key and on the lid in every case) are that module's settings for this machine. The NVIDIA driver's
|
||||
sleep drop-ins stay here: they must run inside the sleep transaction, which a contribution cannot.
|
||||
|
||||
## Its i3 lines are a contribution (changed 2026-10-05, novox/hq ADR 0212)
|
||||
|
||||
The module no longer writes a file into i3's `config.d`. Its window-manager lines (the source is still
|
||||
under `files/i3/` where it had one) are a contribution to `node-display-session`. The i3 module places
|
||||
them in its own configuration under a `# <module>` line, so this module depends on a window manager
|
||||
being assigned beside it.
|
||||
@@ -0,0 +1,264 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The vendor daemons are reached through their own command-line clients, which speak to them on the
|
||||
// system bus. Their bus policy admits the `users` and `wheel` groups, so none of this needs root.
|
||||
|
||||
// Profiles are the platform profiles asusd offers on this model, in its spelling.
|
||||
var Profiles = []string{"Quiet", "Balanced", "Performance"}
|
||||
|
||||
// canonicalProfile accepts any case and answers asusd's spelling, or an error naming the choices.
|
||||
func canonicalProfile(s string) (string, error) {
|
||||
for _, p := range Profiles {
|
||||
if strings.EqualFold(strings.TrimSpace(s), p) {
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("profile %q is not one of %s", s, strings.Join(Profiles, ", "))
|
||||
}
|
||||
|
||||
// ProfileState is what asusd says about the platform profile.
|
||||
type ProfileState struct {
|
||||
Active string `json:"active"`
|
||||
OnAC string `json:"on_ac,omitempty"`
|
||||
Battery string `json:"on_battery,omitempty"`
|
||||
Platform string `json:"platform_profile,omitempty"`
|
||||
Choices string `json:"platform_profile_choices,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
activeProfile = regexp.MustCompile(`(?m)^Active profile:\s*(\S+)`)
|
||||
acProfile = regexp.MustCompile(`(?m)^AC profile\s+(\S+)`)
|
||||
batteryProfile = regexp.MustCompile(`(?m)^Battery profile\s+(\S+)`)
|
||||
)
|
||||
|
||||
// ParseProfileGet reads `asusctl profile get`.
|
||||
func ParseProfileGet(out string) (ProfileState, error) {
|
||||
var p ProfileState
|
||||
if m := activeProfile.FindStringSubmatch(out); m != nil {
|
||||
p.Active = m[1]
|
||||
} else {
|
||||
return p, fmt.Errorf("asusctl profile get said no active profile: %q", strings.TrimSpace(out))
|
||||
}
|
||||
if m := acProfile.FindStringSubmatch(out); m != nil {
|
||||
p.OnAC = m[1]
|
||||
}
|
||||
if m := batteryProfile.FindStringSubmatch(out); m != nil {
|
||||
p.Battery = m[1]
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Profile reads the platform profile from asusd and the kernel.
|
||||
func (m *Machine) Profile(ctx context.Context) (ProfileState, error) {
|
||||
out, err := m.Run(ctx, "asusctl", "profile", "get")
|
||||
if err != nil {
|
||||
return ProfileState{}, vendor("asusctl", err)
|
||||
}
|
||||
p, err := ParseProfileGet(out)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
p.Platform = m.read("/sys/firmware/acpi/platform_profile")
|
||||
p.Choices = m.read("/sys/firmware/acpi/platform_profile_choices")
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// SetProfile has asusd switch the active profile.
|
||||
func (m *Machine) SetProfile(ctx context.Context, profile string) error {
|
||||
_, err := m.Run(ctx, "asusctl", "profile", "set", profile)
|
||||
return vendor("asusctl", err)
|
||||
}
|
||||
|
||||
var chargeLimit = regexp.MustCompile(`charge limit:\s*(\d+)\s*%`)
|
||||
|
||||
// ChargeLimit is the battery's charge limit as asusd reports it.
|
||||
func (m *Machine) ChargeLimit(ctx context.Context) (int, error) {
|
||||
out, err := m.Run(ctx, "asusctl", "battery", "info")
|
||||
if err != nil {
|
||||
return 0, vendor("asusctl", err)
|
||||
}
|
||||
g := chargeLimit.FindStringSubmatch(out)
|
||||
if g == nil {
|
||||
return 0, fmt.Errorf("asusctl battery info said no limit: %q", strings.TrimSpace(out))
|
||||
}
|
||||
n, _ := strconv.Atoi(g[1])
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Keyboard backlight levels in asusd's spelling, index = the kernel's brightness value.
|
||||
var KeyboardLevels = []string{"off", "low", "med", "high"}
|
||||
|
||||
var ledLevel = regexp.MustCompile(`(?i)brightness:\s*(off|low|med|high)`)
|
||||
|
||||
// ParseLeds reads `asusctl leds get`.
|
||||
func ParseLeds(out string) (string, error) {
|
||||
g := ledLevel.FindStringSubmatch(out)
|
||||
if g == nil {
|
||||
return "", fmt.Errorf("asusctl leds get said no level: %q", strings.TrimSpace(out))
|
||||
}
|
||||
return strings.ToLower(g[1]), nil
|
||||
}
|
||||
|
||||
// FanCurve is one fan's curve in one profile: eight points of temperature (°C) and duty (0-255).
|
||||
type FanCurve struct {
|
||||
Fan string `json:"fan"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Temp []int `json:"temp_c"`
|
||||
PWM []int `json:"pwm"`
|
||||
}
|
||||
|
||||
var (
|
||||
fanBlock = regexp.MustCompile(`(?s)fan:\s*(\w+),\s*pwm:\s*\(([^)]*)\),\s*temp:\s*\(([^)]*)\),\s*enabled:\s*(true|false)`)
|
||||
)
|
||||
|
||||
// ParseFanCurves reads `asusctl fan-curve --mod-profile <p>`.
|
||||
func ParseFanCurves(out string) []FanCurve {
|
||||
var curves []FanCurve
|
||||
for _, g := range fanBlock.FindAllStringSubmatch(out, -1) {
|
||||
curves = append(curves, FanCurve{Fan: g[1], PWM: ints(g[2]), Temp: ints(g[3]), Enabled: g[4] == "true"})
|
||||
}
|
||||
return curves
|
||||
}
|
||||
|
||||
func ints(list string) []int {
|
||||
var out []int
|
||||
for _, f := range strings.Split(list, ",") {
|
||||
if n, err := strconv.Atoi(strings.TrimSpace(f)); err == nil {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GPUState is what supergfxd says about the hybrid GPU.
|
||||
type GPUState struct {
|
||||
Mode string `json:"mode"`
|
||||
Supported []string `json:"supported"`
|
||||
Power string `json:"dgpu_power,omitempty"`
|
||||
PendingAction string `json:"pending_action,omitempty"`
|
||||
PendingMode string `json:"pending_mode,omitempty"`
|
||||
Vendor string `json:"dgpu_vendor,omitempty"`
|
||||
}
|
||||
|
||||
// ParseSupported reads `supergfxctl -s`: `[Integrated, Hybrid, AsusMuxDgpu]`.
|
||||
func ParseSupported(out string) []string {
|
||||
out = strings.Trim(strings.TrimSpace(out), "[]")
|
||||
var modes []string
|
||||
for _, f := range strings.Split(out, ",") {
|
||||
if f = strings.TrimSpace(f); f != "" {
|
||||
modes = append(modes, f)
|
||||
}
|
||||
}
|
||||
return modes
|
||||
}
|
||||
|
||||
// GPU reads supergfxd.
|
||||
func (m *Machine) GPU(ctx context.Context) (GPUState, error) {
|
||||
var g GPUState
|
||||
mode, err := m.Run(ctx, "supergfxctl", "-g")
|
||||
if err != nil {
|
||||
return g, vendor("supergfxctl", err)
|
||||
}
|
||||
g.Mode = strings.TrimSpace(mode)
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-s"); err == nil {
|
||||
g.Supported = ParseSupported(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-S"); err == nil {
|
||||
g.Power = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-p"); err == nil {
|
||||
g.PendingAction = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-P"); err == nil {
|
||||
g.PendingMode = strings.TrimSpace(s)
|
||||
}
|
||||
if s, err := m.Run(ctx, "supergfxctl", "-V"); err == nil {
|
||||
g.Vendor = strings.TrimSpace(s)
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// vendor names a vendor client that is not installed, rather than passing on "executable file not
|
||||
// found". asusctl is in the distribution's repositories; supergfxctl is not, and the module keeps it as
|
||||
// it was found until the mesh can build packages from the user repository (research 027, question 1).
|
||||
func vendor(name string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if notInstalled(err) {
|
||||
switch name {
|
||||
case "supergfxctl":
|
||||
return fmt.Errorf("supergfxctl is not installed: it is not in the distribution's repositories, " +
|
||||
"and this module keeps the copy it finds rather than install one (novox/hq research 027, question 1)")
|
||||
default:
|
||||
return fmt.Errorf("%s is not installed; the module's package resource installs it", name)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AsusdConfig is the few settings of asusd's own file that decide what this module's code does. The
|
||||
// file is asusd's: it rewrites it whenever a setting changes, so the module reads it and never writes
|
||||
// it.
|
||||
type AsusdConfig struct {
|
||||
ChargeLimit *int `json:"charge_control_end_threshold,omitempty"`
|
||||
ProfileOnAC string `json:"platform_profile_on_ac,omitempty"`
|
||||
ProfileOnBattery string `json:"platform_profile_on_battery,omitempty"`
|
||||
ChangesProfileOnAC *bool `json:"change_platform_profile_on_ac,omitempty"`
|
||||
ChangesProfileOnBatt *bool `json:"change_platform_profile_on_battery,omitempty"`
|
||||
ACCommand string `json:"ac_command,omitempty"`
|
||||
BatteryCommand string `json:"bat_command,omitempty"`
|
||||
DisablesPowerdOnBatt *bool `json:"disable_nvidia_powerd_on_battery,omitempty"`
|
||||
}
|
||||
|
||||
var ronField = regexp.MustCompile(`(?m)^\s{4}([a-z_]+):\s*(.*?),?\s*$`)
|
||||
|
||||
// ParseAsusdRon reads the top-level scalar fields of asusd.ron. RON is not a format the mesh
|
||||
// speaks; these are one line each, and nothing nested is read.
|
||||
func ParseAsusdRon(text string) AsusdConfig {
|
||||
var c AsusdConfig
|
||||
for _, g := range ronField.FindAllStringSubmatch(text, -1) {
|
||||
key, value := g[1], strings.TrimSuffix(strings.TrimSpace(g[2]), ",")
|
||||
unquoted := strings.Trim(value, `"`)
|
||||
boolean := func() *bool { b := value == "true"; return &b }
|
||||
switch key {
|
||||
case "charge_control_end_threshold":
|
||||
if n, err := strconv.Atoi(value); err == nil {
|
||||
c.ChargeLimit = &n
|
||||
}
|
||||
case "platform_profile_on_ac":
|
||||
c.ProfileOnAC = unquoted
|
||||
case "platform_profile_on_battery":
|
||||
c.ProfileOnBattery = unquoted
|
||||
case "change_platform_profile_on_ac":
|
||||
c.ChangesProfileOnAC = boolean()
|
||||
case "change_platform_profile_on_battery":
|
||||
c.ChangesProfileOnBatt = boolean()
|
||||
case "ac_command":
|
||||
c.ACCommand = unquoted
|
||||
case "bat_command":
|
||||
c.BatteryCommand = unquoted
|
||||
case "disable_nvidia_powerd_on_battery":
|
||||
c.DisablesPowerdOnBatt = boolean()
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Asusd reads asusd's file; nil when it is not there.
|
||||
func (m *Machine) Asusd() *AsusdConfig {
|
||||
text := m.read("/etc/asusd/asusd.ron")
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
c := ParseAsusdRon(text)
|
||||
return &c
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// What asusctl 6.4 and supergfxctl 5.2 said on the laptop on 2026-10-04.
|
||||
const fanCurveQuiet = `
|
||||
Fan curves for Quiet
|
||||
|
||||
[
|
||||
(
|
||||
fan: CPU,
|
||||
pwm: (2, 0, 10, 20, 35, 55, 80, 100),
|
||||
temp: (35, 45, 50, 55, 60, 65, 70, 80),
|
||||
enabled: true,
|
||||
),
|
||||
(
|
||||
fan: GPU,
|
||||
pwm: (0, 0, 10, 20, 35, 65, 90, 115),
|
||||
temp: (35, 45, 50, 55, 60, 65, 70, 80),
|
||||
enabled: false,
|
||||
),
|
||||
]
|
||||
`
|
||||
|
||||
const asusdRon = `(
|
||||
charge_control_end_threshold: 80,
|
||||
base_charge_control_end_threshold: 0,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: "supergfxctl -m Hybrid",
|
||||
bat_command: "supergfxctl -m Integrated",
|
||||
platform_profile_linked_epp: true,
|
||||
platform_profile_on_battery: Quiet,
|
||||
change_platform_profile_on_battery: true,
|
||||
platform_profile_on_ac: Balanced,
|
||||
change_platform_profile_on_ac: true,
|
||||
ac_profile_tunings: {
|
||||
Quiet: (
|
||||
enabled: false,
|
||||
group: {},
|
||||
),
|
||||
},
|
||||
)`
|
||||
|
||||
func TestAsusctlsAnswersAreRead(t *testing.T) {
|
||||
p, err := ParseProfileGet(profileGetBalanced)
|
||||
if err != nil || p.Active != "Balanced" || p.OnAC != "Balanced" || p.Battery != "Quiet" {
|
||||
t.Fatalf("%+v %v", p, err)
|
||||
}
|
||||
if _, err := ParseProfileGet("something else"); err == nil {
|
||||
t.Fatal("an answer with no profile was read as one")
|
||||
}
|
||||
if l, err := ParseLeds("Current keyboard led brightness: High\n"); err != nil || l != "high" {
|
||||
t.Fatalf("%q %v", l, err)
|
||||
}
|
||||
curves := ParseFanCurves(fanCurveQuiet)
|
||||
if len(curves) != 2 || curves[0].Fan != "CPU" || curves[0].PWM[7] != 100 || curves[0].Temp[0] != 35 || curves[1].Enabled {
|
||||
t.Fatalf("%+v", curves)
|
||||
}
|
||||
if got := ParseSupported("[Integrated, Hybrid, AsusMuxDgpu]\n"); strings.Join(got, ",") != "Integrated,Hybrid,AsusMuxDgpu" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAsusdsFileIsReadForWhatDecidesTheModulesCodeAndNothingNested(t *testing.T) {
|
||||
c := ParseAsusdRon(asusdRon)
|
||||
if *c.ChargeLimit != 80 || c.ProfileOnAC != "Balanced" || c.ProfileOnBattery != "Quiet" ||
|
||||
c.ACCommand != "supergfxctl -m Hybrid" || c.BatteryCommand != "supergfxctl -m Integrated" ||
|
||||
!*c.ChangesProfileOnAC || !*c.DisablesPowerdOnBatt {
|
||||
t.Fatalf("%+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMissingVendorClientIsNamedWithWhyItIsMissing(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.fails["supergfxctl"] = notFound
|
||||
_, err := f.machine().GPU(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "research 027") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
f.fails["asusctl"] = notFound
|
||||
_, err = f.machine().Profile(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "package resource installs it") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGPUModeIsSetOnlyWhenTheMachineSupportsItAndAsusdsSwitchingIsSaid(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["supergfxctl -g"] = "Hybrid\n"
|
||||
f.answers["supergfxctl -s"] = "[Integrated, Hybrid, AsusMuxDgpu]\n"
|
||||
f.file("/etc/asusd/asusd.ron", asusdRon)
|
||||
m := f.machine()
|
||||
if _, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "Vfio"}); err == nil {
|
||||
t.Fatal("an unsupported mode was accepted")
|
||||
}
|
||||
out, err := GPUModeTool(context.Background(), m, map[string]any{"mode": "integrated"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.called("supergfxctl -m Integrated") {
|
||||
t.Fatalf("calls %v", f.calls)
|
||||
}
|
||||
if _, said := out.(map[string]any)["asusd_switches_it"]; !said {
|
||||
t.Fatalf("asusd's own switching of the mode was not said: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheChargeLimitIsBoundedAndSetThroughAsusd(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["asusctl battery info"] = "Current battery charge limit: 60%\n"
|
||||
m := f.machine()
|
||||
for _, bad := range []any{float64(10), float64(101), "x", 55.5} {
|
||||
if _, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": bad}); err == nil {
|
||||
t.Errorf("limit %v was accepted", bad)
|
||||
}
|
||||
}
|
||||
out, err := ChargeLimitTool(context.Background(), m, map[string]any{"limit": float64(60)})
|
||||
if err != nil || !f.called("asusctl battery limit 60") || out.(map[string]any)["asusd_limit_percent"] != 60 {
|
||||
t.Fatalf("%+v %v %v", out, err, f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAProfileSetByToolIsHeldAndAnUnknownOneRefused(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.onMains()
|
||||
f.answers["asusctl profile get"] = profileGetBalanced
|
||||
m := f.machine()
|
||||
sw := NewSwitcher(m, nil)
|
||||
if _, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "Turbo"}); err == nil {
|
||||
t.Fatal("an unknown profile was accepted")
|
||||
}
|
||||
out, err := ProfileTool(context.Background(), m, sw, map[string]any{"profile": "performance", "hold_minutes": float64(30)})
|
||||
if err != nil || !f.called("asusctl profile set Performance") {
|
||||
t.Fatalf("%v %v", err, f.calls)
|
||||
}
|
||||
if _, held := out.(map[string]any)["held_until"]; !held {
|
||||
t.Fatalf("not held: %+v", out)
|
||||
}
|
||||
if r := sw.Report(); r.Held != "Performance" {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Check is one thing the module expects of the machine, and whether it holds.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// CheckReport is what zephyrus_check answers. NotChecked says what it did not look at, because a
|
||||
// check that reads as clean while skipping something is the predecessor's verifier again.
|
||||
type CheckReport struct {
|
||||
Model string `json:"model"`
|
||||
Checks []Check `json:"checks"`
|
||||
Failing int `json:"failing"`
|
||||
NotChecked []string `json:"not_checked"`
|
||||
}
|
||||
|
||||
var (
|
||||
pacmanVersion = regexp.MustCompile(`(?m)^Version\s*:\s*(\S+)`)
|
||||
pacmanPackager = regexp.MustCompile(`(?m)^Packager\s*:\s*(.+)$`)
|
||||
nvidiaParam = regexp.MustCompile(`(?m)^(\w+):\s*(\S+)`)
|
||||
)
|
||||
|
||||
// ParseNvidiaParams reads /proc/driver/nvidia/params.
|
||||
func ParseNvidiaParams(text string) map[string]string {
|
||||
out := map[string]string{}
|
||||
for _, g := range nvidiaParam.FindAllStringSubmatch(text, -1) {
|
||||
out[g[1]] = g[2]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// predecessorProcess finds a running process whose command line names the predecessor's script.
|
||||
func (m *Machine) predecessorProcess(name string) (int, bool) {
|
||||
for _, dir := range m.glob("/proc/[0-9]*") {
|
||||
cmd := strings.ReplaceAll(m.read(dir+"/cmdline"), "\x00", " ")
|
||||
if strings.Contains(cmd, "/"+name) && !strings.Contains(cmd, "zephyrus") {
|
||||
var pid int
|
||||
fmt.Sscanf(filepath.Base(dir), "%d", &pid)
|
||||
return pid, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func (m *Machine) unitIs(ctx context.Context, verb, unit string) string {
|
||||
out, _ := m.Run(ctx, "systemctl", verb, unit)
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
// Check reads every expectation and reports each.
|
||||
func (m *Machine) Check(ctx context.Context, sw *Switcher) CheckReport {
|
||||
r := CheckReport{Model: m.Model(), NotChecked: []string{
|
||||
"the fan curves (asusd's own, read them with zephyrus_fan_curves)",
|
||||
"whether the initramfs carries the NVIDIA options (they are read from the running driver instead)",
|
||||
"the vendor keys themselves (press them)",
|
||||
}}
|
||||
add := func(name string, ok bool, format string, a ...any) {
|
||||
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Detail: fmt.Sprintf(format, a...)})
|
||||
if !ok {
|
||||
r.Failing++
|
||||
}
|
||||
}
|
||||
add("model", m.ThisModel(), "the firmware reports %q; this module is for %q", r.Model, ModelFamily)
|
||||
|
||||
// asusctl: present, and from the distribution rather than a local build.
|
||||
if info, err := m.Run(ctx, "pacman", "-Qi", "asusctl"); err != nil {
|
||||
add("asusctl package", false, "not installed: %v", err)
|
||||
} else {
|
||||
v, p := "", ""
|
||||
if g := pacmanVersion.FindStringSubmatch(info); g != nil {
|
||||
v = g[1]
|
||||
}
|
||||
if g := pacmanPackager.FindStringSubmatch(info); g != nil {
|
||||
p = strings.TrimSpace(g[1])
|
||||
}
|
||||
local := p == "Unknown Packager"
|
||||
add("asusctl package", !local, "version %s, packager %s%s", v, p,
|
||||
map[bool]string{true: "; a local build — the distribution's package replaces it at the next upgrade (pacman -S asusctl)", false: ""}[local])
|
||||
}
|
||||
for _, foreign := range []string{"supergfxctl", "triggerhappy"} {
|
||||
_, err := m.Run(ctx, "pacman", "-Q", foreign)
|
||||
add(foreign+" package", err == nil, "%s; not in the distribution's repositories, kept as found (novox/hq research 027, question 1)",
|
||||
map[bool]string{true: "installed", false: "NOT installed"}[err == nil])
|
||||
}
|
||||
for _, unit := range []string{"asusd.service", "supergfxd.service", "triggerhappy.service"} {
|
||||
state := m.unitIs(ctx, "is-active", unit)
|
||||
add(unit, state == "active", "%s", state)
|
||||
}
|
||||
powerd := m.unitIs(ctx, "is-enabled", "nvidia-powerd.service")
|
||||
add("nvidia-powerd.service", powerd == "masked" || powerd == "disabled" || powerd == "" || strings.Contains(powerd, "not-found"),
|
||||
"%s; the module's drop-in keeps it from starting unless the kernel command line says zephyrus.nvidia-powerd", orNone(powerd))
|
||||
wants, _ := m.Run(ctx, "systemctl", "show", "-p", "Wants", "systemd-suspend.service")
|
||||
add("nvidia suspend and resume", strings.Contains(wants, "nvidia-suspend.service") && strings.Contains(wants, "nvidia-resume.service"),
|
||||
"systemd-suspend.service %s", strings.TrimSpace(wants))
|
||||
|
||||
// The touchpad reset after waking is this module's contribution to node-power's after-wake moment
|
||||
// (novox/hq ADR 0211), placed in the power module's moment file under a "# asus-zephyrus-g14" line.
|
||||
afterWake := m.read("/etc/mesh-power/moments/after-wake")
|
||||
placed := strings.Contains(afterWake, "# asus-zephyrus-g14\n") && strings.Contains(afterWake, "zephyrus-touchpad reset")
|
||||
add("touchpad after resume", placed,
|
||||
"the reset is placed in the power module's after-wake moment: %v (it needs the power module on this machine)", placed)
|
||||
if uid := m.triggerhappyUID(); uid < 0 {
|
||||
add("triggerhappy as the account", false, "no thd process runs: the vendor keys do nothing")
|
||||
} else {
|
||||
add("triggerhappy as the account", uid == operatorUID(), "thd runs as uid %d; the operator's account is %d (the module's drop-in passes --user)", uid, operatorUID())
|
||||
}
|
||||
refs := m.asUserReferences()
|
||||
add("no as-user", len(refs) == 0, "%s", orNone(map[bool]string{true: "", false: "the predecessor's as-user is still named in " + strings.Join(refs, ", ") +
|
||||
": it su-s to a named person on a guessed display and sources a file of secrets"}[len(refs) == 0]))
|
||||
|
||||
params := ParseNvidiaParams(m.read("/proc/driver/nvidia/params"))
|
||||
if len(params) == 0 {
|
||||
add("nvidia options", false, "the NVIDIA driver is not loaded (no /proc/driver/nvidia/params)")
|
||||
} else {
|
||||
add("nvidia options", params["PreserveVideoMemoryAllocations"] == "1" && params["DynamicPowerManagement"] == "0",
|
||||
"PreserveVideoMemoryAllocations=%s DynamicPowerManagement=%s (want 1 and 0; a change applies when the driver loads again)",
|
||||
params["PreserveVideoMemoryAllocations"], params["DynamicPowerManagement"])
|
||||
}
|
||||
|
||||
for _, b := range m.Batteries() {
|
||||
ok := b.LimitPercent != nil && *b.LimitPercent == ChargeLimitPercent
|
||||
have := "unknown"
|
||||
if b.LimitPercent != nil {
|
||||
have = fmt.Sprintf("%d%%", *b.LimitPercent)
|
||||
}
|
||||
add("charge limit", ok, "%s is %s, the module's is %d%%", b.Name, have, ChargeLimitPercent)
|
||||
}
|
||||
|
||||
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
|
||||
add("one authority over the GPU mode", false,
|
||||
"asusd runs %q on mains and %q on battery: it switches the GPU mode on every change of power source, "+
|
||||
"so a mode set with zephyrus_gpu_mode lasts until the next one. Clear ac_command and bat_command in /etc/asusd/asusd.ron (asusd's file) to make it the operator's alone",
|
||||
c.ACCommand, c.BatteryCommand)
|
||||
}
|
||||
if out, err := m.Run(ctx, "journalctl", "-b", "-u", "supergfxd.service", "-g", "invalid variant", "-n", "1", "-q", "-o", "cat"); err == nil && strings.TrimSpace(out) != "" {
|
||||
add("supergfxd and logind", false, "supergfxd cannot read logind's sessions this boot (%s): a mode change that needs a logout times out", strings.TrimSpace(out))
|
||||
}
|
||||
|
||||
if pid, ok := m.predecessorProcess("auto-profile"); ok {
|
||||
add("one profile switcher", false, "the predecessor's auto-profile still runs (pid %d) and switches the profile every five seconds; "+
|
||||
"stop it: systemctl --user disable --now auto-profile.service", pid)
|
||||
} else {
|
||||
add("one profile switcher", true, "no predecessor auto-profile is running")
|
||||
}
|
||||
if sw != nil {
|
||||
rep := sw.Report()
|
||||
add("profile switcher", rep.Running, "%s", orNone(firstNonEmpty(rep.Disabled, rep.LastError, "woken by "+rep.Watching)))
|
||||
}
|
||||
if home := os.Getenv("MESH_OPERATOR_HOME"); home != "" {
|
||||
var left []string
|
||||
for _, p := range PredecessorHomeFiles {
|
||||
if _, err := os.Stat(filepath.Join(m.Root, home, p)); err == nil {
|
||||
left = append(left, "~/"+p)
|
||||
}
|
||||
}
|
||||
add("predecessor files in the home", len(left) == 0, "%s", orNone(strings.Join(left, ", ")))
|
||||
} else {
|
||||
r.NotChecked = append(r.NotChecked, "the predecessor's files in the operator's home (MESH_OPERATOR_HOME is not set)")
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// PredecessorHomeFiles are what the predecessor placed in the operator's home for this model and this
|
||||
// module replaces. The mesh removes nothing it did not make (novox/hq ADR 0182): the operator does,
|
||||
// once, and this list is how the check knows.
|
||||
var PredecessorHomeFiles = []string{
|
||||
"scripts/auto-profile",
|
||||
".config/systemd/user/auto-profile.service",
|
||||
"scripts/asus-bright",
|
||||
"scripts/asusctl-kbd-bright",
|
||||
"scripts/xrandr-bright",
|
||||
"scripts/media-control",
|
||||
"scripts/xinput-reset-touchpad",
|
||||
".config/i3/scripts/kbd-brightness-notify.sh",
|
||||
"scripts/.screenlayouts/orden-workspaces.sh",
|
||||
}
|
||||
|
||||
func orNone(s string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return "none"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func firstNonEmpty(ss ...string) string {
|
||||
for _, s := range ss {
|
||||
if s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MinPanelPercent is the floor a brightness change never goes below: a panel at zero is a black
|
||||
// screen that looks like a dead machine, and the keys cannot be seen to bring it back.
|
||||
const MinPanelPercent = 1
|
||||
|
||||
// Panel is the internal display's backlight.
|
||||
type Panel struct {
|
||||
Device string `json:"device"`
|
||||
Percent float64 `json:"percent"`
|
||||
Raw int64 `json:"raw"`
|
||||
Max int64 `json:"max"`
|
||||
Others []string `json:"other_backlights,omitempty"`
|
||||
}
|
||||
|
||||
// panelDevice chooses the backlight that drives the internal panel.
|
||||
//
|
||||
// **This model registers two.** In hybrid mode the integrated GPU drives the panel (amdgpu_bl1,
|
||||
// beneath the eDP connector) and the discrete GPU's driver registers one of its own (nvidia_0) that
|
||||
// moves nothing. The predecessor's scripts named amdgpu_bl1 literally, which is right until the GPU
|
||||
// mode puts the panel on the other GPU. The one that sits under an eDP connector is the panel's; failing
|
||||
// that, the kernel's own preference: firmware, then platform, then raw.
|
||||
func (m *Machine) panelDevice() (string, []string, error) {
|
||||
all := m.glob("/sys/class/backlight/*")
|
||||
if len(all) == 0 {
|
||||
return "", nil, fmt.Errorf("this machine has no backlight in /sys/class/backlight")
|
||||
}
|
||||
names := make([]string, 0, len(all))
|
||||
for _, d := range all {
|
||||
names = append(names, path.Base(d))
|
||||
}
|
||||
sort.Strings(names)
|
||||
rank := func(name string) int {
|
||||
dir := "/sys/class/backlight/" + name
|
||||
if target, err := os.Readlink(m.path(dir)); err == nil && strings.Contains(target, "-eDP-") {
|
||||
return 0
|
||||
}
|
||||
switch m.read(dir + "/type") {
|
||||
case "firmware":
|
||||
return 1
|
||||
case "platform":
|
||||
return 2
|
||||
}
|
||||
return 3
|
||||
}
|
||||
best := names[0]
|
||||
for _, n := range names[1:] {
|
||||
if rank(n) < rank(best) {
|
||||
best = n
|
||||
}
|
||||
}
|
||||
var others []string
|
||||
for _, n := range names {
|
||||
if n != best {
|
||||
others = append(others, n)
|
||||
}
|
||||
}
|
||||
return best, others, nil
|
||||
}
|
||||
|
||||
// PanelBrightness reads the panel.
|
||||
func (m *Machine) PanelBrightness() (Panel, error) {
|
||||
dev, others, err := m.panelDevice()
|
||||
if err != nil {
|
||||
return Panel{}, err
|
||||
}
|
||||
dir := "/sys/class/backlight/" + dev
|
||||
raw, ok1 := m.readInt(dir + "/brightness")
|
||||
max, ok2 := m.readInt(dir + "/max_brightness")
|
||||
if !ok1 || !ok2 || max <= 0 {
|
||||
return Panel{}, fmt.Errorf("%s does not say its brightness", dir)
|
||||
}
|
||||
return Panel{Device: dev, Raw: raw, Max: max, Percent: round1(float64(raw) / float64(max) * 100), Others: others}, nil
|
||||
}
|
||||
|
||||
// PanelTarget turns a request — "40", "40%", "+5", "-10" — into the percentage to set, clamped to
|
||||
// [MinPanelPercent, 100].
|
||||
func PanelTarget(current float64, request string) (float64, error) {
|
||||
r := strings.TrimSuffix(strings.TrimSpace(request), "%")
|
||||
if r == "" {
|
||||
return 0, fmt.Errorf("panel needs a percentage (40) or a step (+5, -5)")
|
||||
}
|
||||
n, err := strconv.ParseFloat(r, 64)
|
||||
if err != nil || math.IsNaN(n) || math.IsInf(n, 0) {
|
||||
return 0, fmt.Errorf("panel %q is not a percentage or a step", request)
|
||||
}
|
||||
target := n
|
||||
if strings.HasPrefix(r, "+") || strings.HasPrefix(r, "-") {
|
||||
target = current + n
|
||||
}
|
||||
return math.Max(MinPanelPercent, math.Min(100, target)), nil
|
||||
}
|
||||
|
||||
// SetPanel sets the panel to a percentage.
|
||||
func (m *Machine) SetPanel(ctx context.Context, request string) (Panel, error) {
|
||||
p, err := m.PanelBrightness()
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
target, err := PanelTarget(p.Percent, request)
|
||||
if err != nil {
|
||||
return p, err
|
||||
}
|
||||
raw := int64(math.Round(target / 100 * float64(p.Max)))
|
||||
if raw < 1 {
|
||||
raw = 1
|
||||
}
|
||||
if err := m.write(ctx, "/sys/class/backlight/"+p.Device+"/brightness", strconv.FormatInt(raw, 10)); err != nil {
|
||||
return p, err
|
||||
}
|
||||
return m.PanelBrightness()
|
||||
}
|
||||
|
||||
// Keyboard is the keyboard's backlight.
|
||||
type Keyboard struct {
|
||||
Device string `json:"device"`
|
||||
Level string `json:"level"`
|
||||
Value int64 `json:"value"`
|
||||
Max int64 `json:"max"`
|
||||
}
|
||||
|
||||
// KeyboardBrightness reads the keyboard backlight from the kernel.
|
||||
func (m *Machine) KeyboardBrightness() (Keyboard, error) {
|
||||
found := m.glob("/sys/class/leds/*kbd_backlight*")
|
||||
if len(found) == 0 {
|
||||
return Keyboard{}, fmt.Errorf("this machine has no keyboard backlight in /sys/class/leds")
|
||||
}
|
||||
dir := found[0]
|
||||
v, ok1 := m.readInt(dir + "/brightness")
|
||||
max, ok2 := m.readInt(dir + "/max_brightness")
|
||||
if !ok1 || !ok2 {
|
||||
return Keyboard{}, fmt.Errorf("%s does not say its brightness", dir)
|
||||
}
|
||||
k := Keyboard{Device: path.Base(dir), Value: v, Max: max}
|
||||
if max == int64(len(KeyboardLevels)-1) && v >= 0 && v <= max {
|
||||
k.Level = KeyboardLevels[v]
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// KeyboardTarget turns a request — off/low/med/high, 0-3, "+", "-" — into asusd's level name.
|
||||
func KeyboardTarget(current int64, request string) (string, error) {
|
||||
r := strings.ToLower(strings.TrimSpace(request))
|
||||
switch r {
|
||||
case "medium":
|
||||
r = "med"
|
||||
case "+", "up":
|
||||
r = strconv.FormatInt(min64(current+1, int64(len(KeyboardLevels)-1)), 10)
|
||||
case "-", "down":
|
||||
r = strconv.FormatInt(max64(current-1, 0), 10)
|
||||
}
|
||||
for _, l := range KeyboardLevels {
|
||||
if r == l {
|
||||
return l, nil
|
||||
}
|
||||
}
|
||||
if n, err := strconv.Atoi(r); err == nil && n >= 0 && n < len(KeyboardLevels) {
|
||||
return KeyboardLevels[n], nil
|
||||
}
|
||||
return "", fmt.Errorf("keyboard %q is not one of off, low, med, high, 0-3, + or -", request)
|
||||
}
|
||||
|
||||
// SetKeyboard has asusd set the keyboard backlight, so its own record of the level stays true.
|
||||
func (m *Machine) SetKeyboard(ctx context.Context, request string) (Keyboard, error) {
|
||||
k, err := m.KeyboardBrightness()
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
level, err := KeyboardTarget(k.Value, request)
|
||||
if err != nil {
|
||||
return k, err
|
||||
}
|
||||
if _, err := m.Run(ctx, "asusctl", "leds", "set", level); err != nil {
|
||||
return k, vendor("asusctl", err)
|
||||
}
|
||||
return m.KeyboardBrightness()
|
||||
}
|
||||
|
||||
func min64(a, b int64) int64 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func max64(a, b int64) int64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// backlight makes a backlight the way sysfs does: a link from /sys/class/backlight into the device
|
||||
// tree, which is where the eDP connector shows.
|
||||
func (f *fake) backlight(name, device string, raw, max string) {
|
||||
dev := "/sys/devices/" + device + "/" + name
|
||||
f.file(dev+"/brightness", raw)
|
||||
f.file(dev+"/max_brightness", max)
|
||||
f.file(dev+"/type", "raw")
|
||||
link := filepath.Join(f.root, "/sys/class/backlight", name)
|
||||
os.MkdirAll(filepath.Dir(link), 0o755)
|
||||
if err := os.Symlink(filepath.Join(f.root, dev), link); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThePanelIsTheBacklightUnderTheEDPConnectorNotTheDiscreteGPUs(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.backlight("amdgpu_bl1", "pci0000:00/0000:65:00.0/drm/card1/card1-eDP-1", "199500", "399000")
|
||||
f.backlight("nvidia_0", "pci0000:00/0000:01:00.0/backlight", "100", "100")
|
||||
p, err := f.machine().PanelBrightness()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Device != "amdgpu_bl1" || p.Percent != 50 || len(p.Others) != 1 || p.Others[0] != "nvidia_0" {
|
||||
t.Fatalf("%+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPanelRequestIsAPercentageOrAStepAndNeverGoesDark(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
cur float64
|
||||
req string
|
||||
want float64
|
||||
}{{50, "40", 40}, {50, "40%", 40}, {50, "+5", 55}, {50, "-10", 40}, {3, "-10", 1}, {98, "+5", 100}, {50, "0", 1}} {
|
||||
got, err := PanelTarget(c.cur, c.req)
|
||||
if err != nil || got != c.want {
|
||||
t.Errorf("%v %q: %v %v, want %v", c.cur, c.req, got, err, c.want)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "bright", "NaN"} {
|
||||
if _, err := PanelTarget(50, bad); err == nil {
|
||||
t.Errorf("%q was accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettingThePanelWritesTheRawValue(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.backlight("amdgpu_bl1", "card1-eDP-1", "399000", "399000")
|
||||
p, err := f.machine().SetPanel(context.Background(), "25")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(f.root, "/sys/devices/card1-eDP-1/amdgpu_bl1/brightness"))
|
||||
if strings.TrimSpace(string(raw)) != "99750" || p.Percent != 25 {
|
||||
t.Fatalf("wrote %q, read back %+v", raw, p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheKeyboardIsSetThroughAsusdByLevel(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.file("/sys/class/leds/asus::kbd_backlight/brightness", "1")
|
||||
f.file("/sys/class/leds/asus::kbd_backlight/max_brightness", "3")
|
||||
k, err := f.machine().KeyboardBrightness()
|
||||
if err != nil || k.Level != "low" {
|
||||
t.Fatalf("%+v %v", k, err)
|
||||
}
|
||||
if _, err := f.machine().SetKeyboard(context.Background(), "+"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.called("asusctl leds set med") {
|
||||
t.Fatalf("calls: %v", f.calls)
|
||||
}
|
||||
for req, want := range map[string]string{"high": "high", "0": "off", "medium": "med", "-": "off"} {
|
||||
if got, err := KeyboardTarget(1, req); err != nil || got != want {
|
||||
t.Errorf("%q: %q %v", req, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := KeyboardTarget(1, "7"); err == nil {
|
||||
t.Error("level 7 was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fake is a machine for a test: a tree standing in for /, and a runner answering from a table and
|
||||
// recording every command it was asked to run.
|
||||
type fake struct {
|
||||
t *testing.T
|
||||
root string
|
||||
mu sync.Mutex
|
||||
answers map[string]string
|
||||
fails map[string]error
|
||||
calls []string
|
||||
}
|
||||
|
||||
func newFake(t *testing.T) *fake {
|
||||
t.Helper()
|
||||
return &fake{t: t, root: t.TempDir(), answers: map[string]string{}, fails: map[string]error{}}
|
||||
}
|
||||
|
||||
func (f *fake) machine() *Machine { return &Machine{Root: f.root, Run: f.run} }
|
||||
|
||||
func (f *fake) run(_ context.Context, name string, args ...string) (string, error) {
|
||||
line := strings.TrimSpace(name + " " + strings.Join(args, " "))
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.calls = append(f.calls, line)
|
||||
if err, ok := f.fails[line]; ok {
|
||||
return "", err
|
||||
}
|
||||
if out, ok := f.answers[line]; ok {
|
||||
return out, nil
|
||||
}
|
||||
if err, ok := f.fails[name]; ok {
|
||||
return "", err
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (f *fake) called(line string) bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
for _, c := range f.calls {
|
||||
if c == line {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (f *fake) callsLike(prefix string) []string {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
var out []string
|
||||
for _, c := range f.calls {
|
||||
if strings.HasPrefix(c, prefix) {
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// file writes a file under the fake root.
|
||||
func (f *fake) file(path, content string) {
|
||||
f.t.Helper()
|
||||
full := filepath.Join(f.root, path)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// supply writes one power supply's attributes.
|
||||
func (f *fake) supply(name string, attrs map[string]string) {
|
||||
for k, v := range attrs {
|
||||
f.file("/sys/class/power_supply/"+name+"/"+k, v+"\n")
|
||||
}
|
||||
}
|
||||
|
||||
// onMains and onBattery are this model's two states as measured on 2026-10-04.
|
||||
func (f *fake) onMains() {
|
||||
f.supply("ACAD", map[string]string{"type": "Mains", "online": "1"})
|
||||
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Not charging", "capacity": "80"})
|
||||
}
|
||||
|
||||
func (f *fake) onBattery() {
|
||||
f.supply("ACAD", map[string]string{"type": "Mains", "online": "0"})
|
||||
f.supply("BAT1", map[string]string{"type": "Battery", "status": "Discharging", "capacity": "79"})
|
||||
}
|
||||
|
||||
var notFound = &exec.Error{Name: "x", Err: exec.ErrNotFound}
|
||||
|
||||
const profileGetBalanced = "Active profile: Balanced\n\nAC profile Balanced\nBattery profile Quiet\n"
|
||||
@@ -0,0 +1,192 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Key is one custom key on the laptop: what it is, what runs, and where that is defined.
|
||||
type Key struct {
|
||||
Key string `json:"key"`
|
||||
Physical string `json:"physical,omitempty"`
|
||||
When string `json:"when,omitempty"`
|
||||
Runs string `json:"runs"`
|
||||
From string `json:"from"`
|
||||
}
|
||||
|
||||
// KeysReport is what zephyrus_keys answers.
|
||||
type KeysReport struct {
|
||||
Keys []Key `json:"keys"`
|
||||
Warnings []string `json:"warnings"`
|
||||
NotRead []string `json:"not_read"`
|
||||
}
|
||||
|
||||
// TriggerDir is triggerhappy's directory of trigger files; the module owns one file in it.
|
||||
const TriggerDir = "/etc/triggerhappy/triggers.d"
|
||||
|
||||
// I3Config is the window manager's configuration, relative to the account's home. This module's lines
|
||||
// are its contribution to node-display-session (novox/hq ADR 0212), placed there by the i3 module
|
||||
// under a line that names this module.
|
||||
const I3Config = ".config/i3/config"
|
||||
|
||||
// ModuleName is the line the controller writes before this module's contributed lines.
|
||||
const ModuleName = "asus-zephyrus-g14"
|
||||
|
||||
// ownSection is this module's contributed lines in a placed file: from the line naming it to the next
|
||||
// line naming another module, a section header, or the file's end.
|
||||
func ownSection(text string) []string {
|
||||
var out []string
|
||||
in := false
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if t == "# "+ModuleName {
|
||||
in = true
|
||||
continue
|
||||
}
|
||||
if !in {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(t, "####") || (strings.HasPrefix(t, "# ") && isModuleLine(strings.TrimPrefix(t, "# "))) {
|
||||
break
|
||||
}
|
||||
out = append(out, line)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isModuleLine is a comment that is one catalogue module's name: lower case, digits and dashes.
|
||||
func isModuleLine(s string) bool {
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// physicalKeys names the key behind an evdev code, as far as it is known on this model. The media
|
||||
// codes are the M4 key and Fn+F4/F5 together; which code is which key was not recorded.
|
||||
var physicalKeys = map[string]string{
|
||||
"KEY_PROG1": "a media key (M4, Fn+F4 or Fn+F5)",
|
||||
"KEY_PROG3": "a media key (M4, Fn+F4 or Fn+F5)",
|
||||
"KEY_PROG4": "a media key (M4, Fn+F4 or Fn+F5)",
|
||||
"KEY_BRIGHTNESSDOWN": "Fn+F7",
|
||||
"KEY_BRIGHTNESSUP": "Fn+F8",
|
||||
"KEY_F21": "Fn+F10 (touchpad)",
|
||||
"$mod+Shift+s": "Fn+F6 (screenshot; the firmware sends Super+Shift+S)",
|
||||
"$mod+p": "Fn+F9 (display; the firmware sends Super+P)",
|
||||
}
|
||||
|
||||
// firmwareKeys are handled below any configuration file.
|
||||
var firmwareKeys = []Key{
|
||||
{Key: "Fn+F2 / Fn+F3", Physical: "keyboard backlight", Runs: "the firmware and asusd; zephyrus-kbd-notify shows the level", From: "firmware"},
|
||||
}
|
||||
|
||||
var (
|
||||
triggerLine = regexp.MustCompile(`^(\S+)\s+([0-9]+)\s+(.+)$`)
|
||||
i3Bind = regexp.MustCompile(`^bindsym\s+((?:--\S+\s+)*)(\S+)\s+(.+)$`)
|
||||
i3Exec = regexp.MustCompile(`^exec(?:_always)?\s+(?:--no-startup-id\s+)?(.+)$`)
|
||||
)
|
||||
|
||||
var triggerWhen = map[string]string{"0": "released", "1": "pressed", "2": "held (repeat)"}
|
||||
|
||||
// Keys lists the laptop's custom keys: every triggerhappy trigger, the module's i3 lines and the keys
|
||||
// the firmware handles itself.
|
||||
func (m *Machine) Keys() KeysReport {
|
||||
r := KeysReport{Keys: []Key{}, Warnings: []string{}, NotRead: []string{}}
|
||||
seen := map[string][]string{}
|
||||
files := m.glob(TriggerDir + "/*.conf")
|
||||
sort.Strings(files)
|
||||
if len(files) == 0 {
|
||||
r.Warnings = append(r.Warnings, "no trigger file in "+TriggerDir+": the vendor keys do nothing")
|
||||
}
|
||||
for _, f := range files {
|
||||
for _, line := range strings.Split(m.read(f), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
g := triggerLine.FindStringSubmatch(line)
|
||||
if g == nil {
|
||||
continue
|
||||
}
|
||||
r.Keys = append(r.Keys, Key{Key: g[1], Physical: physicalKeys[g[1]], When: triggerWhen[g[2]], Runs: g[3], From: f})
|
||||
id := g[1] + " " + g[2]
|
||||
seen[id] = append(seen[id], f)
|
||||
}
|
||||
}
|
||||
for id, fs := range seen {
|
||||
if len(fs) > 1 {
|
||||
r.Warnings = append(r.Warnings, fmt.Sprintf("%s is bound in %d places (%s): it fires every one", id, len(fs), strings.Join(fs, ", ")))
|
||||
}
|
||||
}
|
||||
home := os.Getenv("MESH_OPERATOR_HOME")
|
||||
if home == "" {
|
||||
r.NotRead = append(r.NotRead, "the module's i3 lines (MESH_OPERATOR_HOME is not set)")
|
||||
}
|
||||
if home != "" {
|
||||
lines := ownSection(m.read(filepath.Join(home, I3Config)))
|
||||
if len(lines) == 0 {
|
||||
r.Warnings = append(r.Warnings, "~/"+I3Config+" holds no lines of this module's: is the i3 module assigned and pushed?")
|
||||
}
|
||||
from := "~/" + I3Config + " (" + ModuleName + "'s contribution)"
|
||||
for _, line := range lines {
|
||||
line = strings.TrimSpace(line)
|
||||
if g := i3Bind.FindStringSubmatch(line); g != nil {
|
||||
when := "pressed"
|
||||
if strings.Contains(g[1], "--release") {
|
||||
when = "released"
|
||||
}
|
||||
r.Keys = append(r.Keys, Key{Key: g[2], Physical: physicalKeys[g[2]], When: when, Runs: strings.TrimPrefix(strings.TrimPrefix(g[3], "exec "), "--no-startup-id "), From: from})
|
||||
} else if g := i3Exec.FindStringSubmatch(line); g != nil {
|
||||
r.Keys = append(r.Keys, Key{Key: "(session start)", When: "at login", Runs: g[1], From: from})
|
||||
}
|
||||
}
|
||||
}
|
||||
r.Keys = append(r.Keys, firmwareKeys...)
|
||||
sort.Strings(r.Warnings)
|
||||
return r
|
||||
}
|
||||
|
||||
// asUserReferences finds the predecessor's as-user wrapper still named in a trigger, a udev rule or
|
||||
// the module's i3 lines.
|
||||
func (m *Machine) asUserReferences() []string {
|
||||
var at []string
|
||||
for _, pattern := range []string{TriggerDir + "/*.conf", "/etc/udev/rules.d/*.rules", "/etc/systemd/system-sleep/*"} {
|
||||
for _, f := range m.glob(pattern) {
|
||||
if strings.Contains(m.read(f), "as-user") {
|
||||
at = append(at, f)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(at)
|
||||
return at
|
||||
}
|
||||
|
||||
// triggerhappyUID is the real user id the running thd has, or -1 when none runs.
|
||||
func (m *Machine) triggerhappyUID() int {
|
||||
for _, dir := range m.glob("/proc/[0-9]*") {
|
||||
if strings.TrimSpace(m.read(dir+"/comm")) != "thd" {
|
||||
continue
|
||||
}
|
||||
for _, line := range strings.Split(m.read(dir+"/status"), "\n") {
|
||||
if f := strings.Fields(line); len(f) >= 2 && f[0] == "Uid:" {
|
||||
var uid int
|
||||
if _, err := fmt.Sscanf(f[1], "%d", &uid); err == nil {
|
||||
return uid
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// operatorUID is the account the module's code runs as: the runtime runs it as the operator's.
|
||||
var operatorUID = os.Getuid
|
||||
@@ -0,0 +1,113 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func put(t *testing.T, root, p, content string) {
|
||||
t.Helper()
|
||||
full := filepath.Join(root, p)
|
||||
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(full, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// The module's shipped triggers and i3 lines, read back as keys: what each runs and where.
|
||||
func TestKeysListsTriggersI3LinesAndFirmwareKeys(t *testing.T) {
|
||||
f := newFake(t)
|
||||
m := readManifest(t)
|
||||
content := map[string]string{}
|
||||
for _, r := range m.Resources {
|
||||
if c, ok := r["content"].(string); ok {
|
||||
content[r["id"].(string)] = c
|
||||
}
|
||||
}
|
||||
put(t, f.root, TriggerDir+"/mesh.conf", "# asus-zephyrus-g14\n"+m.triggers())
|
||||
home := "/home/operator"
|
||||
t.Setenv("MESH_OPERATOR_HOME", home)
|
||||
// The i3 module's file as the controller composes it: other modules' lines around this one's.
|
||||
var own string
|
||||
for _, c := range m.Contributions {
|
||||
if c.Seat == "node-display-session" {
|
||||
own += c.Content
|
||||
}
|
||||
}
|
||||
put(t, f.root, home+"/"+I3Config, "set $mod Mod4\n# rofi\nbindsym $mod+d exec rofi\n# "+ModuleName+"\n"+own+
|
||||
"# triggerhappy-not-here\nbindsym $mod+Shift+z exec other\n#########################################\ninclude x\n")
|
||||
|
||||
r := f.machine().Keys()
|
||||
got := map[string]Key{}
|
||||
for _, k := range r.Keys {
|
||||
got[k.Key+"|"+k.When] = k
|
||||
}
|
||||
if k := got["KEY_F21|pressed"]; !strings.Contains(k.Runs, "zephyrus-touchpad reset") || k.Physical == "" {
|
||||
t.Errorf("touchpad key: %+v", k)
|
||||
}
|
||||
if k := got["KEY_PROG1|pressed"]; !strings.Contains(k.Runs, "zephyrus-media play-pause") {
|
||||
t.Errorf("media key: %+v", k)
|
||||
}
|
||||
if k := got["$mod+Shift+s|released"]; !strings.Contains(k.Runs, "screenshot") || !strings.Contains(k.Physical, "Fn+F6") {
|
||||
t.Errorf("screenshot key: %+v", k)
|
||||
}
|
||||
if k := got["$mod+p|pressed"]; !strings.Contains(k.Runs, "zephyrus-display order") {
|
||||
t.Errorf("display key: %+v", k)
|
||||
}
|
||||
if k := got["(session start)|at login"]; k.Runs == "" {
|
||||
t.Errorf("no session-start line read")
|
||||
}
|
||||
if k := got["Fn+F2 / Fn+F3|"]; k.From != "firmware" {
|
||||
t.Errorf("firmware keys missing: %+v", r.Keys)
|
||||
}
|
||||
if len(r.Warnings) != 0 || len(r.NotRead) != 0 {
|
||||
t.Errorf("warnings %v, not read %v", r.Warnings, r.NotRead)
|
||||
}
|
||||
if _, err := json.Marshal(r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A key bound in two trigger files fires twice, which is said.
|
||||
func TestKeysWarnsAboutAKeyInTwoTriggerFiles(t *testing.T) {
|
||||
f := newFake(t)
|
||||
put(t, f.root, TriggerDir+"/asus-g14.conf", "KEY_F21\t1\t/x reset\n")
|
||||
put(t, f.root, TriggerDir+"/old.conf", "KEY_F21\t1\t/y reset\n")
|
||||
t.Setenv("MESH_OPERATOR_HOME", "")
|
||||
r := f.machine().Keys()
|
||||
if len(r.Warnings) != 1 || !strings.Contains(r.Warnings[0], "KEY_F21") || len(r.NotRead) != 1 {
|
||||
t.Errorf("warnings %v, not read %v", r.Warnings, r.NotRead)
|
||||
}
|
||||
}
|
||||
|
||||
// The check names what still calls as-user, and whether triggerhappy runs as the account.
|
||||
func TestCheckFindsAsUserAndTriggerhappysAccount(t *testing.T) {
|
||||
f := newFake(t)
|
||||
put(t, f.root, "/etc/udev/rules.d/91-monitor-hotplug.rules", `RUN+="/x/scripts/as-user setsid wizard"`)
|
||||
put(t, f.root, "/proc/4242/comm", "thd\n")
|
||||
put(t, f.root, "/proc/4242/status", "Name:\tthd\nUid:\t0\t0\t0\t0\n")
|
||||
was := operatorUID
|
||||
operatorUID = func() int { return 1000 }
|
||||
defer func() { operatorUID = was }()
|
||||
t.Setenv("MESH_OPERATOR_HOME", "")
|
||||
r := f.machine().Check(context.Background(), nil)
|
||||
by := map[string]Check{}
|
||||
for _, c := range r.Checks {
|
||||
by[c.Name] = c
|
||||
}
|
||||
if c := by["no as-user"]; c.OK || !strings.Contains(c.Detail, "91-monitor-hotplug.rules") {
|
||||
t.Errorf("as-user: %+v", c)
|
||||
}
|
||||
if c := by["triggerhappy as the account"]; c.OK || !strings.Contains(c.Detail, "uid 0") {
|
||||
t.Errorf("triggerhappy: %+v", c)
|
||||
}
|
||||
if c := by["touchpad after resume"]; c.OK {
|
||||
t.Errorf("resume: %+v", c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandTimeout bounds every command a tool or the switcher runs: a vendor daemon that hangs on its
|
||||
// bus must cost a tool call twenty seconds, never the runtime's thirty.
|
||||
const CommandTimeout = 20 * time.Second
|
||||
|
||||
// Runner runs one command and answers its standard output. It is injected so that every tool is
|
||||
// tested against recorded answers rather than this machine's daemons.
|
||||
type Runner func(ctx context.Context, name string, args ...string) (string, error)
|
||||
|
||||
// ExecRunner runs a command on the machine, bounded by CommandTimeout. A failure carries what the
|
||||
// command said on stderr, because "exit status 1" names nothing.
|
||||
func ExecRunner(ctx context.Context, name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, CommandTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return stdout.String(), fmt.Errorf("%s did not answer within %s", name, CommandTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
said := strings.TrimSpace(stderr.String())
|
||||
if said == "" {
|
||||
said = strings.TrimSpace(stdout.String())
|
||||
}
|
||||
if said != "" {
|
||||
return stdout.String(), fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, said)
|
||||
}
|
||||
return stdout.String(), fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err)
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
// Machine is what the module reads and acts on: a filesystem root (the real one, or a test's tree of
|
||||
// /sys and /proc and /etc) and a way to run commands.
|
||||
type Machine struct {
|
||||
Root string
|
||||
Run Runner
|
||||
}
|
||||
|
||||
// Here is the machine this process runs on.
|
||||
func Here() *Machine { return &Machine{Root: "/", Run: ExecRunner} }
|
||||
|
||||
func (m *Machine) path(p string) string { return filepath.Join(m.Root, p) }
|
||||
|
||||
// read is a file's content, trimmed; "" when it cannot be read.
|
||||
func (m *Machine) read(p string) string {
|
||||
b, err := os.ReadFile(m.path(p))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
// readInt is a file holding one integer; ok false when it is absent or not a number.
|
||||
func (m *Machine) readInt(p string) (int64, bool) {
|
||||
s := m.read(p)
|
||||
if s == "" {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.ParseInt(s, 10, 64)
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
func (m *Machine) glob(pattern string) []string {
|
||||
found, _ := filepath.Glob(m.path(pattern))
|
||||
out := make([]string, 0, len(found))
|
||||
for _, f := range found {
|
||||
rel, err := filepath.Rel(m.Root, f)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, "/"+filepath.ToSlash(rel))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// write puts a value into a file of the kernel's (a backlight). Where the account may not write it
|
||||
// — the udev rule that gives the video group the panel has not run yet — it escalates with `sudo -n`,
|
||||
// which never prompts: the operator's account may escalate without one, and when it may not, the
|
||||
// tool says so in sudo's words.
|
||||
func (m *Machine) write(ctx context.Context, p, value string) error {
|
||||
err := os.WriteFile(m.path(p), []byte(value), 0)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrPermission) {
|
||||
return err
|
||||
}
|
||||
if _, serr := m.Run(ctx, "sudo", "-n", "sh", "-c", `printf '%s' "$1" > "$2"`, "sh", value, m.path(p)); serr != nil {
|
||||
return fmt.Errorf("%s is not writable by this account and sudo -n refused: %v", p, serr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notInstalled says a command failed because it is not on this machine at all.
|
||||
func notInstalled(err error) bool { return errors.Is(err, exec.ErrNotFound) }
|
||||
|
||||
// round to one decimal, for watts and percentages a person reads.
|
||||
func round1(f float64) float64 {
|
||||
return float64(int64(f*10+sign(f)*0.5)) / 10
|
||||
}
|
||||
|
||||
func sign(f float64) float64 {
|
||||
if f < 0 {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// The asus-zephyrus-g14 module's Go bundle (novox/hq ADR 0188, ADR 0193, ADR 0198): one process the
|
||||
// node's runtime launches, serving the module's tools over MCP on stdio and running its long-running
|
||||
// code — the platform-profile switcher — beside them.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
m := Here()
|
||||
sw := NewSwitcher(m, func(eventType string, body any) error { return stdio.Emit(eventType, body) })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sw.Run(ctx)
|
||||
// An empty name serves as the module the runtime names (MESH_SERVED_MODULE).
|
||||
if err := stdio.Serve("", Tools(m, sw)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Tools []string `json:"tools"`
|
||||
Emits []string `json:"emits"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
// Contributions to other modules' seats (novox/hq ADR 0212): the vendor keys go to node-hotkeys.
|
||||
Contributions []struct {
|
||||
Seat string `json:"seat"`
|
||||
Kind string `json:"kind"`
|
||||
Content string `json:"content"`
|
||||
} `json:"contributions"`
|
||||
}
|
||||
|
||||
// triggers is the module's contribution to node-hotkeys: its vendor keys.
|
||||
func (m manifest) triggers() string {
|
||||
for _, c := range m.Contributions {
|
||||
if c.Seat == "node-hotkeys" && c.Kind == "trigger" {
|
||||
return c.Content
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m manifest
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestTheManifestNamesExactlyTheToolsTheBundleServes(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
var served []string
|
||||
for _, tool := range Tools(&Machine{Root: t.TempDir(), Run: newFake(t).run}, nil) {
|
||||
served = append(served, tool.Name)
|
||||
}
|
||||
sort.Strings(served)
|
||||
listed := append([]string(nil), m.Tools...)
|
||||
sort.Strings(listed)
|
||||
if strings.Join(served, ",") != strings.Join(listed, ",") {
|
||||
t.Fatalf("served %v, listed %v", served, listed)
|
||||
}
|
||||
if len(m.Emits) != 1 || m.Emits[0] != "profile.switched" {
|
||||
t.Fatalf("emits %v", m.Emits)
|
||||
}
|
||||
}
|
||||
|
||||
// The module names the model, never a node, a person or a user id (novox/hq ADR 0112), and every
|
||||
// trigger it names a service restart or reload on is one of its own resources.
|
||||
func TestTheManifestNamesNoMachineAndItsTriggersExist(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
ids := map[string]bool{}
|
||||
for _, r := range m.Resources {
|
||||
ids[r["id"].(string)] = true
|
||||
}
|
||||
raw, _ := os.ReadFile("../../module.json")
|
||||
for _, banned := range []string{"jochen", "/home/", "/run/user/1000", "\"g14\"", "shanks"} {
|
||||
if strings.Contains(string(raw), banned) {
|
||||
t.Errorf("the manifest says %q", banned)
|
||||
}
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
for _, key := range []string{"restart-on", "reload-on"} {
|
||||
list, _ := r[key].([]any)
|
||||
for _, id := range list {
|
||||
if !ids[id.(string)] {
|
||||
t.Errorf("%s %s names %v, which is not a resource", r["id"], key, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Every trigger runs a script the module ships, and every script parses.
|
||||
func TestTheVendorKeysRunTheModulesOwnScriptsAndTheyParse(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
triggers := m.triggers()
|
||||
if triggers == "" {
|
||||
t.Fatal("no trigger contribution to node-hotkeys")
|
||||
}
|
||||
for _, line := range strings.Split(triggers, "\n") {
|
||||
f := strings.Split(line, "\t")
|
||||
if strings.HasPrefix(line, "#") || len(f) < 3 {
|
||||
continue
|
||||
}
|
||||
script := strings.Fields(f[2])[0]
|
||||
local := filepath.Join("../../files/bin", filepath.Base(script))
|
||||
if !strings.HasPrefix(script, "/usr/local/lib/asus-zephyrus-g14/bin/") {
|
||||
t.Errorf("%s runs %s, which the module does not ship", f[0], script)
|
||||
} else if st, err := os.Stat(local); err != nil || st.Mode()&0o111 == 0 {
|
||||
t.Errorf("%s: %s is missing or not executable", f[0], local)
|
||||
}
|
||||
}
|
||||
scripts, _ := filepath.Glob("../../files/bin/*")
|
||||
if len(scripts) == 0 {
|
||||
t.Fatal("no scripts")
|
||||
}
|
||||
for _, s := range scripts {
|
||||
if out, err := exec.Command("bash", "-n", s).CombinedOutput(); err != nil {
|
||||
t.Errorf("%s: %v %s", s, err, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The policy, as constants until the mesh has settings a module can read (novox/hq issue 168). The
|
||||
// values are the predecessor's, made explicit, and two of its behaviours are changed on purpose:
|
||||
//
|
||||
// - **Sustained, not momentary.** The predecessor boosted on one five-second sample above 50 %: a
|
||||
// compile's first second, a browser's tab restore. Here the load must stay above the line for
|
||||
// SustainSamples samples in a row, and below the lower line as long, before the profile moves.
|
||||
// - **Waiting on a disk is not load.** iowait is counted as idle: a machine stalled on its SSD does
|
||||
// not get faster with a higher power limit, only hotter.
|
||||
const (
|
||||
ProfileOnBattery = "Quiet"
|
||||
ProfileOnAC = "Balanced"
|
||||
ProfileUnderLoad = "Performance"
|
||||
|
||||
CPUHighPercent = 50.0 // on mains, sustained at or above this boosts to ProfileUnderLoad
|
||||
CPULowPercent = 20.0 // and sustained at or below this goes back to ProfileOnAC
|
||||
|
||||
SampleEvery = 10 * time.Second // CPU is sampled only on mains; on battery nothing is sampled
|
||||
SustainSamples = 3 // 30 s above CPUHighPercent to boost
|
||||
RelaxSamples = 3 // 30 s below CPULowPercent to relax
|
||||
|
||||
// SafetyRecheck is how often the power source is read when no event has said it changed: the
|
||||
// kernel's event is the trigger, and this only covers one lost across a suspend.
|
||||
SafetyRecheck = 5 * time.Minute
|
||||
|
||||
// DefaultHold is how long a profile chosen through the profile tool is kept before the switcher
|
||||
// may move it again. A change of power source ends a hold at once.
|
||||
DefaultHold = 60 * time.Minute
|
||||
|
||||
// ChargeLimitPercent is the battery charge limit the module asserts through asusd at start.
|
||||
ChargeLimitPercent = 80
|
||||
)
|
||||
|
||||
// Policy is the switcher's memory of recent load: how many samples in a row were above the upper line
|
||||
// or below the lower one, and whether it is boosted.
|
||||
type Policy struct {
|
||||
Boosted bool `json:"boosted"`
|
||||
Above int `json:"samples_above"`
|
||||
Below int `json:"samples_below"`
|
||||
Recent []float64 `json:"recent_cpu_percent"`
|
||||
BoostedSince time.Time `json:"boosted_since,omitempty"`
|
||||
}
|
||||
|
||||
// Observe takes one CPU sample (busy percent since the previous one) taken on mains.
|
||||
func (p *Policy) Observe(cpu float64, at time.Time) {
|
||||
p.Recent = append(p.Recent, round1(cpu))
|
||||
if len(p.Recent) > 6 {
|
||||
p.Recent = p.Recent[len(p.Recent)-6:]
|
||||
}
|
||||
switch {
|
||||
case cpu >= CPUHighPercent:
|
||||
p.Above++
|
||||
p.Below = 0
|
||||
if !p.Boosted && p.Above >= SustainSamples {
|
||||
p.Boosted = true
|
||||
p.BoostedSince = at
|
||||
}
|
||||
case cpu <= CPULowPercent:
|
||||
p.Below++
|
||||
p.Above = 0
|
||||
if p.Boosted && p.Below >= RelaxSamples {
|
||||
p.Boosted = false
|
||||
p.BoostedSince = time.Time{}
|
||||
}
|
||||
default:
|
||||
// Between the lines: no direction is sustained, and the profile stays where it is.
|
||||
p.Above, p.Below = 0, 0
|
||||
}
|
||||
}
|
||||
|
||||
// Reset forgets the load, for a change of power source.
|
||||
func (p *Policy) Reset() { *p = Policy{} }
|
||||
|
||||
// Decision is what the switcher would choose, and why.
|
||||
type Decision struct {
|
||||
Profile string `json:"profile"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Decide is the policy: battery → ProfileOnBattery; mains → ProfileOnAC, or ProfileUnderLoad while
|
||||
// boosted.
|
||||
func (p *Policy) Decide(src Source) Decision {
|
||||
if !src.OnAC {
|
||||
return Decision{ProfileOnBattery, "on battery (" + src.Reason + ")"}
|
||||
}
|
||||
if p.Boosted {
|
||||
return Decision{ProfileUnderLoad, fmt.Sprintf("on mains (%s) and CPU load sustained at or above %s%% for %d samples of %s",
|
||||
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64), SustainSamples, SampleEvery)}
|
||||
}
|
||||
return Decision{ProfileOnAC, fmt.Sprintf("on mains (%s), and CPU load not sustained at or above %s%%",
|
||||
src.Reason, strconv.FormatFloat(CPUHighPercent, 'f', -1, 64))}
|
||||
}
|
||||
|
||||
// CPUTimes is the first line of /proc/stat: total and idle jiffies (iowait counted as idle).
|
||||
type CPUTimes struct{ Total, Idle uint64 }
|
||||
|
||||
// ParseProcStat reads the aggregate cpu line of /proc/stat.
|
||||
func ParseProcStat(text string) (CPUTimes, error) {
|
||||
line := strings.SplitN(text, "\n", 2)[0]
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 6 || f[0] != "cpu" {
|
||||
return CPUTimes{}, fmt.Errorf("/proc/stat does not start with the cpu line")
|
||||
}
|
||||
var t CPUTimes
|
||||
for i, s := range f[1:] {
|
||||
if i >= 8 { // user nice system idle iowait irq softirq steal; guest is already in user
|
||||
break
|
||||
}
|
||||
n, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return CPUTimes{}, fmt.Errorf("/proc/stat: %v", err)
|
||||
}
|
||||
t.Total += n
|
||||
if i == 3 || i == 4 {
|
||||
t.Idle += n
|
||||
}
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Busy is the percentage of time not idle between two readings.
|
||||
func Busy(before, after CPUTimes) (float64, bool) {
|
||||
if after.Total <= before.Total {
|
||||
return 0, false
|
||||
}
|
||||
total := float64(after.Total - before.Total)
|
||||
idle := float64(after.Idle - before.Idle)
|
||||
return (total - idle) / total * 100, true
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Supply is one entry of /sys/class/power_supply as the kernel reports it.
|
||||
type Supply struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Online *bool `json:"online,omitempty"`
|
||||
}
|
||||
|
||||
// Supplies is every power supply the kernel knows, sorted by name.
|
||||
func (m *Machine) Supplies() []Supply {
|
||||
var out []Supply
|
||||
for _, dir := range m.glob("/sys/class/power_supply/*") {
|
||||
s := Supply{
|
||||
Name: path.Base(dir),
|
||||
Type: m.read(dir + "/type"),
|
||||
Scope: m.read(dir + "/scope"),
|
||||
Status: m.read(dir + "/status"),
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/online"); ok {
|
||||
on := v == 1
|
||||
s.Online = &on
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
// system is a supply that powers this machine. A mouse's or a headset's battery reports scope
|
||||
// Device, and it says nothing about whether the laptop is on mains.
|
||||
func (s Supply) system() bool { return !strings.EqualFold(s.Scope, "Device") }
|
||||
|
||||
// Source is where the machine draws its power from, and why that was concluded.
|
||||
type Source struct {
|
||||
OnAC bool `json:"on_ac"`
|
||||
Source string `json:"source"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// PowerSource decides mains or battery.
|
||||
//
|
||||
// **A battery that says it is discharging wins over any adapter that says it is online.** The
|
||||
// predecessor's script took any `online` file reading 1 as mains, and a USB-C port reports `online`
|
||||
// for things that do not power the machine. The battery's own status is the one fact that cannot be
|
||||
// misread: it discharges exactly when nothing outside is carrying the load. Only when no battery says
|
||||
// so are the adapters asked, and a machine with no system battery at all is on mains.
|
||||
func PowerSource(supplies []Supply) Source {
|
||||
batteries := 0
|
||||
for _, s := range supplies {
|
||||
if s.Type == "Battery" && s.system() {
|
||||
batteries++
|
||||
if strings.EqualFold(s.Status, "Discharging") {
|
||||
return Source{OnAC: false, Source: "battery", Reason: s.Name + " is discharging"}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, s := range supplies {
|
||||
if (s.Type == "Mains" || strings.HasPrefix(s.Type, "USB")) && s.system() && s.Online != nil && *s.Online {
|
||||
return Source{OnAC: true, Source: "ac", Reason: s.Name + " (" + s.Type + ") is online"}
|
||||
}
|
||||
}
|
||||
if batteries == 0 {
|
||||
return Source{OnAC: true, Source: "ac", Reason: "this machine has no system battery"}
|
||||
}
|
||||
return Source{OnAC: false, Source: "battery", Reason: "no mains or USB supply is online"}
|
||||
}
|
||||
|
||||
// Battery is what the battery tool answers.
|
||||
type Battery struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ChargePercent *int64 `json:"charge_percent,omitempty"`
|
||||
EnergyWh *float64 `json:"energy_wh,omitempty"`
|
||||
FullWh *float64 `json:"full_wh,omitempty"`
|
||||
DesignWh *float64 `json:"design_wh,omitempty"`
|
||||
HealthPercent *float64 `json:"health_percent,omitempty"`
|
||||
Cycles *int64 `json:"cycles"`
|
||||
CyclesNote string `json:"cycles_note,omitempty"`
|
||||
LimitPercent *int64 `json:"charge_limit_percent,omitempty"`
|
||||
PowerW *float64 `json:"power_w,omitempty"`
|
||||
HoursRemaining *float64 `json:"hours_remaining,omitempty"`
|
||||
Technology string `json:"technology,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Manufacturer string `json:"manufacturer,omitempty"`
|
||||
}
|
||||
|
||||
// Batteries reads every system battery.
|
||||
func (m *Machine) Batteries() []Battery {
|
||||
var out []Battery
|
||||
for _, s := range m.Supplies() {
|
||||
if s.Type != "Battery" || !s.system() {
|
||||
continue
|
||||
}
|
||||
out = append(out, m.battery(s))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Machine) battery(s Supply) Battery {
|
||||
dir := "/sys/class/power_supply/" + s.Name
|
||||
b := Battery{
|
||||
Name: s.Name, Status: s.Status,
|
||||
Technology: m.read(dir + "/technology"),
|
||||
Model: m.read(dir + "/model_name"),
|
||||
Manufacturer: strings.TrimSpace(m.read(dir + "/manufacturer")),
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/capacity"); ok {
|
||||
b.ChargePercent = &v
|
||||
}
|
||||
// Energy in Wh: energy_* (µWh) where the firmware reports it, else charge_* (µAh) times the
|
||||
// design minimum voltage, which is how upower converts it too.
|
||||
wh := func(energy, charge string) *float64 {
|
||||
if v, ok := m.readInt(dir + "/" + energy); ok {
|
||||
f := round1(float64(v) / 1e6)
|
||||
return &f
|
||||
}
|
||||
c, okc := m.readInt(dir + "/" + charge)
|
||||
volts, okv := m.readInt(dir + "/voltage_min_design")
|
||||
if okc && okv {
|
||||
f := round1(float64(c) * float64(volts) / 1e12)
|
||||
return &f
|
||||
}
|
||||
return nil
|
||||
}
|
||||
b.EnergyWh = wh("energy_now", "charge_now")
|
||||
b.FullWh = wh("energy_full", "charge_full")
|
||||
b.DesignWh = wh("energy_full_design", "charge_full_design")
|
||||
if b.FullWh != nil && b.DesignWh != nil && *b.DesignWh > 0 {
|
||||
h := round1(*b.FullWh / *b.DesignWh * 100)
|
||||
b.HealthPercent = &h
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/cycle_count"); ok && v > 0 {
|
||||
b.Cycles = &v
|
||||
} else {
|
||||
b.CyclesNote = "the firmware does not report a cycle count (it reads 0)"
|
||||
}
|
||||
if v, ok := m.readInt(dir + "/charge_control_end_threshold"); ok {
|
||||
b.LimitPercent = &v
|
||||
}
|
||||
if w := m.batteryWatts(dir); w != nil {
|
||||
b.PowerW = w
|
||||
if strings.EqualFold(s.Status, "Discharging") && b.EnergyWh != nil && *w > 0.5 {
|
||||
h := round1(*b.EnergyWh / *w)
|
||||
b.HoursRemaining = &h
|
||||
}
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// batteryWatts is how much the battery is giving or taking, in watts, unsigned: power_now where the
|
||||
// firmware reports it, else current times voltage.
|
||||
func (m *Machine) batteryWatts(dir string) *float64 {
|
||||
if v, ok := m.readInt(dir + "/power_now"); ok {
|
||||
f := round1(abs(float64(v)) / 1e6)
|
||||
return &f
|
||||
}
|
||||
i, oki := m.readInt(dir + "/current_now")
|
||||
u, oku := m.readInt(dir + "/voltage_now")
|
||||
if oki && oku {
|
||||
f := round1(abs(float64(i)) * float64(u) / 1e12)
|
||||
return &f
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func abs(f float64) float64 {
|
||||
if f < 0 {
|
||||
return -f
|
||||
}
|
||||
return f
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func on(b bool) *bool { return &b }
|
||||
|
||||
func TestADischargingBatteryWinsOverAnAdapterThatSaysOnline(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "BAT1", Type: "Battery", Status: "Discharging"},
|
||||
{Name: "ucsi-source-psy-USBC000:001", Type: "USB", Scope: "System", Online: on(true)},
|
||||
})
|
||||
if got.OnAC {
|
||||
t.Fatalf("a USB-C port reporting online while the battery discharges was read as mains: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMainsOnlineIsAC(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "ACAD", Type: "Mains", Online: on(true)},
|
||||
{Name: "BAT1", Type: "Battery", Status: "Not charging"},
|
||||
})
|
||||
if !got.OnAC || got.Reason != "ACAD (Mains) is online" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPeripheralsBatteryDecidesNothing(t *testing.T) {
|
||||
got := PowerSource([]Supply{
|
||||
{Name: "hidpp_battery_0", Type: "Battery", Scope: "Device", Status: "Discharging"},
|
||||
{Name: "ACAD", Type: "Mains", Online: on(true)},
|
||||
{Name: "BAT1", Type: "Battery", Status: "Charging"},
|
||||
})
|
||||
if !got.OnAC {
|
||||
t.Fatalf("a mouse's discharging battery put the laptop on battery: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoSupplyOnlineWithABatteryIsBatteryAndNoBatteryIsMains(t *testing.T) {
|
||||
if got := PowerSource([]Supply{{Name: "ACAD", Type: "Mains", Online: on(false)}, {Name: "BAT1", Type: "Battery", Status: "Unknown"}}); got.OnAC {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if got := PowerSource(nil); !got.OnAC {
|
||||
t.Fatalf("a machine with no battery is on mains: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheBatteryIsReadInWattHoursFromChargeAndHealthAgainstDesign(t *testing.T) {
|
||||
f := newFake(t)
|
||||
// The laptop's own battery, as measured: charge_* in µAh, no energy_* and no power_now.
|
||||
f.supply("BAT1", map[string]string{
|
||||
"type": "Battery", "status": "Discharging", "capacity": "80",
|
||||
"charge_now": "3073000", "charge_full": "3865000", "charge_full_design": "4580000",
|
||||
"voltage_min_design": "15939000", "current_now": "1000000", "voltage_now": "16000000",
|
||||
"cycle_count": "0", "charge_control_end_threshold": "80", "manufacturer": "ASUS ",
|
||||
})
|
||||
bs := f.machine().Batteries()
|
||||
if len(bs) != 1 {
|
||||
t.Fatalf("%+v", bs)
|
||||
}
|
||||
b := bs[0]
|
||||
if *b.EnergyWh != 49 || *b.FullWh != 61.6 || *b.DesignWh != 73 || *b.HealthPercent != 84.4 {
|
||||
t.Fatalf("energy %v full %v design %v health %v", *b.EnergyWh, *b.FullWh, *b.DesignWh, *b.HealthPercent)
|
||||
}
|
||||
if b.Cycles != nil || b.CyclesNote == "" {
|
||||
t.Fatal("a cycle count of 0 is the firmware not reporting one, and said so")
|
||||
}
|
||||
if *b.LimitPercent != 80 || *b.PowerW != 16 || b.HoursRemaining == nil || *b.HoursRemaining != 3.1 {
|
||||
t.Fatalf("limit %v power %v hours %v", *b.LimitPercent, *b.PowerW, b.HoursRemaining)
|
||||
}
|
||||
if b.Manufacturer != "ASUS" {
|
||||
t.Fatalf("manufacturer %q", b.Manufacturer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The module's long-running code (novox/hq ADR 0198): the profile switcher, launched with the tools
|
||||
// by the node's runtime and running beside them in the same process.
|
||||
//
|
||||
// It replaces the predecessor's `auto-profile`, a user unit that woke every five seconds for ever —
|
||||
// read the adapters, read /proc/stat, maybe call asusctl — on battery too, where its only possible
|
||||
// answer was the one it had already given. Here the kernel's power-supply event is the trigger; the
|
||||
// CPU is sampled only on mains, where the answer depends on it; and on battery the process sleeps
|
||||
// until the adapter comes back.
|
||||
//
|
||||
// **It acts on a change of its decision, never to restore one.** A profile chosen by hand — the
|
||||
// vendor's profile key, asusctl in a terminal, the profile tool — stays until the power source
|
||||
// changes or the load crosses a line. The predecessor re-asserted its choice every five seconds and so
|
||||
// made the profile key useless on battery.
|
||||
|
||||
// Emitter publishes an event as the module; nil when the process is not under the runtime.
|
||||
type Emitter func(eventType string, body any) error
|
||||
|
||||
// Switcher is the switcher's state, shared with the tools that report it.
|
||||
type Switcher struct {
|
||||
m *Machine
|
||||
now func() time.Time
|
||||
emit Emitter
|
||||
|
||||
mu sync.Mutex
|
||||
policy Policy
|
||||
source *Source
|
||||
decision *Decision
|
||||
applied string
|
||||
appliedAt time.Time
|
||||
lastError string
|
||||
holdUntil time.Time
|
||||
holdOf string
|
||||
watching string
|
||||
cpuPrev *CPUTimes
|
||||
disabled string
|
||||
asserted []string
|
||||
}
|
||||
|
||||
func NewSwitcher(m *Machine, emit Emitter) *Switcher {
|
||||
return &Switcher{m: m, now: time.Now, emit: emit}
|
||||
}
|
||||
|
||||
// Model is the machine's product family as its firmware reports it.
|
||||
func (m *Machine) Model() string { return m.read("/sys/class/dmi/id/product_family") }
|
||||
|
||||
// ModelFamily is the family this module is written for.
|
||||
const ModelFamily = "ROG Zephyrus G14"
|
||||
|
||||
// ThisModel says whether the machine is the model this module is written for.
|
||||
func (m *Machine) ThisModel() bool { return strings.EqualFold(m.Model(), ModelFamily) }
|
||||
|
||||
// sampleCPU reads /proc/stat and answers the busy percentage since the previous reading.
|
||||
func (s *Switcher) sampleCPU() (float64, bool) {
|
||||
t, err := ParseProcStat(s.m.read("/proc/stat"))
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
prev := s.cpuPrev
|
||||
s.cpuPrev = &t
|
||||
if prev == nil {
|
||||
return 0, false
|
||||
}
|
||||
return Busy(*prev, t)
|
||||
}
|
||||
|
||||
// Evaluate reads the power source, takes a CPU sample when asked and on mains, decides, and applies
|
||||
// the decision when it changed. It is the whole of one wake-up and what the tests drive.
|
||||
func (s *Switcher) Evaluate(ctx context.Context, sample bool) {
|
||||
if body := s.evaluate(ctx, sample); body != nil && s.emit != nil {
|
||||
// Outside the lock: publishing waits for the bus, and the tools that report the switcher
|
||||
// must not wait with it.
|
||||
if err := s.emit("profile.switched", body); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "profile.switched not published: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// evaluate is Evaluate under the lock; it answers the event to publish when it switched.
|
||||
func (s *Switcher) evaluate(ctx context.Context, sample bool) map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.disabled != "" {
|
||||
return nil
|
||||
}
|
||||
src := PowerSource(s.m.Supplies())
|
||||
now := s.now()
|
||||
first := s.source == nil
|
||||
if first || s.source.OnAC != src.OnAC {
|
||||
// A new power source: what was learnt about load on the other one says nothing here, and a
|
||||
// hold was for the source it was asked on.
|
||||
s.policy.Reset()
|
||||
s.cpuPrev = nil
|
||||
s.holdUntil = time.Time{}
|
||||
s.holdOf = ""
|
||||
s.sampleCPU() // the first reading on this source, so the next sample is a difference
|
||||
} else if sample && src.OnAC {
|
||||
if busy, ok := s.sampleCPU(); ok {
|
||||
s.policy.Observe(busy, now)
|
||||
}
|
||||
}
|
||||
s.source = &src
|
||||
d := s.policy.Decide(src)
|
||||
s.decision = &d
|
||||
// **Starting is not a reason to switch.** The runtime starts this process on every push that
|
||||
// changes a bundle; at boot and at every change of power source asusd has already applied its own
|
||||
// profile for the source, which AssertVendorSettings made the policy's. So the first decision is
|
||||
// taken as applied, and a profile someone chose by hand survives a push.
|
||||
if first {
|
||||
s.applied = d.Profile
|
||||
return nil
|
||||
}
|
||||
// Compared with what the switcher itself last applied, never with the profile in force: a profile
|
||||
// someone chose by hand is not a reason to act, a new decision is.
|
||||
if d.Profile == s.applied || now.Before(s.holdUntil) {
|
||||
return nil
|
||||
}
|
||||
from := s.applied
|
||||
if err := s.m.SetProfile(ctx, d.Profile); err != nil {
|
||||
s.lastError = err.Error() // and tried again at the next wake-up, since applied did not move
|
||||
return nil
|
||||
}
|
||||
s.lastError = ""
|
||||
s.applied, s.appliedAt = d.Profile, now
|
||||
body := map[string]any{"profile": d.Profile, "reason": d.Reason, "source": src.Source}
|
||||
if from != "" {
|
||||
body["from"] = from
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// Hold keeps a profile chosen through the tool for a while: the switcher does not move it until the
|
||||
// hold ends or the power source changes.
|
||||
func (s *Switcher) Hold(profile string, d time.Duration) time.Time {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if d <= 0 {
|
||||
s.holdUntil, s.holdOf = time.Time{}, ""
|
||||
return time.Time{}
|
||||
}
|
||||
s.holdUntil, s.holdOf = s.now().Add(d), profile
|
||||
return s.holdUntil
|
||||
}
|
||||
|
||||
// Run is the switcher's life: assert asusd's settings once, then wake on each power-supply event, on
|
||||
// each CPU sample while on mains, and at SafetyRecheck otherwise.
|
||||
func (s *Switcher) Run(ctx context.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
s.mu.Lock()
|
||||
s.disabled = fmt.Sprintf("the switcher stopped on a fault: %v", r)
|
||||
s.mu.Unlock()
|
||||
fmt.Fprintln(os.Stderr, s.disabled)
|
||||
}
|
||||
}()
|
||||
if !s.m.ThisModel() {
|
||||
s.mu.Lock()
|
||||
s.disabled = fmt.Sprintf("this machine reports %q, not %q: the switcher does not act on another model",
|
||||
s.m.Model(), ModelFamily)
|
||||
s.mu.Unlock()
|
||||
fmt.Fprintln(os.Stderr, s.disabled)
|
||||
return
|
||||
}
|
||||
s.AssertVendorSettings(ctx)
|
||||
|
||||
events, err := listenPowerSupply(ctx)
|
||||
s.mu.Lock()
|
||||
if err != nil {
|
||||
s.watching = "polling every " + SampleEvery.String() + ": " + err.Error()
|
||||
} else {
|
||||
s.watching = "the kernel's power-supply events"
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
s.Evaluate(ctx, false)
|
||||
timer := time.NewTimer(s.interval(err != nil))
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case _, open := <-events:
|
||||
if !open {
|
||||
events = nil
|
||||
s.mu.Lock()
|
||||
s.watching = "polling every " + SampleEvery.String() + ": the uevent socket closed"
|
||||
s.mu.Unlock()
|
||||
err = fmt.Errorf("closed")
|
||||
continue
|
||||
}
|
||||
// Settle: an adapter change arrives as several events within a moment.
|
||||
time.Sleep(time.Second)
|
||||
s.Evaluate(ctx, false)
|
||||
case <-timer.C:
|
||||
s.Evaluate(ctx, true)
|
||||
timer.Reset(s.interval(err != nil))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// interval is how long to sleep: a CPU sample's period on mains (or with no events to wake on), the
|
||||
// safety recheck on battery.
|
||||
func (s *Switcher) interval(polling bool) time.Duration {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if polling || s.source == nil || s.source.OnAC {
|
||||
return SampleEvery
|
||||
}
|
||||
return SafetyRecheck
|
||||
}
|
||||
|
||||
// AssertVendorSettings puts asusd's own settings where the module wants them, once at start: the
|
||||
// battery charge limit, and the profiles asusd itself switches to on mains and on battery, so that the
|
||||
// vendor daemon's own switching and this module's never disagree. Each is read first and set only if
|
||||
// it differs. A value changed later with a tool stands until the next start.
|
||||
func (s *Switcher) AssertVendorSettings(ctx context.Context) []string {
|
||||
var said []string
|
||||
if limit, err := s.m.ChargeLimit(ctx); err != nil {
|
||||
said = append(said, "charge limit not read: "+err.Error())
|
||||
} else if limit != ChargeLimitPercent {
|
||||
if _, err := s.m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(ChargeLimitPercent)); err != nil {
|
||||
said = append(said, "charge limit not set: "+vendor("asusctl", err).Error())
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("charge limit %d%% → %d%%", limit, ChargeLimitPercent))
|
||||
}
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("charge limit already %d%%", ChargeLimitPercent))
|
||||
}
|
||||
p, err := s.m.Profile(ctx)
|
||||
if err != nil {
|
||||
said = append(said, "asusd's profiles not read: "+err.Error())
|
||||
} else {
|
||||
for _, want := range []struct{ flag, have, want, what string }{
|
||||
{"-a", p.OnAC, ProfileOnAC, "on mains"},
|
||||
{"-b", p.Battery, ProfileOnBattery, "on battery"},
|
||||
} {
|
||||
if want.have == "" || strings.EqualFold(want.have, want.want) {
|
||||
continue
|
||||
}
|
||||
if _, err := s.m.Run(ctx, "asusctl", "profile", "set", want.flag, want.want); err != nil {
|
||||
said = append(said, "asusd's profile "+want.what+" not set: "+err.Error())
|
||||
} else {
|
||||
said = append(said, fmt.Sprintf("asusd's profile %s %s → %s", want.what, want.have, want.want))
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.asserted = said
|
||||
s.mu.Unlock()
|
||||
for _, line := range said {
|
||||
fmt.Fprintln(os.Stderr, line)
|
||||
}
|
||||
return said
|
||||
}
|
||||
|
||||
// SwitcherReport is the switcher's state as the profile-policy tool shows it.
|
||||
type SwitcherReport struct {
|
||||
Running bool `json:"running"`
|
||||
Disabled string `json:"disabled,omitempty"`
|
||||
Watching string `json:"woken_by,omitempty"`
|
||||
Source *Source `json:"source,omitempty"`
|
||||
Decision *Decision `json:"decision,omitempty"`
|
||||
Load Policy `json:"load"`
|
||||
LastApplied string `json:"last_applied,omitempty"`
|
||||
LastAppliedAt *time.Time `json:"last_applied_at,omitempty"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
HeldUntil *time.Time `json:"held_until,omitempty"`
|
||||
Held string `json:"held_profile,omitempty"`
|
||||
AssertedAtStart []string `json:"asserted_at_start,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Switcher) Report() SwitcherReport {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
r := SwitcherReport{
|
||||
Running: s.watching != "" && s.disabled == "", Disabled: s.disabled, Watching: s.watching,
|
||||
Source: s.source, Decision: s.decision, Load: s.policy, LastApplied: s.applied,
|
||||
LastAppliedAt: when(s.appliedAt), LastError: s.lastError, AssertedAtStart: s.asserted,
|
||||
}
|
||||
if s.now().Before(s.holdUntil) {
|
||||
r.HeldUntil, r.Held = when(s.holdUntil), s.holdOf
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// when is a time for a report: absent rather than the zero time.
|
||||
func when(t time.Time) *time.Time {
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return &t
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTheLoadMustBeSustainedToBoostAndToRelaxAndBetweenTheLinesNothingMoves(t *testing.T) {
|
||||
var p Policy
|
||||
at := time.Now()
|
||||
mains := Source{OnAC: true, Reason: "ACAD (Mains) is online"}
|
||||
for i := 0; i < SustainSamples-1; i++ {
|
||||
p.Observe(90, at)
|
||||
}
|
||||
if p.Decide(mains).Profile != ProfileOnAC {
|
||||
t.Fatal("boosted before the load was sustained")
|
||||
}
|
||||
p.Observe(35, at) // between the lines breaks the run
|
||||
p.Observe(90, at)
|
||||
if p.Boosted {
|
||||
t.Fatal("a broken run still counted")
|
||||
}
|
||||
for i := 0; i < SustainSamples; i++ {
|
||||
p.Observe(CPUHighPercent, at)
|
||||
}
|
||||
if d := p.Decide(mains); d.Profile != ProfileUnderLoad {
|
||||
t.Fatalf("%+v", d)
|
||||
}
|
||||
p.Observe(35, at)
|
||||
if !p.Boosted {
|
||||
t.Fatal("load between the lines relaxed the boost")
|
||||
}
|
||||
for i := 0; i < RelaxSamples; i++ {
|
||||
p.Observe(5, at)
|
||||
}
|
||||
if p.Decide(mains).Profile != ProfileOnAC {
|
||||
t.Fatal("did not relax after a sustained low")
|
||||
}
|
||||
p.Boosted = true
|
||||
if d := p.Decide(Source{OnAC: false, Reason: "BAT1 is discharging"}); d.Profile != ProfileOnBattery {
|
||||
t.Fatalf("battery: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIOWaitIsIdle(t *testing.T) {
|
||||
a, err := ParseProcStat("cpu 100 0 100 700 100 0 0 0 0 0\ncpu0 1 2 3\n")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := ParseProcStat("cpu 150 0 150 700 200 0 0 0 0 0\n")
|
||||
busy, ok := Busy(a, b)
|
||||
if !ok || busy != 50 {
|
||||
t.Fatalf("%v %v", busy, ok)
|
||||
}
|
||||
if _, ok := Busy(b, b); ok {
|
||||
t.Fatal("no time passed and a load was answered")
|
||||
}
|
||||
if _, err := ParseProcStat("intr 1 2"); err == nil {
|
||||
t.Fatal("a file without the cpu line was read")
|
||||
}
|
||||
}
|
||||
|
||||
func switcherOn(t *testing.T) (*fake, *Switcher, *[]map[string]any) {
|
||||
f := newFake(t)
|
||||
f.onMains()
|
||||
f.file("/proc/stat", "cpu 0 0 0 0 0 0 0 0\n")
|
||||
var emitted []map[string]any
|
||||
sw := NewSwitcher(f.machine(), func(_ string, body any) error {
|
||||
emitted = append(emitted, body.(map[string]any))
|
||||
return nil
|
||||
})
|
||||
return f, sw, &emitted
|
||||
}
|
||||
|
||||
func TestStartingIsNotAReasonToSwitch(t *testing.T) {
|
||||
f, sw, emitted := switcherOn(t)
|
||||
sw.Evaluate(context.Background(), false)
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 0 || len(*emitted) != 0 {
|
||||
t.Fatalf("the first decision acted: %v %v", calls, *emitted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAChangeOfPowerSourceSwitchesOnceAndPublishesIt(t *testing.T) {
|
||||
f, sw, emitted := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
sw.Evaluate(ctx, false)
|
||||
f.onBattery()
|
||||
sw.Evaluate(ctx, false)
|
||||
sw.Evaluate(ctx, true) // nothing changed: nothing done, and on battery nothing sampled
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 1 || calls[0] != "asusctl profile set Quiet" {
|
||||
t.Fatalf("%v", calls)
|
||||
}
|
||||
if len(*emitted) != 1 || (*emitted)[0]["profile"] != "Quiet" || (*emitted)[0]["from"] != "Balanced" {
|
||||
t.Fatalf("%v", *emitted)
|
||||
}
|
||||
f.onMains()
|
||||
sw.Evaluate(ctx, false)
|
||||
if calls := f.callsLike("asusctl profile set"); len(calls) != 2 || calls[1] != "asusctl profile set Balanced" {
|
||||
t.Fatalf("%v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSustainedLoadOnMainsBoostsFromSamples(t *testing.T) {
|
||||
f, sw, _ := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
sw.Evaluate(ctx, false)
|
||||
var user int
|
||||
for i := 1; i <= SustainSamples; i++ {
|
||||
user += 90
|
||||
f.file("/proc/stat", "cpu "+itoa(user)+" 0 0 "+itoa(i*10)+" 0 0 0 0\n")
|
||||
sw.Evaluate(ctx, true)
|
||||
}
|
||||
if !f.called("asusctl profile set Performance") {
|
||||
t.Fatalf("%v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHoldKeepsTheProfileUntilItEndsAndAFailureIsTriedAgain(t *testing.T) {
|
||||
f, sw, _ := switcherOn(t)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
sw.now = func() time.Time { return now }
|
||||
sw.Evaluate(ctx, false)
|
||||
f.onBattery()
|
||||
sw.Evaluate(ctx, false) // source change ends any hold; switches to Quiet
|
||||
sw.Hold("Performance", time.Hour)
|
||||
f.fails["asusctl profile set Balanced"] = errors.New("asusd is restarting")
|
||||
f.onMains()
|
||||
sw.Evaluate(ctx, false) // a change of source: the hold ends, the switch is attempted and fails
|
||||
if r := sw.Report(); r.LastError == "" || r.Held != "" {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
delete(f.fails, "asusctl profile set Balanced")
|
||||
sw.Evaluate(ctx, false)
|
||||
if r := sw.Report(); r.LastApplied != "Balanced" || r.LastError != "" {
|
||||
t.Fatalf("not tried again: %+v", r)
|
||||
}
|
||||
// A hold on the same source keeps a new decision from acting until it ends.
|
||||
sw.Hold("Quiet", time.Hour)
|
||||
sw.policy.Boosted = true
|
||||
sw.Evaluate(ctx, false)
|
||||
if f.called("asusctl profile set Performance") {
|
||||
t.Fatal("switched during a hold")
|
||||
}
|
||||
now = now.Add(2 * time.Hour)
|
||||
sw.Evaluate(ctx, false)
|
||||
if !f.called("asusctl profile set Performance") {
|
||||
t.Fatal("did not act once the hold ended")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAsusdsSettingsAreSetOnlyWhereTheyDiffer(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.answers["asusctl battery info"] = "Current battery charge limit: 100%\n"
|
||||
f.answers["asusctl profile get"] = "Active profile: Balanced\nAC profile Performance\nBattery profile Quiet\n"
|
||||
sw := NewSwitcher(f.machine(), nil)
|
||||
sw.AssertVendorSettings(context.Background())
|
||||
if !f.called("asusctl battery limit 80") || !f.called("asusctl profile set -a Balanced") || f.called("asusctl profile set -b Quiet") {
|
||||
t.Fatalf("%v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSwitcherDoesNotActOnAnotherModel(t *testing.T) {
|
||||
f := newFake(t)
|
||||
f.file("/sys/class/dmi/id/product_family", "ROG Strix\n")
|
||||
sw := NewSwitcher(f.machine(), nil)
|
||||
done := make(chan struct{})
|
||||
go func() { sw.Run(context.Background()); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("the switcher ran on another model")
|
||||
}
|
||||
if r := sw.Report(); r.Running || r.Disabled == "" || len(f.calls) != 0 {
|
||||
t.Fatalf("%+v %v", r, f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyPowerSupplyUeventsWake(t *testing.T) {
|
||||
yes := []byte("change@/devices/LNXSYSTM:00/ACPI0003:00/power_supply/ACAD\x00ACTION=change\x00SUBSYSTEM=power_supply\x00POWER_SUPPLY_ONLINE=0\x00")
|
||||
no := []byte("change@/devices/virtual/net/wlan0\x00ACTION=change\x00SUBSYSTEM=net\x00")
|
||||
if !powerSupplyEvent(yes) || powerSupplyEvent(no) {
|
||||
t.Fatal("the uevent filter")
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string { return strconv.Itoa(n) }
|
||||
@@ -0,0 +1,168 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Sensor is one temperature, fan or power reading from hwmon.
|
||||
type Sensor struct {
|
||||
Chip string `json:"chip"`
|
||||
Label string `json:"label"`
|
||||
Value float64 `json:"value"`
|
||||
}
|
||||
|
||||
// DGPU is the discrete GPU as the PCI bus and its driver see it.
|
||||
type DGPU struct {
|
||||
Address string `json:"pci_address"`
|
||||
Runtime string `json:"runtime_status"`
|
||||
Name string `json:"name,omitempty"`
|
||||
TempC *float64 `json:"temp_c,omitempty"`
|
||||
PowerW *float64 `json:"power_w,omitempty"`
|
||||
PState string `json:"pstate,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
}
|
||||
|
||||
// hwmon reads every hwmon reading of one kind: "temp" (°C), "fan" (RPM) or "power" (W).
|
||||
func (m *Machine) hwmon(kind string) []Sensor {
|
||||
var out []Sensor
|
||||
for _, dir := range m.glob("/sys/class/hwmon/hwmon*") {
|
||||
chip := m.read(dir + "/name")
|
||||
inputs := m.glob(dir + "/" + kind + "*_input")
|
||||
if kind == "power" {
|
||||
inputs = append(inputs, m.glob(dir+"/power*_average")...)
|
||||
}
|
||||
for _, in := range inputs {
|
||||
v, ok := m.readInt(in)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
base := path.Base(in)
|
||||
stem := base[:strings.LastIndex(base, "_")]
|
||||
label := m.read(dir + "/" + stem + "_label")
|
||||
if label == "" {
|
||||
label = base
|
||||
} else if strings.HasSuffix(base, "_average") {
|
||||
label += " (average)"
|
||||
}
|
||||
value := float64(v)
|
||||
switch kind {
|
||||
case "temp":
|
||||
value = round1(value / 1000)
|
||||
case "power":
|
||||
value = round1(value / 1e6)
|
||||
}
|
||||
out = append(out, Sensor{Chip: chip, Label: label, Value: value})
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Chip != out[j].Chip {
|
||||
return out[i].Chip < out[j].Chip
|
||||
}
|
||||
return out[i].Label < out[j].Label
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// dgpu finds the NVIDIA display controller and, only when it is already awake, asks its driver for
|
||||
// its temperature and draw. **Asking wakes it**: nvidia-smi brings a suspended GPU out of D3, which
|
||||
// is the power a reading of power draw should not cost.
|
||||
func (m *Machine) dgpu(ctx context.Context) *DGPU {
|
||||
for _, dir := range m.glob("/sys/bus/pci/devices/*") {
|
||||
if m.read(dir+"/vendor") != "0x10de" || !strings.HasPrefix(m.read(dir+"/class"), "0x03") {
|
||||
continue
|
||||
}
|
||||
g := &DGPU{Address: path.Base(dir), Runtime: m.read(dir + "/power/runtime_status")}
|
||||
if g.Runtime != "active" {
|
||||
g.Note = "the discrete GPU is " + g.Runtime + "; not woken to be read"
|
||||
return g
|
||||
}
|
||||
out, err := m.Run(ctx, "nvidia-smi", "--query-gpu=name,temperature.gpu,power.draw,pstate", "--format=csv,noheader,nounits")
|
||||
if err != nil {
|
||||
g.Note = "nvidia-smi: " + err.Error()
|
||||
return g
|
||||
}
|
||||
f := strings.Split(strings.TrimSpace(strings.SplitN(out, "\n", 2)[0]), ",")
|
||||
if len(f) >= 4 {
|
||||
g.Name = strings.TrimSpace(f[0])
|
||||
if t, err := strconv.ParseFloat(strings.TrimSpace(f[1]), 64); err == nil {
|
||||
g.TempC = &t
|
||||
}
|
||||
if w, err := strconv.ParseFloat(strings.TrimSpace(f[2]), 64); err == nil {
|
||||
w = round1(w)
|
||||
g.PowerW = &w
|
||||
}
|
||||
g.PState = strings.TrimSpace(f[3])
|
||||
}
|
||||
return g
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Thermals is what the thermals tool answers.
|
||||
type Thermals struct {
|
||||
Temperatures []Sensor `json:"temperatures_c"`
|
||||
Fans []Sensor `json:"fans_rpm"`
|
||||
DGPU *DGPU `json:"dgpu,omitempty"`
|
||||
Profile string `json:"platform_profile,omitempty"`
|
||||
Hottest *Sensor `json:"hottest,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Machine) Thermals(ctx context.Context) Thermals {
|
||||
t := Thermals{Temperatures: m.hwmon("temp"), Fans: m.hwmon("fan"), DGPU: m.dgpu(ctx),
|
||||
Profile: m.read("/sys/firmware/acpi/platform_profile")}
|
||||
if t.Temperatures == nil {
|
||||
t.Temperatures = []Sensor{}
|
||||
}
|
||||
if t.Fans == nil {
|
||||
t.Fans = []Sensor{}
|
||||
}
|
||||
for i := range t.Temperatures {
|
||||
if t.Hottest == nil || t.Temperatures[i].Value > t.Hottest.Value {
|
||||
h := t.Temperatures[i]
|
||||
t.Hottest = &h
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// PowerDraw is what the power-draw tool answers.
|
||||
type PowerDraw struct {
|
||||
Source Source `json:"source"`
|
||||
BatteryW *float64 `json:"battery_w,omitempty"`
|
||||
BatteryFlow string `json:"battery_flow,omitempty"`
|
||||
CPUPackageW *float64 `json:"apu_package_w,omitempty"`
|
||||
DGPU *DGPU `json:"dgpu,omitempty"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
func (m *Machine) PowerDraw(ctx context.Context) PowerDraw {
|
||||
p := PowerDraw{Source: PowerSource(m.Supplies()), DGPU: m.dgpu(ctx),
|
||||
Note: "on battery, battery_w is what the whole machine draws; on mains it is only what the battery takes or gives"}
|
||||
for _, b := range m.Batteries() {
|
||||
if b.PowerW != nil {
|
||||
w := *b.PowerW
|
||||
p.BatteryW = &w
|
||||
switch strings.ToLower(b.Status) {
|
||||
case "discharging":
|
||||
p.BatteryFlow = "discharging"
|
||||
case "charging":
|
||||
p.BatteryFlow = "charging"
|
||||
default:
|
||||
p.BatteryFlow = strings.ToLower(b.Status)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
// The integrated GPU's hwmon reports the whole APU's package power (PPT) on this model.
|
||||
for _, s := range m.hwmon("power") {
|
||||
if s.Chip == "amdgpu" && s.Label == "PPT" {
|
||||
w := s.Value
|
||||
p.CPUPackageW = &w
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// Tools is the module's tools, over one machine and its switcher.
|
||||
func Tools(m *Machine, sw *Switcher) []stdio.Tool {
|
||||
ctx := context.Background
|
||||
return []stdio.Tool{
|
||||
{
|
||||
Name: "zephyrus_brightness",
|
||||
Description: "Read or set the internal panel's and the keyboard's backlight. With no argument, reads both. " +
|
||||
"panel is a percentage (40) or a step (+5, -10), never below 1 %; keyboard is off, low, med, high, 0-3, + or -.",
|
||||
Input: map[string]any{
|
||||
"panel": map[string]any{"type": "string", "description": "percentage or step, e.g. 40, +5, -10"},
|
||||
"keyboard": map[string]any{"type": "string", "description": "off, low, med, high, 0-3, + or -"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
out := map[string]any{}
|
||||
if p := str(args, "panel"); p != "" {
|
||||
got, err := m.SetPanel(ctx(), p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["panel"] = got
|
||||
} else if got, err := m.PanelBrightness(); err == nil {
|
||||
out["panel"] = got
|
||||
} else {
|
||||
out["panel_error"] = err.Error()
|
||||
}
|
||||
if k := str(args, "keyboard"); k != "" {
|
||||
got, err := m.SetKeyboard(ctx(), k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["keyboard"] = got
|
||||
} else if got, err := m.KeyboardBrightness(); err == nil {
|
||||
out["keyboard"] = got
|
||||
} else {
|
||||
out["keyboard_error"] = err.Error()
|
||||
}
|
||||
return out, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_battery",
|
||||
Description: "The battery: charge, energy, health (full against design), cycles, the charge limit, the power it gives or takes, and time left when discharging.",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
return map[string]any{"source": PowerSource(m.Supplies()), "batteries": orEmpty(m.Batteries())}, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_charge_limit",
|
||||
Description: fmt.Sprintf("Read or set the battery charge limit through asusd. limit is 20-100; oneshot charges to full once "+
|
||||
"and goes back to the limit. The module asserts %d %% again when its process next starts.", ChargeLimitPercent),
|
||||
Input: map[string]any{
|
||||
"limit": map[string]any{"type": "integer", "description": "20-100"},
|
||||
"oneshot": map[string]any{"type": "boolean", "description": "charge to full once, keeping the limit"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return ChargeLimitTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_gpu_mode",
|
||||
Description: "Read or set the hybrid GPU's mode through supergfxd: Integrated, Hybrid or AsusMuxDgpu as the machine supports. " +
|
||||
"Answers the mode, the discrete GPU's power state, any pending mode and the action it waits for (a logout, a reboot), " +
|
||||
"and whether asusd will switch it again on the next change of power source.",
|
||||
Input: map[string]any{
|
||||
"mode": map[string]any{"type": "string", "description": "a supported mode, e.g. Integrated or Hybrid"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return GPUModeTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_profile",
|
||||
Description: "Read or set the platform profile (Quiet, Balanced, Performance) through asusd. A profile set here is held " +
|
||||
fmt.Sprintf("for hold_minutes (default %d, 0 for none) before the module's switcher may move it; a change of power source ends the hold.", int(DefaultHold.Minutes())),
|
||||
Input: map[string]any{
|
||||
"profile": map[string]any{"type": "string", "enum": Profiles},
|
||||
"hold_minutes": map[string]any{"type": "integer", "description": "how long the switcher leaves it (default 60, at most 1440)"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return ProfileTool(ctx(), m, sw, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_thermals",
|
||||
Description: "Every temperature and fan the hardware reports (°C, RPM), the hottest, the platform profile, and the discrete GPU's temperature when it is awake (it is not woken to be read).",
|
||||
Run: func(map[string]any) (any, error) { return m.Thermals(ctx()), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_power_draw",
|
||||
Description: "What the machine draws: the battery's flow in watts, the APU's package power, the discrete GPU's draw when awake, and the power source with the reason it was decided.",
|
||||
Run: func(map[string]any) (any, error) { return m.PowerDraw(ctx()), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_profile_policy",
|
||||
Description: "What the module's profile switcher would choose now and why: the power source, recent CPU load against the thresholds, " +
|
||||
"the decision, the profile in force, any hold, what woke it, and what it asserted in asusd at start.",
|
||||
Run: func(map[string]any) (any, error) { return PolicyTool(ctx(), m, sw), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_fan_curves",
|
||||
Description: "The fan curves asusd holds for each profile (or one profile): per fan, eight points of temperature and duty.",
|
||||
Input: map[string]any{
|
||||
"profile": map[string]any{"type": "string", "enum": Profiles},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) { return FanCurvesTool(ctx(), m, args) },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_keys",
|
||||
Description: "Every custom key on the laptop: each triggerhappy trigger (the vendor keys that reach no X client), the module's own i3 lines " +
|
||||
"(keys the firmware sends as ordinary presses, and what starts with the session), and the keys the firmware handles itself — " +
|
||||
"what each runs and the file it is defined in. Warns when one key is bound in two trigger files, which fires it twice.",
|
||||
Run: func(map[string]any) (any, error) { return m.Keys(), nil },
|
||||
},
|
||||
{
|
||||
Name: "zephyrus_check",
|
||||
Description: "Check what this module expects of the machine: the model, the vendor packages and daemons, the NVIDIA options in force, " +
|
||||
"suspend and resume, the charge limit, one authority each over the profile and the GPU mode, and the predecessor's leftovers. Says what it did not check.",
|
||||
Run: func(map[string]any) (any, error) { return m.Check(ctx(), sw), nil },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ChargeLimitTool reads or sets the limit.
|
||||
func ChargeLimitTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
out := map[string]any{"module_limit_percent": ChargeLimitPercent}
|
||||
if v, given := args["limit"]; given && v != nil {
|
||||
n, err := whole(v, "limit")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n < 20 || n > 100 {
|
||||
return nil, fmt.Errorf("limit %d is outside 20-100", n)
|
||||
}
|
||||
if _, err := m.Run(ctx, "asusctl", "battery", "limit", strconv.Itoa(n)); err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out["set"] = n
|
||||
}
|
||||
if b, _ := args["oneshot"].(bool); b {
|
||||
if _, err := m.Run(ctx, "asusctl", "battery", "oneshot"); err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out["oneshot"] = "charging to full once; the limit returns after"
|
||||
}
|
||||
if n, err := m.ChargeLimit(ctx); err == nil {
|
||||
out["asusd_limit_percent"] = n
|
||||
} else {
|
||||
out["asusd_error"] = err.Error()
|
||||
}
|
||||
for _, b := range m.Batteries() {
|
||||
if b.LimitPercent != nil {
|
||||
out["kernel_limit_percent"] = *b.LimitPercent
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GPUModeTool reads or sets the GPU mode.
|
||||
func GPUModeTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
g, err := m.GPU(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]any{}
|
||||
if want := str(args, "mode"); want != "" {
|
||||
mode := ""
|
||||
for _, s := range g.Supported {
|
||||
if strings.EqualFold(s, want) {
|
||||
mode = s
|
||||
}
|
||||
}
|
||||
if mode == "" {
|
||||
return nil, fmt.Errorf("mode %q is not one this machine supports (%s)", want, strings.Join(g.Supported, ", "))
|
||||
}
|
||||
said, err := m.Run(ctx, "supergfxctl", "-m", mode)
|
||||
if err != nil {
|
||||
return nil, vendor("supergfxctl", err)
|
||||
}
|
||||
out["requested"] = mode
|
||||
if s := strings.TrimSpace(said); s != "" {
|
||||
out["supergfxctl_said"] = s
|
||||
}
|
||||
if g, err = m.GPU(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
out["gpu"] = g
|
||||
if c := m.Asusd(); c != nil && (c.ACCommand != "" || c.BatteryCommand != "") {
|
||||
out["asusd_switches_it"] = map[string]string{"on_ac": c.ACCommand, "on_battery": c.BatteryCommand,
|
||||
"note": "asusd runs these on every change of power source, so a mode set here lasts until the next one"}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ProfileTool reads or sets the profile.
|
||||
func ProfileTool(ctx context.Context, m *Machine, sw *Switcher, args map[string]any) (any, error) {
|
||||
out := map[string]any{}
|
||||
if want := str(args, "profile"); want != "" {
|
||||
p, err := canonicalProfile(want)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hold := DefaultHold
|
||||
if v, given := args["hold_minutes"]; given && v != nil {
|
||||
n, err := whole(v, "hold_minutes")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n < 0 {
|
||||
return nil, fmt.Errorf("hold_minutes must not be negative")
|
||||
}
|
||||
hold = time.Duration(min(n, 1440)) * time.Minute
|
||||
}
|
||||
if err := m.SetProfile(ctx, p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["set"] = p
|
||||
if sw != nil {
|
||||
if until := sw.Hold(p, hold); !until.IsZero() {
|
||||
out["held_until"] = until
|
||||
}
|
||||
}
|
||||
}
|
||||
state, err := m.Profile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out["profile"] = state
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// PolicyTool reports the switcher and, independently of it, what the policy says now.
|
||||
func PolicyTool(ctx context.Context, m *Machine, sw *Switcher) any {
|
||||
out := map[string]any{
|
||||
"thresholds": map[string]any{
|
||||
"on_battery": ProfileOnBattery, "on_ac": ProfileOnAC, "under_load": ProfileUnderLoad,
|
||||
"cpu_high_percent": CPUHighPercent, "cpu_low_percent": CPULowPercent,
|
||||
"sample_every": SampleEvery.String(), "sustain_samples": SustainSamples, "relax_samples": RelaxSamples,
|
||||
"set_by": "constants until settings exist (novox/hq issue 168)",
|
||||
},
|
||||
}
|
||||
if sw != nil {
|
||||
out["switcher"] = sw.Report()
|
||||
} else {
|
||||
var p Policy
|
||||
out["decision_now"] = p.Decide(PowerSource(m.Supplies()))
|
||||
}
|
||||
if state, err := m.Profile(ctx); err == nil {
|
||||
out["in_force"] = state
|
||||
} else {
|
||||
out["in_force_error"] = err.Error()
|
||||
}
|
||||
if pid, ok := m.predecessorProcess("auto-profile"); ok {
|
||||
out["second_switcher"] = fmt.Sprintf("the predecessor's auto-profile still runs (pid %d) and overrides this every five seconds", pid)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FanCurvesTool reads asusd's fan curves.
|
||||
func FanCurvesTool(ctx context.Context, m *Machine, args map[string]any) (any, error) {
|
||||
profiles := Profiles
|
||||
if want := str(args, "profile"); want != "" {
|
||||
p, err := canonicalProfile(want)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profiles = []string{p}
|
||||
}
|
||||
out := map[string]any{}
|
||||
for _, p := range profiles {
|
||||
said, err := m.Run(ctx, "asusctl", "fan-curve", "--mod-profile", strings.ToLower(p))
|
||||
if err != nil {
|
||||
return nil, vendor("asusctl", err)
|
||||
}
|
||||
out[p] = orEmpty(ParseFanCurves(said))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func str(args map[string]any, key string) string {
|
||||
s, _ := args[key].(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
// whole is an integer argument given as a JSON number or a numeric string.
|
||||
func whole(v any, key string) (int, error) {
|
||||
switch n := v.(type) {
|
||||
case float64:
|
||||
if n != math.Trunc(n) {
|
||||
return 0, fmt.Errorf("%s must be a whole number, not %v", key, n)
|
||||
}
|
||||
return int(n), nil
|
||||
case string:
|
||||
i, err := strconv.Atoi(strings.TrimSpace(n))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s must be a whole number, not %q", key, n)
|
||||
}
|
||||
return i, nil
|
||||
}
|
||||
return 0, fmt.Errorf("%s must be a whole number", key)
|
||||
}
|
||||
|
||||
func orEmpty[T any](s []T) []T {
|
||||
if s == nil {
|
||||
return []T{}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// The kernel announces every change of a power supply — an adapter plugged or pulled, a battery
|
||||
// starting or stopping to discharge — as a uevent on a netlink socket that any account may listen
|
||||
// on. That is the event the switcher reacts to: no daemon, no bus client, no polling.
|
||||
//
|
||||
// upower re-announces the same changes on the system bus, and listening there would need a D-Bus
|
||||
// client in the bundle; udev's re-broadcast (netlink group 2) carries a libudev header. The kernel's
|
||||
// own group (1) is the source both of them read.
|
||||
|
||||
// powerSupplyEvent says whether a uevent is about a power supply.
|
||||
func powerSupplyEvent(msg []byte) bool {
|
||||
for _, field := range bytes.Split(msg, []byte{0}) {
|
||||
if bytes.Equal(field, []byte("SUBSYSTEM=power_supply")) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// listenPowerSupply opens the kernel's uevent socket and sends on the channel for each power-supply
|
||||
// event, never blocking: a burst of events is one wake-up. It stops when ctx ends.
|
||||
func listenPowerSupply(ctx context.Context) (<-chan struct{}, error) {
|
||||
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW|syscall.SOCK_CLOEXEC, syscall.NETLINK_KOBJECT_UEVENT)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening the kernel's uevent socket: %w", err)
|
||||
}
|
||||
if err := syscall.Bind(fd, &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK, Groups: 1}); err != nil {
|
||||
syscall.Close(fd)
|
||||
return nil, fmt.Errorf("joining the kernel's uevent group: %w", err)
|
||||
}
|
||||
events := make(chan struct{}, 1)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
syscall.Close(fd)
|
||||
}()
|
||||
go func() {
|
||||
defer close(events)
|
||||
buf := make([]byte, 64*1024)
|
||||
for {
|
||||
n, _, err := syscall.Recvfrom(fd, buf, 0)
|
||||
if err != nil {
|
||||
if err == syscall.EINTR || err == syscall.ENOBUFS {
|
||||
// ENOBUFS: events were dropped. Treat it as one, since a dropped one may have
|
||||
// been the adapter.
|
||||
if err == syscall.ENOBUFS {
|
||||
select {
|
||||
case events <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
return
|
||||
}
|
||||
if powerSupplyEvent(buf[:n]) {
|
||||
select {
|
||||
case events <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return events, nil
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-backlight + | - | PERCENT — step or set the internal panel's backlight, never below 1 %.
|
||||
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# The panel is the backlight beneath the eDP connector, not a name: in hybrid mode this model also
|
||||
# registers the discrete GPU's backlight (nvidia_0), which moves nothing. Writable by the video group
|
||||
# through the module's udev rule, so the vendor-key trigger needs no root.
|
||||
set -u
|
||||
STEP=5
|
||||
dev=""
|
||||
for d in /sys/class/backlight/*; do
|
||||
[ -e "$d" ] || continue
|
||||
case "$(readlink -f "$d")" in *-eDP-*) dev=$d; break ;; esac
|
||||
done
|
||||
if [ -z "$dev" ]; then
|
||||
for d in /sys/class/backlight/*; do [ -e "$d" ] && { dev=$d; break; }; done
|
||||
fi
|
||||
[ -n "$dev" ] || { echo "zephyrus-backlight: no backlight" >&2; exit 1; }
|
||||
cur=$(cat "$dev/brightness")
|
||||
max=$(cat "$dev/max_brightness")
|
||||
pct=$(( cur * 100 / max ))
|
||||
case "${1:-}" in
|
||||
+|up|Up) pct=$(( pct + STEP )) ;;
|
||||
-|down|Down) pct=$(( pct - STEP )) ;;
|
||||
''|*[!0-9]*) echo "usage: zephyrus-backlight + | - | PERCENT" >&2; exit 2 ;;
|
||||
*) pct=$1 ;;
|
||||
esac
|
||||
(( pct < 1 )) && pct=1
|
||||
(( pct > 100 )) && pct=100
|
||||
new=$(( max * pct / 100 ))
|
||||
(( new < 1 )) && new=1
|
||||
printf '%s' "$new" >"$dev/brightness" || exit 1
|
||||
exec "$(dirname "$0")/zephyrus-notify" 5555 "Brightness: ${pct}%"
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-display primary | order — the laptop's internal panel among the outputs.
|
||||
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# primary makes the internal panel X's primary output, where the bars' tray goes.
|
||||
# order the display key (Fn+F9, which the firmware sends as Super+P): odd workspaces to the
|
||||
# internal panel, even ones to the first external output, or all to the panel when it
|
||||
# is alone. The predecessor's orden-workspaces.
|
||||
#
|
||||
# The panel is found, not named: the connected output whose name starts with eDP. The predecessor
|
||||
# wrote eDP-1, which is what this model calls it today and not a promise.
|
||||
set -u
|
||||
here=$(dirname "$0")
|
||||
panel=$(xrandr --query 2>/dev/null | awk '$2 == "connected" && $1 ~ /^eDP/ { print $1; exit }')
|
||||
[ -n "$panel" ] || { echo "zephyrus-display: no internal panel connected" >&2; exit 1; }
|
||||
case "${1:-}" in
|
||||
primary)
|
||||
exec xrandr --output "$panel" --primary
|
||||
;;
|
||||
order)
|
||||
external=$(xrandr --listmonitors 2>/dev/null | awk -v p="$panel" 'NR > 1 && $NF != p { print $NF; exit }')
|
||||
[ -n "$external" ] || external=$panel
|
||||
# i3's workspace list, one object per workspace; num and output read from each. No jq: the
|
||||
# fields are flat strings and numbers, and rect, the only nested value, holds neither name.
|
||||
i3-msg -t get_workspaces 2>/dev/null | sed 's/},{"id"/}\n{"id"/g' |
|
||||
while read -r ws; do
|
||||
num=$(printf '%s' "$ws" | grep -o '"num":-\?[0-9]*' | cut -d: -f2)
|
||||
out=$(printf '%s' "$ws" | grep -o '"output":"[^"]*"' | cut -d'"' -f4)
|
||||
[ -n "$num" ] && [ "$num" -ge 0 ] || continue
|
||||
if [ $((num % 2)) -eq 0 ]; then dest=$external; else dest=$panel; fi
|
||||
[ "$out" = "$dest" ] && continue
|
||||
i3-msg "workspace number $num; move workspace to output $dest" >/dev/null
|
||||
done
|
||||
if [ "$external" = "$panel" ]; then
|
||||
"$here/zephyrus-notify" 7780 "Workspaces: all on the panel"
|
||||
else
|
||||
"$here/zephyrus-notify" 7780 "Workspaces: odd on the panel, even on $external"
|
||||
fi
|
||||
;;
|
||||
*) echo "usage: zephyrus-display primary | order" >&2; exit 2 ;;
|
||||
esac
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-kbd-notify — shows the keyboard backlight's level when it changes. The level itself is set
|
||||
# by the firmware and asusd (Fn+F2/F3), which tell UPower; this only listens and notifies. Started once
|
||||
# per session from the module's i3 fragment. Shipped by the mesh's asus-zephyrus-g14 module.
|
||||
#
|
||||
# One instance per session: i3 runs its `exec` lines again on an in-place restart, and the
|
||||
# predecessor's listener ran twice after one, showing every change twice.
|
||||
set -u
|
||||
here=$(dirname "$0")
|
||||
lock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/zephyrus-kbd-notify.lock"
|
||||
exec 9>"$lock"
|
||||
flock -n 9 || exit 0
|
||||
levels=(Off Low Med High)
|
||||
dbus-monitor --system "type='signal',interface='org.freedesktop.UPower.KbdBacklight',member='BrightnessChanged'" 2>/dev/null |
|
||||
while read -r line; do
|
||||
if [[ $line =~ int32\ ([0-9]+) ]]; then
|
||||
v=${BASH_REMATCH[1]}
|
||||
"$here/zephyrus-notify" 5556 "Keyboard: ${levels[$v]:-$v}"
|
||||
fi
|
||||
done
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-media play-pause | next | previous — the media keys, through MPRIS (playerctl), with a short
|
||||
# notification of what happened. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# From the predecessor's media-control, kept: the lock against a double fire (the vendor keys can
|
||||
# repeat), and the notification. Dropped: its fallback to a media server's local API, which needed a
|
||||
# token from a file of secrets (novox/hq research 027 question 2). A player that speaks MPRIS is
|
||||
# reached; one that does not says so.
|
||||
set -u
|
||||
here=$(dirname "$0")
|
||||
action=${1:-play-pause}
|
||||
case "$action" in play-pause | next | previous) ;; *) echo "usage: zephyrus-media play-pause | next | previous" >&2; exit 2 ;; esac
|
||||
lock="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/zephyrus-media.lock"
|
||||
exec 9>"$lock"
|
||||
flock -n 9 || exit 0
|
||||
if ! playerctl status >/dev/null 2>&1; then
|
||||
"$here/zephyrus-notify" 7777 "Media: no player"
|
||||
exit 0
|
||||
fi
|
||||
playerctl "$action" 2>/dev/null
|
||||
if [ "$action" = play-pause ]; then
|
||||
sleep 0.2
|
||||
[ "$(playerctl status 2>/dev/null)" = Playing ] && label=Playing || label=Paused
|
||||
else
|
||||
label=${action^}
|
||||
fi
|
||||
"$here/zephyrus-notify" 7777 "Media: $label"
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-notify ID SUMMARY — a short desktop notification that replaces the previous one with the
|
||||
# same ID, through the session's notification service on its bus. busctl is the service manager's
|
||||
# own client, so nothing is installed for it. Shipped by the mesh's asus-zephyrus-g14 module.
|
||||
set -u
|
||||
id=${1:-0}
|
||||
summary=${2:-}
|
||||
uid=$(id -u)
|
||||
DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/${uid}/bus" \
|
||||
busctl --user call org.freedesktop.Notifications /org/freedesktop/Notifications \
|
||||
org.freedesktop.Notifications Notify susssasa{sv}i \
|
||||
asus-zephyrus-g14 "$id" "" "$summary" "" 0 1 urgency y 0 1500 >/dev/null 2>&1 || true
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-session COMMAND [ARG...] — run a command in the operator's graphical session from outside
|
||||
# it: from a vendor-key trigger, which triggerhappy runs as the operator's account but with none of
|
||||
# the session's environment. Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# What it replaces: the predecessor's `as-user`, which triggerhappy ran as root and which `su`-ed to
|
||||
# a named person with a hard-coded user id and display, and sourced a file of secrets on the way.
|
||||
# Here the account is whoever runs it, the bus is that account's, and the display is the one the
|
||||
# account's own session uses. Nothing is sourced.
|
||||
set -u
|
||||
uid=$(id -u)
|
||||
export XDG_RUNTIME_DIR="/run/user/${uid}"
|
||||
export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
|
||||
home=$(getent passwd "$uid" | cut -d: -f6)
|
||||
[ -n "$home" ] && export HOME="$home"
|
||||
# The session's own window manager says best which display and authority the session uses: read
|
||||
# them from its environment, as the desktop modules' session finder does. Then logind, then any
|
||||
# process of this account that has a display.
|
||||
from_environ() {
|
||||
env=$(tr '\0' '\n' <"/proc/$1/environ" 2>/dev/null) || return 1
|
||||
d=$(printf '%s\n' "$env" | sed -n 's/^DISPLAY=//p' | head -n1)
|
||||
[ -n "$d" ] || return 1
|
||||
export DISPLAY="$d"
|
||||
a=$(printf '%s\n' "$env" | sed -n 's/^XAUTHORITY=//p' | head -n1)
|
||||
[ -n "$a" ] && export XAUTHORITY="$a"
|
||||
return 0
|
||||
}
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
for pid in $(pgrep -xu "$uid" i3 2>/dev/null); do
|
||||
from_environ "$pid" && break
|
||||
done
|
||||
fi
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk -v u="$uid" '$2 == u { print $1 }'); do
|
||||
d=$(loginctl show-session "$s" -p Display --value 2>/dev/null)
|
||||
if [ -n "$d" ]; then export DISPLAY="$d"; break; fi
|
||||
done
|
||||
fi
|
||||
if [ -z "${DISPLAY:-}" ]; then
|
||||
for pid in $(pgrep -u "$uid" 2>/dev/null); do
|
||||
from_environ "$pid" && break
|
||||
done
|
||||
fi
|
||||
: "${XAUTHORITY:=${HOME}/.Xauthority}"
|
||||
export XAUTHORITY
|
||||
exec "$@"
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# zephyrus-touchpad reset | toggle — apply the touchpad's settings again, or switch it on or off.
|
||||
# Shipped by the mesh's asus-zephyrus-g14 module; edit the catalogue.
|
||||
#
|
||||
# The settings themselves are an X input class (/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf),
|
||||
# which X applies every time the device appears — after a resume too, which is what the predecessor's
|
||||
# sleep hook existed for. This is the manual form, bound to the touchpad key.
|
||||
set -u
|
||||
here=$(dirname "$0")
|
||||
name=$("$here/zephyrus-session" xinput list --name-only 2>/dev/null | grep -m1 -i 'touchpad')
|
||||
[ -n "$name" ] || { echo "zephyrus-touchpad: no touchpad in this session" >&2; exit 1; }
|
||||
x() { "$here/zephyrus-session" xinput "$@"; }
|
||||
case "${1:-reset}" in
|
||||
reset)
|
||||
x set-prop "$name" "libinput Tapping Enabled" 1
|
||||
x set-prop "$name" "libinput Natural Scrolling Enabled" 1
|
||||
x set-prop "$name" "libinput Accel Speed" 0.15
|
||||
x enable "$name"
|
||||
"$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: reset"
|
||||
;;
|
||||
toggle)
|
||||
if x list-props "$name" | grep -q 'Device Enabled ([0-9]*):[[:space:]]*1'; then
|
||||
x disable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: off"
|
||||
else
|
||||
x enable "$name"; "$here/zephyrus-session" "$here/zephyrus-notify" 7779 "Touchpad: on"
|
||||
fi
|
||||
;;
|
||||
*) echo "usage: zephyrus-touchpad reset | toggle" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,5 @@
|
||||
module asuszephyrusg14
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.6
|
||||
@@ -0,0 +1,2 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
@@ -0,0 +1,224 @@
|
||||
{
|
||||
"module": "asus-zephyrus-g14",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager",
|
||||
"service-manager"
|
||||
],
|
||||
"requires": [
|
||||
"x11-display"
|
||||
],
|
||||
"emits": [
|
||||
"profile.switched"
|
||||
],
|
||||
"tools": [
|
||||
"zephyrus_brightness",
|
||||
"zephyrus_battery",
|
||||
"zephyrus_charge_limit",
|
||||
"zephyrus_gpu_mode",
|
||||
"zephyrus_profile",
|
||||
"zephyrus_thermals",
|
||||
"zephyrus_power_draw",
|
||||
"zephyrus_profile_policy",
|
||||
"zephyrus_fan_curves",
|
||||
"zephyrus_keys",
|
||||
"zephyrus_check"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "asusctl",
|
||||
"type": "package",
|
||||
"package": "asusctl"
|
||||
},
|
||||
{
|
||||
"id": "playerctl",
|
||||
"type": "package",
|
||||
"package": "playerctl"
|
||||
},
|
||||
{
|
||||
"id": "asusd",
|
||||
"type": "service",
|
||||
"unit": "asusd.service",
|
||||
"state": "running"
|
||||
},
|
||||
{
|
||||
"id": "supergfxd",
|
||||
"type": "service",
|
||||
"unit": "supergfxd.service",
|
||||
"state": "running",
|
||||
"boot": "enabled"
|
||||
},
|
||||
{
|
||||
"id": "scripts",
|
||||
"type": "archive",
|
||||
"path": "/usr/local/lib/asus-zephyrus-g14",
|
||||
"artifact": "scripts"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-options",
|
||||
"type": "file",
|
||||
"path": "/etc/modprobe.d/g14-nvidia-power.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The discrete GPU's driver options on the ROG Zephyrus G14 (GA403, RTX 40 series, hybrid graphics).\n#\n# NVreg_DynamicPowerManagement=0x00 turns runtime D3 off. With it on, a change of power source sends\n# the driver an ACPI notification it fails to handle on this model (\"RmHandleDNotifierEvent: Failed to\n# handle ACPI D-Notifier event, status=0x62\"), and the GPU stops making progress until the machine is\n# powered off. Off costs a few idle watts in hybrid mode and keeps the machine up.\n#\n# NVreg_PreserveVideoMemoryAllocations=1 saves video memory across suspend, so what used the GPU still\n# works after waking. It needs nvidia-suspend, -hibernate and -resume to run around a sleep, which this\n# module's drop-ins on the sleep services ask for.\n#\n# A change here applies when the driver next loads: at the next boot.\noptions nvidia NVreg_PreserveVideoMemoryAllocations=1\noptions nvidia NVreg_DynamicPowerManagement=0x00\n"
|
||||
},
|
||||
{
|
||||
"id": "video-options",
|
||||
"type": "file",
|
||||
"path": "/etc/modprobe.d/video-brightness-switch.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The ACPI video driver does not change the backlight itself on the brightness keys: on this model it\n# moves the wrong one. The keys are triggerhappy's (see /etc/triggerhappy/triggers.d/asus-g14.conf).\n# Applies when the module next loads: at the next boot.\noptions video brightness_switch_enabled=0\n"
|
||||
},
|
||||
{
|
||||
"id": "suspend-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-suspend.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-suspend",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-suspend.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "hibernate-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-hibernate.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-hibernate",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-hibernate.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "suspend-then-hibernate-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "nvidia-on-suspend-then-hibernate",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/systemd-suspend-then-hibernate.service.d/asus-zephyrus-g14-nvidia.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The NVIDIA driver's own sleep actions, asked for by the sleep itself rather than enabled as\n# links: the mesh declares files and never makes links (novox/hq ADR 0012), and the host's service\n# shape must not start these units by hand, which would put the GPU to sleep with the machine awake.\n[Unit]\nWants=nvidia-suspend-then-hibernate.service nvidia-resume.service\n"
|
||||
},
|
||||
{
|
||||
"id": "powerd-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/systemd/system/nvidia-powerd.service.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "powerd-opt-in",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/nvidia-powerd.service.d/asus-zephyrus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# nvidia-powerd (Dynamic Boost) was the first error in the chain that hung this model's GPU on a change\n# of power source, and asusd starts it on mains. It runs only when the kernel command line says\n# zephyrus.nvidia-powerd — an explicit opt-in, at boot.\n[Unit]\nConditionKernelCommandLine=zephyrus.nvidia-powerd\n"
|
||||
},
|
||||
{
|
||||
"id": "backlight-rule",
|
||||
"type": "file",
|
||||
"path": "/etc/udev/rules.d/90-backlight.rules",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The backlights are writable by the video group, so the brightness keys and the module's brightness tool\n# move the panel without root.\nACTION==\"add\", SUBSYSTEM==\"backlight\", RUN+=\"/usr/bin/chgrp video /sys/class/backlight/%k/brightness\", RUN+=\"/usr/bin/chmod g+w /sys/class/backlight/%k/brightness\"\n"
|
||||
},
|
||||
{
|
||||
"id": "udev",
|
||||
"type": "service",
|
||||
"unit": "systemd-udevd.service",
|
||||
"reload-on": [
|
||||
"backlight-rule"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "upower-package",
|
||||
"type": "package",
|
||||
"package": "upower"
|
||||
},
|
||||
{
|
||||
"id": "upower-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/UPower/UPower.conf.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "low-battery",
|
||||
"type": "file",
|
||||
"path": "/etc/UPower/UPower.conf.d/50-asus-zephyrus-g14.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# On low battery the machine suspends rather than powering off, at 7 % — s2idle still draws a little,\n# so it leaves headroom. A drop-in over the package's own UPower.conf, which stays the package's.\n[UPower]\nUsePercentageForPolicy=true\nPercentageLow=15.0\nPercentageCritical=10.0\nPercentageAction=7.0\nCriticalPowerAction=Suspend\nAllowRiskyCriticalPowerAction=true\n"
|
||||
},
|
||||
{
|
||||
"id": "upower",
|
||||
"type": "service",
|
||||
"unit": "upower.service",
|
||||
"state": "running",
|
||||
"boot": "enabled",
|
||||
"restart-on": [
|
||||
"low-battery"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "xorg-drop-ins",
|
||||
"type": "directory",
|
||||
"path": "/etc/X11/xorg.conf.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "touchpad",
|
||||
"type": "file",
|
||||
"path": "/etc/X11/xorg.conf.d/30-asus-zephyrus-g14-touchpad.conf",
|
||||
"mode": "0644",
|
||||
"content": "# Managed by the mesh (module asus-zephyrus-g14). Replaced on every push; edit the catalogue instead.\n#\n# The touchpad's settings, applied by X every time the device appears — at login and after every\n# resume, when the device is initialised again. This replaces the predecessor's sleep hook, which ran\n# xinput after a resume as a named person on a guessed display.\nSection \"InputClass\"\n Identifier \"asus-zephyrus-g14 touchpad\"\n MatchIsTouchpad \"on\"\n Option \"Tapping\" \"on\"\n Option \"NaturalScrolling\" \"true\"\n Option \"AccelSpeed\" \"0.15\"\nEndSection\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools-go",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/zephyrus",
|
||||
"binary": "zephyrus",
|
||||
"loads": [
|
||||
"zephyrus"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "scripts",
|
||||
"kind": "archive",
|
||||
"from": "files"
|
||||
}
|
||||
]
|
||||
},
|
||||
"contributions": [
|
||||
{
|
||||
"seat": "node-hotkeys",
|
||||
"kind": "trigger",
|
||||
"content": "# The ROG Zephyrus G14's vendor keys, which reach no X client: media (the M-keys), panel brightness,\n# and the touchpad key. Each runs this module's own script, as the operator's account.\nKEY_PROG1\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media play-pause\nKEY_PROG3\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media previous\nKEY_PROG4\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-session /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-media next\nKEY_BRIGHTNESSDOWN\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSDOWN\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight -\nKEY_BRIGHTNESSUP\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_BRIGHTNESSUP\t2\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-backlight +\nKEY_F21\t1\t/usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
|
||||
},
|
||||
{
|
||||
"seat": "node-display-session",
|
||||
"kind": "config",
|
||||
"content": "# The laptop's own lines in i3 (module asus-zephyrus-g14, novox/hq ADR 0208, ADR 0210). Owned by the\n# mesh: replaced at every push. Once the controller places contributions to node-display-session\n# (ADR 0210), these become the module's contribution instead of a file in i3's directory.\n#\n# The keys the firmware turns into ordinary key presses. The vendor keys that reach no X client are\n# triggerhappy's (/etc/triggerhappy/triggers.d/asus-g14.conf): M4 and Fn+F4/F5 for media, Fn+F7/F8 for\n# the panel, Fn+F10 for the touchpad. The keyboard backlight (Fn+F2/F3) is the firmware's and asusd's.\n\n# Fn+F6, the screenshot key: the firmware sends Super+Shift+S. Released before it runs, because the\n# screenshot grabs the pointer to select a region, which fails while the key is still held.\nbindsym --release $mod+Shift+s exec --no-startup-id $XDG_CONFIG_HOME/i3/scripts/screenshot.sh\n\n# Fn+F9, the display key: the firmware sends Super+P. Odd workspaces to the panel, even ones to the\n# external output.\nbindsym $mod+p exec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-display order\n\n# The keyboard backlight's level, shown when it changes.\nexec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-kbd-notify\n"
|
||||
},
|
||||
{
|
||||
"seat": "node-display-session",
|
||||
"kind": "config",
|
||||
"content": "# The laptop's own lines in i3 (module asus-zephyrus-g14, novox/hq ADR 0208, ADR 0210). Owned by the\n# mesh: replaced at every push. Once the controller places contributions to node-display-session\n# (ADR 0210), these become the module's contribution instead of a file in i3's directory.\n#\n# The model's panel and touchpad.\n\n# The internal panel is the primary output, where the bars' tray goes. Which monitors are on and where\n# is the display server's (autorandr, run at every session start).\nexec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-display primary\n\n# The touchpad's settings again, by hand. X applies them itself whenever the device appears.\nbindsym $mod+Shift+x exec --no-startup-id /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\n"
|
||||
}
|
||||
],
|
||||
"shell": [
|
||||
{
|
||||
"for": "after-wake",
|
||||
"slot": "normal",
|
||||
"code": "# The touchpad's settings again after waking, in the operator's session: X applies the module's\n# input class when the device appears, and this covers a wake that does not initialise it again.\n# Runs as root from the power module; the reset itself runs as the session's owner.\nsleep 2\nowner=$(ps -o user= -C i3 | head -n 1)\n[ -n \"$owner\" ] && runuser -u \"$owner\" -- /usr/local/lib/asus-zephyrus-g14/bin/zephyrus-touchpad reset\ntrue\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -22,7 +22,7 @@ whenever the node's tool runtime collects the module's tools:
|
||||
| file | holds |
|
||||
|---|---|
|
||||
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh`, and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
|
||||
| `managed-settings.json` | the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, and the key-helper while the node holds an API-key licence |
|
||||
| `managed-settings.json` | the keys set in this module's `managed_settings` setting, under the mesh's own: the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, and the key-helper while the node holds an API-key licence |
|
||||
| `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions |
|
||||
|
||||
Under the operator's home, only `~/.claude/.credentials.json`, and only when the licence manager hands
|
||||
@@ -58,6 +58,12 @@ Per node or for the whole mesh, through `mesh-controller.settings module=claude-
|
||||
registered through the tools; keyed by name, in the vendor's `.mcp.json` entry shape
|
||||
(`{"type":"http","url":…}` or `{"type":"stdio","command":…,"args":[…]}`). The name `mesh` is the
|
||||
module's own and cannot be set. Put a person's own servers here, or they stop loading.
|
||||
- `managed_settings` — keys of the agent's managed settings, in the vendor's `settings.json` shape:
|
||||
`permissions` (allow, ask, deny), `autoMode` (environment, allow, soft_deny), `env`, hooks and so on.
|
||||
Managed settings outrank every other scope, so a rule here holds in every session on the node. The
|
||||
mesh's own keys (`attribution`, `allowAllClaudeAiMcps`, `apiKeyHelper`) are laid last and cannot be
|
||||
set. A setting layer is replaced whole: setting `managed_settings` without `role` or `mcp_servers`
|
||||
clears those in that layer.
|
||||
|
||||
## On a machine that carried the predecessor
|
||||
|
||||
|
||||
@@ -94,6 +94,40 @@ func TestASettingCannotReplaceTheMeshsOwnEntryAndABadNameIsLeftOut(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheOperatorsManagedSettingsAreLaidUnderTheMeshsOwnKeys(t *testing.T) {
|
||||
settings := Settings{ManagedSettings: map[string]any{
|
||||
"autoMode": map[string]any{"allow": []any{"merging an approved pull request"}},
|
||||
"permissions": map[string]any{"deny": []any{"Bash(rm -rf /)"}},
|
||||
"attribution": map[string]any{"commit": "made by a machine"},
|
||||
"allowAllClaudeAiMcps": false,
|
||||
"apiKeyHelper": "/somewhere/else",
|
||||
}}
|
||||
read := func(binding *Binding) map[string]any {
|
||||
var m map[string]any
|
||||
out := Render(Facts{Console: "x"}, settings, binding, "/h", nil)
|
||||
if err := json.Unmarshal([]byte(out["managed-settings.json"]), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
m := read(nil)
|
||||
if allow := m["autoMode"].(map[string]any)["allow"].([]any); len(allow) != 1 || allow[0] != "merging an approved pull request" {
|
||||
t.Errorf("the operator's auto mode was not carried: %v", m["autoMode"])
|
||||
}
|
||||
if m["permissions"] == nil {
|
||||
t.Errorf("the operator's permissions were not carried: %v", m)
|
||||
}
|
||||
if !reflect.DeepEqual(m["attribution"], map[string]any{"commit": "", "pr": ""}) || m["allowAllClaudeAiMcps"] != true {
|
||||
t.Errorf("a setting replaced the mesh's own keys: %v", m)
|
||||
}
|
||||
if _, ok := m["apiKeyHelper"]; ok {
|
||||
t.Errorf("a setting named a key-helper the licence did not: %v", m)
|
||||
}
|
||||
if helper := read(&Binding{Licence: "api", Kind: "api-key"})["apiKeyHelper"]; helper != "/h" {
|
||||
t.Errorf("an API-key licence's key-helper was replaced: %v", helper)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the credentials file -----------------------------------------------------------------------------
|
||||
|
||||
func i64(v int64) *int64 { return &v }
|
||||
@@ -362,3 +396,68 @@ func TestABadEntryIsRefusedBeforeAnythingIsPut(t *testing.T) {
|
||||
t.Fatal("another node's key changed this one")
|
||||
}
|
||||
}
|
||||
|
||||
// An API key goes to the manager sealed to its key, never in the clear, and its file is gone afterwards.
|
||||
func TestAnAPIKeyIsHandedOverSealedAndItsFileRemoved(t *testing.T) {
|
||||
p, _ := node(t, "laptop")
|
||||
manager, _ := GenerateKeyPair()
|
||||
file := filepath.Join(p.Home, "api-key")
|
||||
writeFile(t, file, "sk-ant-api03-secret\n")
|
||||
var sent []string
|
||||
ask := func(address string, args any) (json.RawMessage, error) {
|
||||
raw, _ := json.Marshal(args)
|
||||
sent = append(sent, address+" "+string(raw))
|
||||
switch address {
|
||||
case "seat:anthropic-licence-manager.public-key":
|
||||
return json.Marshal(map[string]any{"public_key": manager.PublicKey})
|
||||
case "seat:anthropic-licence-manager.adopt":
|
||||
box := args.(map[string]any)["sealed"].(SealedBox)
|
||||
if key, err := Open(box, manager.PrivateKey); err != nil || key != "sk-ant-api03-secret" {
|
||||
t.Fatalf("the manager opened %q, %v", key, err)
|
||||
}
|
||||
return json.Marshal(map[string]any{"adopted": true})
|
||||
case "seat:anthropic-licence-manager.switch":
|
||||
return json.Marshal(map[string]any{"licence": "api"})
|
||||
}
|
||||
t.Fatalf("asked %s", address)
|
||||
return nil, nil
|
||||
}
|
||||
out, err := AddAPIKey(p, "api", file, true, ask)
|
||||
if err != nil || out["file"] != "removed" || out["switched"] == nil {
|
||||
t.Fatalf("%v %v", out, err)
|
||||
}
|
||||
if _, err := os.Stat(file); !os.IsNotExist(err) {
|
||||
t.Fatal("the key file is still there")
|
||||
}
|
||||
if strings.Contains(strings.Join(sent, "\n"), "sk-ant") {
|
||||
t.Fatalf("the key crossed in the clear: %v", sent)
|
||||
}
|
||||
}
|
||||
|
||||
// A manager whose store was rebuilt counts generations from one again (novox/hq issue 243): a binding with a
|
||||
// lower generation than the one applied is still a binding to apply, and only the one applied is skipped.
|
||||
func TestALowerGenerationAfterTheManagerWasRebuiltIsStillApplied(t *testing.T) {
|
||||
p, w := node(t, "laptop")
|
||||
var asked []string
|
||||
if _, err := OnBinding(p, &BindingState{Licence: "personal", Kind: "subscription", Generation: 16},
|
||||
seat(t, "personal", "at-old", 16, &asked), writer(w)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The rotation that came with it: a later token, as a refresh hands one over.
|
||||
later := func(address string, args any) (json.RawMessage, error) {
|
||||
asked = append(asked, address)
|
||||
g, _ := json.Marshal(Grant{AccessToken: "at-new", ExpiresAt: now + 7_200_000})
|
||||
box, err := Seal(string(g), args.(map[string]any)["public_key"].(string))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return json.Marshal(Current{Licence: "personal", Kind: "subscription", Generation: 3, Sealed: &box})
|
||||
}
|
||||
if _, err := OnBinding(p, &BindingState{Licence: "personal", Kind: "subscription", Generation: 3},
|
||||
later, writer(w)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(asked) != 2 || creds(t, p)["accessToken"] != "at-new" || HoldingsOf(p).Generation != 3 {
|
||||
t.Fatalf("asked %v, credentials %v: a lower generation was ignored", asked, creds(t, p))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,6 +177,25 @@ func tools(p Paths, servers ServerState, view *ServerView) []stdio.Tool {
|
||||
}
|
||||
return GrantFor(p, key)
|
||||
}},
|
||||
{Name: "claude_code_add_api_key",
|
||||
Description: "Add an Anthropic API key as a licence (ADR 0209): read from a file on this machine — never typed as an argument — sealed to the licence manager's key, handed over, and the file removed once taken. With use_here, this machine switches to it at once; other machines move with the manager's `switch`.",
|
||||
Input: map[string]any{
|
||||
"name": str("the licence's name, e.g. api"),
|
||||
"file": str("a file on this machine holding the key, e.g. ~/api-key (removed once the manager has it)"),
|
||||
"use_here": map[string]any{"type": "boolean", "description": "switch this machine to the new licence"},
|
||||
},
|
||||
Run: func(a map[string]any) (any, error) {
|
||||
name, _ := a["name"].(string)
|
||||
file, _ := a["file"].(string)
|
||||
if strings.TrimSpace(name) == "" || strings.TrimSpace(file) == "" {
|
||||
return nil, errors.New("name and file are required")
|
||||
}
|
||||
if strings.HasPrefix(file, "~/") {
|
||||
file = filepath.Join(p.Home, file[2:])
|
||||
}
|
||||
useHere, _ := a["use_here"].(bool)
|
||||
return AddAPIKey(p, strings.TrimSpace(name), file, useHere, ask)
|
||||
}},
|
||||
{Name: "claude_code_mcp_list",
|
||||
Description: "The MCP servers registered through this module: those that apply on this node (beside the console, `mesh`, and those set in the module's settings), and every registration on the mesh, by key — `all.<server>` for every node, `<node>.<server>` for one.",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
|
||||
@@ -255,14 +255,19 @@ func Pull(p Paths, ask Ask, write WriteManaged) (map[string]any, error) {
|
||||
}
|
||||
|
||||
// OnBinding takes a change to this node's key in the manager's `bindings` state (ADR 0206): the token is
|
||||
// fetched when the generation is newer than the one applied. A released binding keeps the last token,
|
||||
// which lives hours, and says so.
|
||||
// fetched when the binding differs from the one applied. A released binding keeps the last token, which
|
||||
// lives hours, and says so.
|
||||
//
|
||||
// **Differs, not "is newer"** (novox/hq issue 243). The state keeps only the latest value per node, so
|
||||
// nothing older can arrive. A manager whose store was rebuilt counts generations from one again, and
|
||||
// a node that waited for a number above its own ignored every binding it was sent, its login and the
|
||||
// licence's rotations included, until the count caught up. Only the binding already applied is skipped.
|
||||
func OnBinding(p Paths, b *BindingState, ask Ask, write WriteManaged) (string, error) {
|
||||
if b == nil {
|
||||
return "this node's binding was released; it keeps its last token until it expires", nil
|
||||
}
|
||||
var applied Binding
|
||||
if readJSON(p.binding(), &applied) && applied.Generation >= b.Generation {
|
||||
if readJSON(p.binding(), &applied) && applied.Generation == b.Generation && applied.Licence == b.Licence {
|
||||
return "", nil
|
||||
}
|
||||
out, err := Pull(p, ask, write)
|
||||
@@ -343,6 +348,54 @@ func Apply(p Paths, c Current, write WriteManaged) (map[string]any, error) {
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AddAPIKey adds an API key from a file on this node to the licence manager (ADR 0209): sealed to the
|
||||
// manager's public key, handed to the seat's `adopt` on request/reply, and the file removed once taken. With
|
||||
// useHere, this node is switched to the new licence. The key never crosses the bus in the clear and is
|
||||
// never an argument.
|
||||
func AddAPIKey(p Paths, name, file string, useHere bool, ask Ask) (map[string]any, error) {
|
||||
raw, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the key is read from a file on this node: %w", err)
|
||||
}
|
||||
key := strings.TrimSpace(string(raw))
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("%s is empty", file)
|
||||
}
|
||||
answer, err := ask(SeatVerb("public-key"), map[string]any{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pk struct {
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
if err := json.Unmarshal(answer, &pk); err != nil || !strings.Contains(pk.PublicKey, "PUBLIC KEY") {
|
||||
return nil, errors.New("the licence manager did not say what key to seal to")
|
||||
}
|
||||
box, err := Seal(key, pk.PublicKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
adopted, err := ask(SeatVerb("adopt"), map[string]any{"name": name, "sealed": box, "from": p.Node})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := map[string]any{"adopted": json.RawMessage(adopted)}
|
||||
// Taken: the key now lives encrypted in the manager's store alone.
|
||||
if err := os.Remove(file); err != nil {
|
||||
out["file"] = "could not be removed: " + err.Error()
|
||||
} else {
|
||||
out["file"] = "removed"
|
||||
}
|
||||
if useHere {
|
||||
switched, err := ask(SeatVerb("switch"), map[string]any{"consumer": p.Node, "licence": name})
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("adopted, and switching this node to it failed: %w", err)
|
||||
}
|
||||
out["switched"] = json.RawMessage(switched)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ---- MCP servers ----------------------------------------------------------------------------------
|
||||
|
||||
// Registration is a server registered (or, with no entry, unregistered) through this module.
|
||||
|
||||
@@ -10,9 +10,11 @@ package main
|
||||
// servers the operator declared or registered through this module. Exclusive by
|
||||
// the vendor's rule — a server not listed here does not load (operator's choice,
|
||||
// 2026-10-03).
|
||||
// managed-settings.json the mesh's keys only: the repositories' attribution convention, the claude.ai
|
||||
// connectors kept beside the managed servers, and — for an API-key licence only —
|
||||
// the key-helper. A person's preferences are theirs.
|
||||
// managed-settings.json the keys the operator set in this module's `managed_settings` (the agent's
|
||||
// permissions and auto mode, say), under the mesh's own keys, which always win:
|
||||
// the repositories' attribution convention, the claude.ai connectors kept beside
|
||||
// the managed servers, and — for an API-key licence only — the key-helper. A
|
||||
// person's preferences are theirs, in their own settings.
|
||||
// CLAUDE.md how a session on this mesh works, who this node is, the conventions.
|
||||
|
||||
import (
|
||||
@@ -38,6 +40,8 @@ type Facts struct {
|
||||
type Settings struct {
|
||||
Role string `json:"role"`
|
||||
MCPServers map[string]map[string]any `json:"mcp_servers"`
|
||||
// ManagedSettings are keys of the agent's managed settings the operator sets, for the mesh or a node.
|
||||
ManagedSettings map[string]any `json:"managed_settings"`
|
||||
}
|
||||
|
||||
// Binding is the licence this node holds, as it was last applied.
|
||||
@@ -105,7 +109,14 @@ func Render(facts Facts, settings Settings, binding *Binding, helperPath string,
|
||||
}
|
||||
servers[meshEntry] = map[string]any{"type": "http", "url": facts.Console}
|
||||
|
||||
managed := map[string]any{"attribution": map[string]any{"commit": "", "pr": ""}, "allowAllClaudeAiMcps": true}
|
||||
managed := map[string]any{}
|
||||
for key, value := range settings.ManagedSettings {
|
||||
managed[key] = value
|
||||
}
|
||||
// The mesh's own keys are laid last: a setting never replaces them.
|
||||
managed["attribution"] = map[string]any{"commit": "", "pr": ""}
|
||||
managed["allowAllClaudeAiMcps"] = true
|
||||
delete(managed, "apiKeyHelper")
|
||||
if binding != nil && binding.Kind == "api-key" {
|
||||
managed["apiKeyHelper"] = helperPath
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"claude_code_render",
|
||||
"claude_code_pull",
|
||||
"claude_code_grant",
|
||||
"claude_code_add_api_key",
|
||||
"claude_code_mcp_list",
|
||||
"claude_code_mcp_register",
|
||||
"claude_code_mcp_unregister"
|
||||
@@ -68,7 +69,7 @@
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"merge": "json",
|
||||
"content": "{\n \"role\": \"\",\n \"mcp_servers\": {}\n}\n"
|
||||
"content": "{\n \"role\": \"\",\n \"mcp_servers\": {},\n \"managed_settings\": {}\n}\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
|
||||
@@ -290,7 +290,7 @@ func tools() []stdio.Tool {
|
||||
}
|
||||
return m.Bind(ctx, c, l, "bind")
|
||||
}),
|
||||
verb("switch", "Move a consumer to another licence. Its node fetches the new licence's token at once and points the agent's account at it.",
|
||||
verb("switch", "Move a consumer to another licence. Its node fetches the new licence's token at once and points the agent's account at it. A login on a node does this by itself (ADR 0209); this is for moving one without a login, or back.",
|
||||
map[string]any{"consumer": consumer, "licence": str("the licence to move to")},
|
||||
func(ctx context.Context, m *Manager, a map[string]any) (any, error) {
|
||||
c, l, err := two(a, "consumer", "licence")
|
||||
@@ -326,15 +326,34 @@ func tools() []stdio.Tool {
|
||||
}
|
||||
return m.Store.Usage(ctx, l, limit)
|
||||
}),
|
||||
verb("adopt", "Adopt an API key from a file on the manager's node, never as an argument. Subscriptions are adopted from the nodes' logins by themselves.",
|
||||
map[string]any{"name": str("the licence's name"), "file": str("a file on the manager's node holding the key")},
|
||||
verb("adopt", "Adopt an API key — never as an argument: from a file on the manager's node (`file`), or sealed to the manager's `public-key` by a node's claude-code (`sealed`; its `claude_code_add_api_key` does this). Subscriptions are adopted from the nodes' logins by themselves.",
|
||||
map[string]any{"name": str("the licence's name"), "file": str("a file on the manager's node holding the key"),
|
||||
"sealed": map[string]any{"type": "object", "description": "the key sealed to the manager's public key"},
|
||||
"from": str("which node it came from, for the audit")},
|
||||
func(ctx context.Context, m *Manager, a map[string]any) (any, error) {
|
||||
n, f, err := two(a, "name", "file")
|
||||
n, err := text(a, "name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if raw, ok := a["sealed"]; ok && raw != nil {
|
||||
b, _ := json.Marshal(raw)
|
||||
var box SealedBox
|
||||
if err := json.Unmarshal(b, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
from, _ := a["from"].(string)
|
||||
return m.AdoptSealedKey(ctx, n, box, "a node: "+from)
|
||||
}
|
||||
f, err := text(a, "file")
|
||||
if err != nil {
|
||||
return nil, errors.New("adopt takes a `file` on the manager's node, or a `sealed` key")
|
||||
}
|
||||
return m.AdoptKey(ctx, n, f)
|
||||
}),
|
||||
verb("public-key", "The manager's public key, PEM: what a node seals an API key or a login to before handing it over.",
|
||||
nil, func(_ context.Context, m *Manager, _ map[string]any) (any, error) {
|
||||
return map[string]any{"public_key": m.Keys.PublicKey}, nil
|
||||
}),
|
||||
verb("current", "For a consumer's agent module (ADR 0206): its token, sealed to the public key it sends, with the licence, kind and generation. Null when it is bound to nothing.",
|
||||
map[string]any{"consumer": consumer, "public_key": str("the consumer's public key, PEM")},
|
||||
func(ctx context.Context, m *Manager, a map[string]any) (any, error) {
|
||||
|
||||
@@ -49,6 +49,8 @@ type Holdings struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
} `json:"refresh"`
|
||||
ChangedAt string `json:"changedAt"`
|
||||
// Generation is the binding generation the node last applied (novox/hq issue 243).
|
||||
Generation int64 `json:"generation"`
|
||||
}
|
||||
|
||||
// BindingState is what `bindings` holds for one consumer: no secret, only what it should hold and which
|
||||
@@ -189,6 +191,17 @@ func (m *Manager) CandidatesIn(ctx context.Context, reports []Holdings) (map[str
|
||||
// newest first; the first that refreshes is adopted and the rest are settled as skipped without being
|
||||
// exchanged. Answers what was adopted.
|
||||
func (m *Manager) Consider(ctx context.Context, reports []Holdings) ([]string, error) {
|
||||
// **Never a generation a node has already passed** (novox/hq issue 243). A store rebuilt after a loss
|
||||
// counts from one again, while every node still holds the number it last applied. The nodes no longer
|
||||
// wait for a higher number, but a binding numbered exactly as the one a node applied would still be
|
||||
// skipped. So the count is moved past every number reported, before anything here binds.
|
||||
var highest int64
|
||||
for _, r := range reports {
|
||||
highest = max(highest, r.Generation)
|
||||
}
|
||||
if err := m.Store.GenerationsAbove(ctx, highest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
byAccount, err := m.CandidatesIn(ctx, reports)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -336,7 +349,24 @@ func (m *Manager) adoptOne(ctx context.Context, c Candidate, reports []Holdings)
|
||||
_ = m.Store.Audit(ctx, "adopted", map[string]any{"licence": l.Name, "node": c.Node, "account": c.Identity.AccountUUID,
|
||||
"vendorNamedAccount": r.Account != ""})
|
||||
|
||||
// A first binding follows the login (ADR 0206 §7): every node reporting this account and bound to nothing.
|
||||
// A login moves its node (ADR 0209): the node this login came from is bound to its licence —
|
||||
// switched, if it was bound to another. Then every node reporting this account and bound to nothing.
|
||||
if b, err := m.Store.Binding(ctx, c.Node); err != nil {
|
||||
return "", err
|
||||
} else if b == nil || b.Licence != l.Name {
|
||||
if _, err := m.Store.Bind(ctx, c.Node, l.Name); err != nil {
|
||||
return "", err
|
||||
}
|
||||
from := ""
|
||||
if b != nil {
|
||||
from = b.Licence
|
||||
}
|
||||
_ = m.Store.Audit(ctx, map[bool]string{true: "switched", false: "bound"}[b != nil],
|
||||
map[string]any{"consumer": c.Node, "licence": l.Name, "from": from, "by": "a login there"})
|
||||
if b != nil {
|
||||
m.Log("%s moved from %s to %s: a login there", c.Node, from, l.Name)
|
||||
}
|
||||
}
|
||||
for _, rep := range reports {
|
||||
if rep.Identity == nil || rep.Identity.AccountUUID != c.Identity.AccountUUID {
|
||||
continue
|
||||
@@ -612,16 +642,29 @@ var licenceName = regexp.MustCompile(`^[A-Za-z0-9@._-]+$`)
|
||||
|
||||
// AdoptKey adopts an API key from a file on this node — never an argument (design 39 §6).
|
||||
func (m *Manager) AdoptKey(ctx context.Context, name, file string) (map[string]any, error) {
|
||||
if !licenceName.MatchString(name) {
|
||||
return nil, fmt.Errorf("%q is not a licence name: letters, digits and @._-", name)
|
||||
}
|
||||
raw, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := strings.TrimSpace(string(raw))
|
||||
return m.adoptKey(ctx, name, strings.TrimSpace(string(raw)), "a file on "+m.Holder)
|
||||
}
|
||||
|
||||
// AdoptSealedKey adopts an API key sealed to this module's public key by a node's agent module (ADR 0209):
|
||||
// the key crosses the bus only sealed, on request/reply.
|
||||
func (m *Manager) AdoptSealedKey(ctx context.Context, name string, box SealedBox, from string) (map[string]any, error) {
|
||||
key, err := Open(box, m.Keys.PrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.adoptKey(ctx, name, strings.TrimSpace(key), from)
|
||||
}
|
||||
|
||||
func (m *Manager) adoptKey(ctx context.Context, name, key, from string) (map[string]any, error) {
|
||||
if !licenceName.MatchString(name) {
|
||||
return nil, fmt.Errorf("%q is not a licence name: letters, digits and @._-", name)
|
||||
}
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("%s is empty", file)
|
||||
return nil, errors.New("the key is empty")
|
||||
}
|
||||
held, err := m.Store.Licence(ctx, name)
|
||||
if err != nil {
|
||||
@@ -634,11 +677,11 @@ func (m *Manager) AdoptKey(ctx context.Context, name, file string) (map[string]a
|
||||
if err := m.Store.SaveLicence(ctx, l); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = m.Store.Audit(ctx, "adopted", map[string]any{"licence": name, "kind": "api-key", "from": "a file"})
|
||||
_ = m.Store.Audit(ctx, "adopted", map[string]any{"licence": name, "kind": "api-key", "from": from})
|
||||
if err := m.publishAdvance(ctx, l); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = m.Emit("licence.adopted", map[string]any{"licence": name, "from": "a file", "replaced": held != nil})
|
||||
_ = m.Emit("licence.adopted", map[string]any{"licence": name, "from": from, "replaced": held != nil})
|
||||
return map[string]any{"licence": name, "kind": "api-key", "adopted": true, "fingerprint": Fingerprint(key)}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -357,3 +357,84 @@ func TestANodeReportingAnAdoptedAccountLaterIsBoundToIt(t *testing.T) {
|
||||
t.Fatal("a node already bound was bound again")
|
||||
}
|
||||
}
|
||||
|
||||
// A login to another account on one node adopts it and moves that node, and only that node (ADR 0209).
|
||||
func TestALoginToAnotherAccountMovesItsNodeAndNoOther(t *testing.T) {
|
||||
mm := newMesh(t)
|
||||
ctx := context.Background()
|
||||
_, _ = mm.m.Consider(ctx, []Holdings{mm.login("laptop", "rt-a", true, t0), mm.report("server", "", t0, "acct-1")})
|
||||
if mm.state["laptop"].Licence != licence1 || mm.state["server"].Licence != licence1 {
|
||||
t.Fatalf("%v", mm.state)
|
||||
}
|
||||
mm.now = t0.Add(time.Hour)
|
||||
mm.logins["laptop"] = FullGrant{AccessToken: "local", RefreshToken: "rt-b", ExpiresAt: 1}
|
||||
mm.vendor.live["rt-b"] = true
|
||||
second := mm.report("laptop", "rt-b", t0.Add(time.Hour), "acct-2")
|
||||
adopted, _ := mm.m.Consider(ctx, []Holdings{second, mm.report("server", "", t0, "acct-1")})
|
||||
if len(adopted) != 1 || adopted[0] != "acct-2@example.org" {
|
||||
t.Fatalf("adopted %v", adopted)
|
||||
}
|
||||
if mm.state["laptop"].Licence != "acct-2@example.org" {
|
||||
t.Fatalf("the node a login was made on stayed bound to %v", mm.state["laptop"])
|
||||
}
|
||||
if mm.state["server"].Licence != licence1 {
|
||||
t.Fatalf("another node moved: %v", mm.state["server"])
|
||||
}
|
||||
ls, _ := mm.store.Licences(ctx)
|
||||
if len(ls) != 2 {
|
||||
t.Fatalf("%d licences", len(ls))
|
||||
}
|
||||
}
|
||||
|
||||
// A login that does not refresh moves nothing.
|
||||
func TestALoginThatDoesNotRefreshMovesNothing(t *testing.T) {
|
||||
mm := newMesh(t)
|
||||
ctx := context.Background()
|
||||
_, _ = mm.m.Consider(ctx, []Holdings{mm.login("laptop", "rt-a", true, t0)})
|
||||
g := mm.state["laptop"]
|
||||
mm.logins["laptop"] = FullGrant{AccessToken: "local", RefreshToken: "rt-dead", ExpiresAt: 1}
|
||||
_, _ = mm.m.Consider(ctx, []Holdings{mm.report("laptop", "rt-dead", t0.Add(time.Hour), "acct-2")})
|
||||
if mm.state["laptop"] != g {
|
||||
t.Fatalf("a dead login moved its node: %v", mm.state["laptop"])
|
||||
}
|
||||
}
|
||||
|
||||
// An API key sealed to the manager by a node is adopted, and opens only for the manager.
|
||||
func TestAnAPIKeySealedByANodeIsAdopted(t *testing.T) {
|
||||
mm := newMesh(t)
|
||||
ctx := context.Background()
|
||||
box, _ := Seal("sk-ant-api03-test\n", mm.keys.PublicKey)
|
||||
r, err := mm.m.AdoptSealedKey(ctx, "api", box, "laptop")
|
||||
if err != nil || r["adopted"] != true {
|
||||
t.Fatalf("%v %v", r, err)
|
||||
}
|
||||
l, _ := mm.store.Licence(ctx, "api")
|
||||
if plain, _ := mm.m.Crypt.Open(l.Sealed); plain != "sk-ant-api03-test" {
|
||||
t.Fatalf("stored %q", plain)
|
||||
}
|
||||
other, _ := GenerateKeyPair()
|
||||
wrong, _ := Seal("sk", other.PublicKey)
|
||||
if _, err := mm.m.AdoptSealedKey(ctx, "api2", wrong, "laptop"); err == nil {
|
||||
t.Fatal("a key sealed to another key was adopted")
|
||||
}
|
||||
for _, e := range mm.events {
|
||||
if strings.Contains(e, "sk-ant") {
|
||||
t.Fatalf("the key was published: %s", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A store rebuilt after a loss counts generations from one again (novox/hq issue 243): the first look at the
|
||||
// reports moves the count past every generation a node says it applied, so no binding repeats one.
|
||||
func TestARebuiltStoreNeverGivesAGenerationANodeHasPassed(t *testing.T) {
|
||||
mm := newMesh(t)
|
||||
ctx := context.Background()
|
||||
laptop := mm.login("laptop", "rt-a", true, t0)
|
||||
laptop.Generation = 16
|
||||
if _, err := mm.m.Consider(ctx, []Holdings{laptop}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if g := mm.state["laptop"].Generation; g <= 16 {
|
||||
t.Fatalf("the laptop applied generation 16 and was given %d", g)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +225,16 @@ func (s *PgStore) Unbind(ctx context.Context, consumer string) (bool, error) {
|
||||
return err == nil && tag.RowsAffected() == 1, err
|
||||
}
|
||||
|
||||
func (s *PgStore) GenerationsAbove(ctx context.Context, generation int64) error {
|
||||
if generation <= 0 {
|
||||
return nil
|
||||
}
|
||||
// setval with is_called, so the next nextval is generation+1; only ever forward.
|
||||
_, err := s.pool.Exec(ctx, `select setval('binding_generation', $1, true) from binding_generation
|
||||
where not is_called or last_value < $1`, generation)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *PgStore) Advance(ctx context.Context, licence string) ([]Binding, error) {
|
||||
return s.bindingsWhere(ctx, `update binding set generation = nextval('binding_generation') where licence = $1
|
||||
returning consumer, licence, generation`, licence)
|
||||
|
||||
@@ -70,6 +70,8 @@ type Store interface {
|
||||
Unbind(ctx context.Context, consumer string) (bool, error)
|
||||
// Advance gives every consumer of a licence a new generation: what a rotation is to them.
|
||||
Advance(ctx context.Context, licence string) ([]Binding, error)
|
||||
// GenerationsAbove makes every generation given from now on greater than this one.
|
||||
GenerationsAbove(ctx context.Context, generation int64) error
|
||||
Outcome(ctx context.Context, fingerprint string) (Outcome, error)
|
||||
RecordOutcome(ctx context.Context, fingerprint, node, account string, o Outcome, why string) error
|
||||
RecordUsage(ctx context.Context, licence string, at int64, r UsageReading, raw map[string]any) error
|
||||
@@ -200,6 +202,13 @@ func (m *MemoryStore) Unbind(_ context.Context, consumer string) (bool, error) {
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func (m *MemoryStore) GenerationsAbove(_ context.Context, generation int64) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.generation = max(m.generation, generation)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemoryStore) Advance(_ context.Context, licence string) ([]Binding, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
"refresh",
|
||||
"usage",
|
||||
"adopt",
|
||||
"current"
|
||||
"current",
|
||||
"public-key"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -50,7 +51,8 @@
|
||||
"refresh",
|
||||
"usage",
|
||||
"adopt",
|
||||
"current"
|
||||
"current",
|
||||
"public-key"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -67,3 +67,23 @@ would empty whenever the runtime restarted.
|
||||
them, `mctl` reads them as unknown.
|
||||
- `CM_*` reach the session through `node-env` (ADR 0203), so the account's environment module must
|
||||
be assigned too. Without it clipmenu runs on its defaults: both selections, 1000 clips, 8 lines.
|
||||
|
||||
## Only text is read (added 2026-10-04)
|
||||
|
||||
clipmenud reads a selection with `timeout 1 xsel -o`. A selection holding an image, such as a
|
||||
screenshot copied as `image/png`, arrives in pieces. One second is too short for megabytes, so
|
||||
`timeout` kills xsel half way, and the program owning the image waits for ever for a reader that is
|
||||
gone. From then on every paste hangs, and an app asking on its main thread (Electron: Slack) freezes.
|
||||
The first screenshot after this module was assigned did exactly that.
|
||||
|
||||
So clipmenud runs with the module's own `xsel` first on its `PATH`
|
||||
(`/usr/local/lib/mesh-clipmenu/xsel`). Before a read it asks the selection for its `TARGETS` and goes
|
||||
ahead only when the selection offers text. It uses `xclip` for that question, which the `xclip`
|
||||
module installs on every workstation.
|
||||
|
||||
## Its i3 lines are a contribution (changed 2026-10-05, novox/hq ADR 0212)
|
||||
|
||||
The module no longer writes a file into i3's `config.d`. Its window-manager lines (the source is still
|
||||
under `files/i3/` where it had one) are a contribution to `node-display-session`. The i3 module places
|
||||
them in its own configuration under a `# <module>` line, so this module depends on a window manager
|
||||
being assigned beside it.
|
||||
|
||||
@@ -22,7 +22,9 @@ type manifest struct {
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Build struct {
|
||||
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
|
||||
Contributions []contribution `json:"contributions"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
@@ -173,3 +175,32 @@ func checkNoSecretsOrInstallationNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type contribution struct {
|
||||
Seat string `json:"seat"`
|
||||
Kind string `json:"kind"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// i3Lines is what the module contributes to the window manager.
|
||||
func (m manifest) i3Lines() string {
|
||||
var out string
|
||||
for _, c := range m.Contributions {
|
||||
if c.Seat == "node-display-session" && c.Kind == "config" {
|
||||
out += c.Content
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// i3LinesAreSource checks the window-manager contribution is the source file it is written from.
|
||||
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
t.Helper()
|
||||
want, err := os.ReadFile(filepath.Join("..", "..", source))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.i3Lines() != string(want) {
|
||||
t.Fatalf("the contribution to node-display-session is not %s: edit the source and copy it into module.json", source)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,9 @@ func TestTheDaemonStartsOnceFromTheSessionsStart(t *testing.T) {
|
||||
t.Fatalf("%+v", m.Shell)
|
||||
}
|
||||
code := m.Shell[0].Code
|
||||
if strings.Count(code, "\nclipmenud &\n") != 1 || strings.Contains(code, "greenclip") {
|
||||
// Started once, through the module's text-only xsel (a selection holding an image is never read).
|
||||
if strings.Count(code, "clipmenud &\n") != 1 || !strings.Contains(code, `PATH="/usr/local/lib/mesh-clipmenu:$PATH" clipmenud &`) ||
|
||||
strings.Contains(code, "greenclip") {
|
||||
t.Fatalf("%q", code)
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
@@ -51,8 +53,8 @@ func TestItsSettingsAreEnvironmentAndItsMenuIsTheLaunchersDmenu(t *testing.T) {
|
||||
if _, set := m.Environment.Variables["CM_LAUNCHER"]; set {
|
||||
t.Fatal("the launcher is clipmenu's default, dmenu: the seat's command")
|
||||
}
|
||||
m.sameAsSource(t, "i3-bindings", "files/i3/50-clipmenu.conf")
|
||||
if c := m.resource(t, "i3-bindings")["content"].(string); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
|
||||
m.i3LinesAreSource(t, "files/i3/50-clipmenu.conf")
|
||||
if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
|
||||
t.Fatalf("%s", c)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
{
|
||||
"for": "xinitrc",
|
||||
"slot": "normal",
|
||||
"code": "# The clipboard's history (module clipmenu, novox/hq ADR 0208): clipmenud collects every copy from\n# here on, once per session. It keeps the history in the account's runtime directory, so a reboot\n# forgets it, and with it every password that was ever copied.\nclipmenud &\n"
|
||||
"code": "# The clipboard's history (module clipmenu, novox/hq ADR 0208): clipmenud collects every copy from\n# here on, once per session. It keeps the history in the account's runtime directory, so a reboot\n# forgets it, and with it every password that was ever copied.\n# Through the module's xsel, which reads only a selection offering text (see the README).\nPATH=\"/usr/local/lib/mesh-clipmenu:$PATH\" clipmenud &\n"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
@@ -49,12 +49,11 @@
|
||||
"absent": true
|
||||
},
|
||||
{
|
||||
"id": "i3-bindings",
|
||||
"id": "text-only",
|
||||
"type": "file",
|
||||
"path": "${machine:account-home}/.config/i3/config.d/50-clipmenu.conf",
|
||||
"owner": "${machine:account}",
|
||||
"mode": "0644",
|
||||
"content": "# The clipboard's history key (module clipmenu, novox/hq ADR 0208). Owned by the mesh: replaced at\n# every push. clipmenu shows the history through `dmenu`, the node's dmenu-compatible command, which\n# the holder of node-launcher answers (rofi on the workstations); the chosen entry is put back on the\n# clipboard.\nbindsym $mod+period exec --no-startup-id clipmenu -p Clipboard\n"
|
||||
"path": "/usr/local/lib/mesh-clipmenu/xsel",
|
||||
"mode": "0755",
|
||||
"content": "#!/bin/sh\n# xsel as clipmenud sees it, written by the mesh (module clipmenu). Replaced at every push.\n#\n# clipmenud records text, and reads a selection with `timeout 1 xsel -o`. A selection holding an\n# image (a screenshot copied as image/png) is sent in pieces; one second is too short for megabytes,\n# timeout kills xsel half way, and the program owning the image waits for ever for a reader that is\n# gone. From then on nothing can ask the clipboard anything: pastes hang, and an Electron app that\n# asks on its main thread freezes. So a read goes ahead only when the selection offers text.\ncase \" $* \" in\n*\" -o \"* | *\" --output \"*)\n\tselection=clipboard\n\tcase \" $* \" in\n\t*\" --primary \"* | *\" -p \"*) selection=primary ;;\n\t*\" --secondary \"* | *\" -s \"*) selection=secondary ;;\n\tesac\n\ttargets=$(timeout 1 xclip -selection \"$selection\" -t TARGETS -o 2>/dev/null) || exit 1\n\tprintf '%s\\n' \"$targets\" | grep -qxE 'UTF8_STRING|STRING|TEXT|text/plain(;charset=utf-8)?' || exit 1\n\t;;\nesac\nexec /usr/bin/xsel \"$@\"\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
@@ -71,5 +70,12 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"contributions": [
|
||||
{
|
||||
"seat": "node-display-session",
|
||||
"kind": "config",
|
||||
"content": "# The clipboard's history key (module clipmenu, novox/hq ADR 0208). Owned by the mesh: replaced at\n# every push. clipmenu shows the history through `dmenu`, the node's dmenu-compatible command, which\n# the holder of node-launcher answers (rofi on the workstations); the chosen entry is put back on the\n# clipboard.\nbindsym $mod+period exec --no-startup-id clipmenu -p Clipboard\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# dbus
|
||||
|
||||
A machine's message bus (novox/hq ADR 0215). This module holds `node-message-bus` on every machine,
|
||||
servers included, because every machine runs a D-Bus system bus. It owns the bus implementation's
|
||||
packages and declares its system service running. It publishes what matters about the bus on the
|
||||
mesh's bus, and serves tools to look at the system bus and at the operator's session bus.
|
||||
|
||||
## What it owns
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| package `dbus-broker` | the bus every machine runs |
|
||||
| package `dbus-broker-units` | `dbus.service` as an alias of `dbus-broker.service`, for the system and for each user |
|
||||
| package `dbus` | the bus's configuration (`system.conf`, `session.conf`), `dbus.socket`, which starts the bus at boot, and libdbus |
|
||||
| service `dbus-broker.service` | declared running, with no boot state and no restart or reload trigger (below) |
|
||||
|
||||
All four machines were found with dbus-broker 37 behind `dbus.service` and dbus 1.16.2, from the
|
||||
distribution. One server also has an old `dbus-units` package, an empty package that depends on
|
||||
`dbus-broker-units`. It is not declared: nothing needs it, and removing it is a choice for its
|
||||
operator.
|
||||
|
||||
## The bus is never restarted live
|
||||
|
||||
On 2026-10-04 a full upgrade on a workstation restarted the system bus while the upgrade was still
|
||||
running. From then on every login hung, sshd answered nothing and the machine's host stopped
|
||||
reporting, until someone rebooted it at its keyboard. Every program that speaks on the bus (the
|
||||
service manager, logind, the network manager, the keyring, the power module's sleep lock) holds a
|
||||
connection to it. A restart takes all of them away at once, and not all of them come back.
|
||||
|
||||
So the module never restarts or reloads the bus, for any change. Its service has no `restart-on` and
|
||||
no `reload-on`, and the host never restarts a service that has neither. A new bus takes effect at
|
||||
the next boot. `dbus_check` says when the running bus is older than an installed package, which is
|
||||
the sign that a reboot is due. The distribution's own upgrade can still restart the bus. This rule
|
||||
covers what the mesh does, not what pacman does.
|
||||
|
||||
**Why `state: running` and no `boot`.** `dbus.service` is an alias (`systemctl is-enabled` says
|
||||
`alias`), so it cannot be declared enabled: the host would run `systemctl enable` and read back
|
||||
something other than `enabled`. The real unit, `dbus-broker.service`, reads `disabled` on three
|
||||
machines and `enabled` on one. It needs no enabling. At boot `dbus.socket`, which the `dbus` package
|
||||
links into `sockets.target`, pulls in `dbus.service`, and `dbus-broker-units` ships that name as a
|
||||
link to `dbus-broker.service`. On the three machines where it reads `disabled`, enabling it would
|
||||
only write a second alias link into `/etc`, and a module's apply would change something on a running
|
||||
machine for no gain. The service is declared so that the mesh knows the bus is the module's and says
|
||||
so when it is not running. A host finding it stopped would start it, which can only help a machine
|
||||
whose bus is down. ADR 0215 §1 says "running and enabled". On these machines the package's own
|
||||
socket link is what makes it start at boot.
|
||||
|
||||
**A policy change** a module needs in the future uses the bus's own reload (`dbus-broker.service` is
|
||||
`Type=notify-reload`), which keeps every connection. No module needs one today (below).
|
||||
|
||||
## Events
|
||||
|
||||
The watcher runs beside the tools in the same process, on its own connection to the system bus as the
|
||||
operator's account. It reads only the bus driver's answers, the driver's `NameOwnerChanged` signal and
|
||||
the bus unit's journal.
|
||||
|
||||
| event | when | carries |
|
||||
|---|---|---|
|
||||
| `bus.stalled` | the bus does not answer the driver's `GetId` within 3 s, or cannot be reached | the reason |
|
||||
| `bus.recovered` | a stalled bus answers again | since when it was stalled, and for how long |
|
||||
| `bus.restarted` | after reconnecting, the bus's id or the driver's pid has changed within the same boot (after a boot both change, and `power` says `booted`) | the old and new id and pid, the unit |
|
||||
| `service.appeared` | a well-known name appears and is still there 10 s later | the name, the owner's pid, process and unit, whether it is activatable |
|
||||
| `service.left` | a well-known name is gone and still gone 10 s later | the name and what held it |
|
||||
| `policy.denied` | the bus logged a policy denial, at most once per 5 minutes | how many since the last one, and up to 5 distinct examples: the refused message's type, sender, destination, path, interface and member |
|
||||
|
||||
Unique names (`:1.42`) come and go with every client and are never published. A service restarted
|
||||
within the 10 s, or one that came and went, publishes nothing. Activatable services that exit when
|
||||
idle, such as hostnamed, do appear and leave, and their events say `activatable: true`.
|
||||
|
||||
**Why traffic never leaves the machine.** The bus carries secrets from the keyring, notification text
|
||||
and the clipboard. The watcher never becomes a monitor, so it never sees another peer's messages. Its
|
||||
events are built from names, pids, units and the header fields the broker logs with a denial. The log
|
||||
line itself is not passed on. The tests hold every event's body to those fields.
|
||||
|
||||
Events the mesh's bus does not take wait in order and go out when it answers again, as `power`'s do.
|
||||
At most 1000 events wait. When there are more, the oldest are dropped and counted.
|
||||
|
||||
The watcher's ping is `GetId`, not `org.freedesktop.DBus.Peer.Ping`. The system policy refuses the
|
||||
peer ping to an account that is not root and logs a denial each time, which the watcher would then
|
||||
publish.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | |
|
||||
|---|---|
|
||||
| `dbus_names` | `bus`: system or session. Every well-known name with its owner's pid, process, user and unit, the activatable names that are not running, and the number of connections |
|
||||
| `dbus_introspect` | `bus`, `service`, `path`. The object's interfaces with their methods, properties (type and access, never values) and signals, and its children. Uses `--auto-start=no`, so looking never starts a service |
|
||||
| `dbus_monitor` | `bus`, `seconds` (at most 15), optional `match` rule and `names`. The headers of what passed (type, sender, destination, path, interface, member, error name), at most 500. Never a body: each line is decoded into the header alone. On the system bus only root may monitor, so it runs through `sudo -n` |
|
||||
| `dbus_check` | the packages are installed. `dbus.service` is `dbus-broker.service` and active. The running bus is not older than the installed `dbus-broker` or `dbus` (otherwise a reboot is due). Every activatable service file's `SystemdService` exists. Policy denials in the last hour. The watcher is connected, not stalled, and has nothing stuck |
|
||||
| `dbus_health` | the round trip of a ping on the watcher's connection, the connection count (from `Debug.Stats` through `sudo -n`, else the unique names), and the bus's unit, pid, start and uptime |
|
||||
|
||||
Every command is bounded at 20 s and its output read up to 1 MiB. Lists stop at 500 entries.
|
||||
`Debug.Stats` is asked only as root: asked as the account it is refused and logged as a denial.
|
||||
|
||||
The session bus is the runtime's `DBUS_SESSION_BUS_ADDRESS`, else `$XDG_RUNTIME_DIR/bus`, else
|
||||
`/run/user/<uid>/bus`. On a machine where the account has no session, the tools say so.
|
||||
|
||||
The check notes, without failing, systemd's own services whose `dbus-org.*` alias is missing because
|
||||
they are not enabled, such as resolved, networkd and homed on the workstations. Activating them fails
|
||||
by design.
|
||||
|
||||
## Assignment
|
||||
|
||||
On every machine, as the first holder of `node-message-bus`. The module needs nothing set: no
|
||||
settings, no secrets, no ports.
|
||||
|
||||
## What comes later
|
||||
|
||||
ADR 0215 §4: the seat receives nothing yet. Packages ship their own D-Bus policy and service files,
|
||||
and no module writes one of its own. When one does, that file will be a contribution to this seat,
|
||||
and this module will list the kind and reload the bus's policy for it, without a restart.
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
busName = "org.freedesktop.DBus"
|
||||
busPath = "/org/freedesktop/DBus"
|
||||
)
|
||||
|
||||
// systemBus is the machine's system bus as the watcher uses it, over its own private connection: the
|
||||
// bus driver's answers and its NameOwnerChanged signal, never another peer's messages.
|
||||
type systemBus struct {
|
||||
conn *dbus.Conn
|
||||
out chan NameChange
|
||||
}
|
||||
|
||||
// DialSystemBus connects to the system bus as this account and listens for names changing owner.
|
||||
func DialSystemBus() (Bus, error) {
|
||||
conn, err := dbus.SystemBusPrivate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := conn.Auth(nil); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := conn.Hello(); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := conn.AddMatchSignal(dbus.WithMatchSender(busName), dbus.WithMatchInterface(busName),
|
||||
dbus.WithMatchMember("NameOwnerChanged")); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
raw := make(chan *dbus.Signal, 256)
|
||||
conn.Signal(raw)
|
||||
b := &systemBus{conn: conn, out: make(chan NameChange, 256)}
|
||||
go func() {
|
||||
// The signal channel closes when the connection is lost; so does this one, which is how the
|
||||
// watcher learns the bus went away.
|
||||
defer close(b.out)
|
||||
for {
|
||||
select {
|
||||
case s, open := <-raw:
|
||||
if !open {
|
||||
return
|
||||
}
|
||||
if s.Name != busName+".NameOwnerChanged" || len(s.Body) != 3 {
|
||||
continue
|
||||
}
|
||||
name, _ := s.Body[0].(string)
|
||||
old, _ := s.Body[1].(string)
|
||||
nw, _ := s.Body[2].(string)
|
||||
b.out <- NameChange{Name: name, Old: old, New: nw}
|
||||
case <-conn.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (b *systemBus) driver() dbus.BusObject { return b.conn.Object(busName, busPath) }
|
||||
|
||||
// Ping asks the bus driver its id. Not org.freedesktop.DBus.Peer.Ping: dbus-broker's system policy
|
||||
// refuses that to an account that is not root, and logs the refusal as a denial.
|
||||
func (b *systemBus) Ping(ctx context.Context) error {
|
||||
var id string
|
||||
return b.driver().CallWithContext(ctx, busName+".GetId", 0).Store(&id)
|
||||
}
|
||||
|
||||
func (b *systemBus) ID(ctx context.Context) (string, error) {
|
||||
var id string
|
||||
err := b.driver().CallWithContext(ctx, busName+".GetId", 0).Store(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
func (b *systemBus) PID(ctx context.Context, name string) (uint32, error) {
|
||||
var pid uint32
|
||||
err := b.driver().CallWithContext(ctx, busName+".GetConnectionUnixProcessID", 0, name).Store(&pid)
|
||||
return pid, err
|
||||
}
|
||||
|
||||
func (b *systemBus) Names(ctx context.Context) ([]string, error) {
|
||||
var names []string
|
||||
err := b.driver().CallWithContext(ctx, busName+".ListNames", 0).Store(&names)
|
||||
return names, err
|
||||
}
|
||||
|
||||
func (b *systemBus) Activatable(ctx context.Context) ([]string, error) {
|
||||
var names []string
|
||||
err := b.driver().CallWithContext(ctx, busName+".ListActivatableNames", 0).Store(&names)
|
||||
return names, err
|
||||
}
|
||||
|
||||
func (b *systemBus) Changes() <-chan NameChange { return b.out }
|
||||
|
||||
func (b *systemBus) Close() { b.conn.Close() }
|
||||
@@ -0,0 +1,290 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Packages are the bus implementation's packages, as the manifest declares them: dbus-broker (the
|
||||
// bus), its units (the dbus.service alias), and the reference package, which ships the bus's
|
||||
// configuration, the socket that starts it at boot, and libdbus.
|
||||
var Packages = []string{"dbus", "dbus-broker", "dbus-broker-units"}
|
||||
|
||||
// RunningPackages are the packages whose files the running bus loaded when it started: a newer one
|
||||
// installed since takes effect only at the next boot (novox/hq ADR 0215 §2).
|
||||
var RunningPackages = []string{"dbus-broker", "dbus"}
|
||||
|
||||
// SystemUnit is the bus's real unit; dbus.service is its alias.
|
||||
const SystemUnit = "dbus-broker.service"
|
||||
|
||||
// ServiceDirs are where activatable system services are described.
|
||||
var ServiceDirs = []string{"/usr/share/dbus-1/system-services", "/usr/local/share/dbus-1/system-services",
|
||||
"/usr/lib/dbus-1/system-services"}
|
||||
|
||||
// Package is one installed package as the package manager's local database records it.
|
||||
type Package struct {
|
||||
Name string
|
||||
Version string
|
||||
Installed time.Time
|
||||
}
|
||||
|
||||
// ParseDesc reads one package's desc file in the local database.
|
||||
func ParseDesc(desc string) Package {
|
||||
var p Package
|
||||
lines := strings.Split(desc, "\n")
|
||||
for i := 0; i+1 < len(lines); i++ {
|
||||
v := strings.TrimSpace(lines[i+1])
|
||||
switch strings.TrimSpace(lines[i]) {
|
||||
case "%NAME%":
|
||||
p.Name = v
|
||||
case "%VERSION%":
|
||||
p.Version = v
|
||||
case "%INSTALLDATE%":
|
||||
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
|
||||
p.Installed = time.Unix(n, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// InstalledPackage reads a package from the local database, without running the package manager.
|
||||
func (m *Machine) InstalledPackage(name string) (Package, bool) {
|
||||
for _, d := range m.glob("/var/lib/pacman/local/" + name + "-*/desc") {
|
||||
if p := ParseDesc(m.read(d) + "\n"); p.Name == name {
|
||||
return p, true
|
||||
}
|
||||
}
|
||||
return Package{}, false
|
||||
}
|
||||
|
||||
// ParseShow reads `systemctl show` blocks: one map per unit, in the order asked.
|
||||
func ParseShow(out string) []map[string]string {
|
||||
var blocks []map[string]string
|
||||
cur := map[string]string{}
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
if len(cur) > 0 {
|
||||
blocks = append(blocks, cur)
|
||||
cur = map[string]string{}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if k, v, ok := strings.Cut(line, "="); ok {
|
||||
cur[k] = v
|
||||
}
|
||||
}
|
||||
if len(cur) > 0 {
|
||||
blocks = append(blocks, cur)
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// unixStamp reads systemd's "@<seconds>" timestamp.
|
||||
func unixStamp(s string) (time.Time, bool) {
|
||||
n, err := strconv.ParseInt(strings.TrimPrefix(s, "@"), 10, 64)
|
||||
if err != nil || n == 0 {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.Unix(n, 0), true
|
||||
}
|
||||
|
||||
// BusUnit is the system bus's unit as the service manager has it.
|
||||
type BusUnit struct {
|
||||
Unit string `json:"unit"`
|
||||
Active string `json:"active"`
|
||||
PID uint32 `json:"pid,omitempty"`
|
||||
Since time.Time `json:"-"`
|
||||
Started string `json:"started,omitempty"`
|
||||
}
|
||||
|
||||
// SystemBusUnit asks the service manager about the system bus through its alias, so the answer is
|
||||
// the implementation's unit whichever it is.
|
||||
func (m *Machine) SystemBusUnit(ctx context.Context) (BusUnit, error) {
|
||||
out, err := m.Run(ctx, "systemctl", "show", "dbus.service", "-p", "Id,ActiveState,MainPID,ActiveEnterTimestamp",
|
||||
"--timestamp=unix")
|
||||
if err != nil {
|
||||
return BusUnit{}, err
|
||||
}
|
||||
b := ParseShow(out)
|
||||
if len(b) == 0 {
|
||||
return BusUnit{}, fmt.Errorf("systemctl show answered nothing for dbus.service")
|
||||
}
|
||||
u := BusUnit{Unit: b[0]["Id"], Active: b[0]["ActiveState"], PID: parsePID(b[0]["MainPID"])}
|
||||
if t, ok := unixStamp(b[0]["ActiveEnterTimestamp"]); ok {
|
||||
u.Since, u.Started = t, t.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// ServiceFile is one activatable system service's description.
|
||||
type ServiceFile struct {
|
||||
File string
|
||||
Name string
|
||||
Unit string
|
||||
}
|
||||
|
||||
// ParseServiceFile reads the Name and SystemdService of a D-Bus service file.
|
||||
func ParseServiceFile(file, content string) ServiceFile {
|
||||
s := ServiceFile{File: file}
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
k, v, ok := strings.Cut(strings.TrimSpace(line), "=")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch strings.TrimSpace(k) {
|
||||
case "Name":
|
||||
s.Name = strings.TrimSpace(v)
|
||||
case "SystemdService":
|
||||
s.Unit = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Check is one thing the module expects of the machine.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
OK bool `json:"ok"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// RebootDue says, per package the running bus loaded, whether a newer one was installed after the bus
|
||||
// started: the bus is never restarted live, so that package waits for a boot.
|
||||
func RebootDue(started time.Time, pkgs []Package) (bool, string) {
|
||||
var newer []string
|
||||
for _, p := range pkgs {
|
||||
if !p.Installed.IsZero() && p.Installed.After(started) {
|
||||
newer = append(newer, fmt.Sprintf("%s %s installed %s", p.Name, p.Version, p.Installed.UTC().Format(time.RFC3339)))
|
||||
}
|
||||
}
|
||||
if len(newer) == 0 {
|
||||
return false, "the running bus started " + started.UTC().Format(time.RFC3339) + ", after every package it loaded was installed"
|
||||
}
|
||||
return true, "the running bus started " + started.UTC().Format(time.RFC3339) + " and is older than " +
|
||||
strings.Join(newer, ", ") + ": a reboot is due (the bus is never restarted live, novox/hq ADR 0215)"
|
||||
}
|
||||
|
||||
// Check says what this module expects and whether the machine meets it.
|
||||
func (m *Machine) Check(ctx context.Context, w *Watcher) map[string]any {
|
||||
var checks []Check
|
||||
var notes []string
|
||||
add := func(name string, ok bool, format string, args ...any) {
|
||||
checks = append(checks, Check{Name: name, OK: ok, Detail: fmt.Sprintf(format, args...)})
|
||||
}
|
||||
var running []Package
|
||||
for _, name := range Packages {
|
||||
p, ok := m.InstalledPackage(name)
|
||||
add("package "+name, ok, "installed: %v %s", ok, p.Version)
|
||||
for _, r := range RunningPackages {
|
||||
if ok && r == name {
|
||||
running = append(running, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
unit, err := m.SystemBusUnit(ctx)
|
||||
if err != nil {
|
||||
add("system bus", false, "%v", err)
|
||||
} else {
|
||||
add("system bus", unit.Unit == SystemUnit && unit.Active == "active",
|
||||
"dbus.service is %s, %s, pid %d, since %s (want %s active)", orWord(unit.Unit, "unknown"),
|
||||
orWord(unit.Active, "unknown"), unit.PID, orWord(unit.Started, "unknown"), SystemUnit)
|
||||
if !unit.Since.IsZero() {
|
||||
due, detail := RebootDue(unit.Since, running)
|
||||
add("running bus is the installed one", !due, "%s", detail)
|
||||
}
|
||||
}
|
||||
|
||||
var files []ServiceFile
|
||||
for _, dir := range ServiceDirs {
|
||||
for _, f := range m.glob(dir + "/*.service") {
|
||||
if s := ParseServiceFile(f, m.read(f)); s.Unit != "" {
|
||||
files = append(files, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
|
||||
if len(files) > 0 {
|
||||
args := []string{"show", "-p", "Id,LoadState"}
|
||||
for _, f := range files {
|
||||
args = append(args, f.Unit)
|
||||
}
|
||||
out, err := m.Run(ctx, "systemctl", args...)
|
||||
blocks := ParseShow(out)
|
||||
switch {
|
||||
case err != nil:
|
||||
add("activatable services", false, "systemctl show: %v", err)
|
||||
case len(blocks) != len(files):
|
||||
add("activatable services", false, "systemctl show answered %d units for %d service files", len(blocks), len(files))
|
||||
default:
|
||||
var broken, disabled []string
|
||||
for i, f := range files {
|
||||
if blocks[i]["LoadState"] != "not-found" {
|
||||
continue
|
||||
}
|
||||
// systemd's own bus services are reached through a dbus-org.* alias that exists only
|
||||
// while the service is enabled: a disabled one is a choice, not a fault.
|
||||
if strings.HasPrefix(f.Unit, "dbus-org.") {
|
||||
disabled = append(disabled, f.Name+" → "+f.Unit)
|
||||
} else {
|
||||
broken = append(broken, f.Name+" → "+f.Unit+" ("+f.File+")")
|
||||
}
|
||||
}
|
||||
add("activatable services", len(broken) == 0, "%d service files; whose unit does not exist: %s",
|
||||
len(files), orWord(strings.Join(broken, ", "), "none"))
|
||||
if len(disabled) > 0 {
|
||||
notes = append(notes, "activation fails for "+strings.Join(disabled, ", ")+
|
||||
": the service is not enabled, so its dbus-org alias does not exist")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
denials, _, err := m.Denials(ctx, "", m.Now().Add(-time.Hour))
|
||||
if err != nil {
|
||||
add("policy denials in the last hour", false, "reading the journal: %v", err)
|
||||
} else {
|
||||
seen := map[string]bool{}
|
||||
var ex []string
|
||||
for _, d := range denials {
|
||||
k := strings.TrimSpace(d.Type + " " + d.Interface + "." + d.Member + " to " + d.Destination)
|
||||
if !seen[k] && len(ex) < DenialExamples {
|
||||
seen[k] = true
|
||||
ex = append(ex, k)
|
||||
}
|
||||
}
|
||||
add("policy denials in the last hour", len(denials) == 0, "%d: %s", len(denials), orWord(strings.Join(ex, "; "), "none"))
|
||||
}
|
||||
|
||||
if a, err := m.SessionAddress(); err == nil {
|
||||
notes = append(notes, "this account's session bus: "+a)
|
||||
} else {
|
||||
notes = append(notes, err.Error())
|
||||
}
|
||||
|
||||
if w != nil {
|
||||
s := w.Snapshot()
|
||||
add("watcher", s.Connected && !s.Stalled, "connected %v, stalled %v%s, last ping %.1f ms, %d well-known names",
|
||||
s.Connected, s.Stalled, orNote(s.StallReason), s.LastPingMS, s.Services)
|
||||
add("events reach the mesh's bus", s.Pending == 0 && s.Problem == "", "%d event(s) waiting, %d dropped%s",
|
||||
s.Pending, s.Dropped, orNote(s.Problem))
|
||||
}
|
||||
failing := 0
|
||||
for _, c := range checks {
|
||||
if !c.OK {
|
||||
failing++
|
||||
}
|
||||
}
|
||||
return map[string]any{"checks": checks, "failing": failing, "notes": notes}
|
||||
}
|
||||
|
||||
func orNote(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
return " (" + s + ")"
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CountConnections reads the bus driver's Debug.Stats answer (`busctl call … GetStats --json=short`):
|
||||
// dbus-broker lists one accounting entry per peer, the reference daemon says ActiveConnections.
|
||||
func CountConnections(out string) (int, bool) {
|
||||
var reply struct {
|
||||
Data []map[string]struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(out)), &reply) != nil || len(reply.Data) != 1 {
|
||||
return 0, false
|
||||
}
|
||||
if v, ok := reply.Data[0]["org.bus1.DBus.Debug.Stats.PeerAccounting"]; ok {
|
||||
var peers []json.RawMessage
|
||||
if json.Unmarshal(v.Data, &peers) == nil {
|
||||
return len(peers), true
|
||||
}
|
||||
}
|
||||
if v, ok := reply.Data[0]["ActiveConnections"]; ok {
|
||||
var n int
|
||||
if json.Unmarshal(v.Data, &n) == nil {
|
||||
return n, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// CountUniqueNames counts the connections among ListNames' answer (`busctl call … ListNames`).
|
||||
func CountUniqueNames(out string) (int, bool) {
|
||||
var reply struct {
|
||||
Data [][]string `json:"data"`
|
||||
}
|
||||
if json.Unmarshal([]byte(strings.TrimSpace(out)), &reply) != nil || len(reply.Data) != 1 {
|
||||
return 0, false
|
||||
}
|
||||
n := 0
|
||||
for _, name := range reply.Data[0] {
|
||||
if strings.HasPrefix(name, ":") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// Health is the system bus's health now: a ping through the watcher's connection, how many
|
||||
// connections the bus has, and how long it has run.
|
||||
func (m *Machine) Health(ctx context.Context, w *Watcher) map[string]any {
|
||||
h := map[string]any{"bus": "system"}
|
||||
if w != nil {
|
||||
took, err := w.PingNow()
|
||||
if err != nil {
|
||||
h["ping"] = "no answer: " + err.Error()
|
||||
} else {
|
||||
h["ping_ms"] = float64(took.Microseconds()) / 1000
|
||||
}
|
||||
h["watcher"] = w.Snapshot()
|
||||
}
|
||||
// Debug.Stats is root's on the system bus; asked as the account it is refused and logged as a
|
||||
// denial, which the watcher would then publish. So it is asked through sudo -n or not at all.
|
||||
call := []string{"busctl", "--system", "--json=short", "--no-pager", "call", busName, busPath}
|
||||
if out, err := m.privileged(ctx, call[0], append(call[1:], busName+".Debug.Stats", "GetStats")...); err == nil {
|
||||
if n, ok := CountConnections(out); ok {
|
||||
h["connections"], h["connections_from"] = n, "the bus's Debug.Stats"
|
||||
}
|
||||
}
|
||||
if _, ok := h["connections"]; !ok {
|
||||
if out, err := m.Run(ctx, call[0], append(call[1:], busName, "ListNames")...); err == nil {
|
||||
if n, ok := CountUniqueNames(out); ok {
|
||||
h["connections"], h["connections_from"] = n, "the unique names on the bus (Debug.Stats needs sudo -n)"
|
||||
}
|
||||
}
|
||||
}
|
||||
if u, err := m.SystemBusUnit(ctx); err != nil {
|
||||
h["unit"] = err.Error()
|
||||
} else {
|
||||
h["unit"], h["active"], h["pid"] = u.Unit, u.Active, u.PID
|
||||
if !u.Since.IsZero() {
|
||||
h["started"] = u.Started
|
||||
h["uptime"] = m.Now().Sub(u.Since).Round(time.Second).String()
|
||||
}
|
||||
}
|
||||
return h
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/godbus/dbus/v5/introspect"
|
||||
)
|
||||
|
||||
// A bus name and an object path as the specification allows them; anything else is refused before
|
||||
// it reaches busctl, so no argument is ever taken for an option.
|
||||
var (
|
||||
busNameRE = regexp.MustCompile(`^(:[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+|[A-Za-z_-][A-Za-z0-9_-]*(\.[A-Za-z_-][A-Za-z0-9_-]*)+)$`)
|
||||
objectPathRE = regexp.MustCompile(`^/([A-Za-z0-9_]+(/[A-Za-z0-9_]+)*)?$`)
|
||||
)
|
||||
|
||||
// Member is one method or signal, with its arguments as "name type".
|
||||
type Member struct {
|
||||
Name string `json:"name"`
|
||||
In []string `json:"in,omitempty"`
|
||||
Out []string `json:"out,omitempty"`
|
||||
Args []string `json:"args,omitempty"`
|
||||
}
|
||||
|
||||
// Property is one property's name, type and access, never its value: a value can be anything a
|
||||
// service holds, and reading it is a call of its own.
|
||||
type Property struct {
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Access string `json:"access"`
|
||||
}
|
||||
|
||||
// Interface is one interface of an object.
|
||||
type Interface struct {
|
||||
Name string `json:"name"`
|
||||
Methods []Member `json:"methods,omitempty"`
|
||||
Properties []Property `json:"properties,omitempty"`
|
||||
Signals []Member `json:"signals,omitempty"`
|
||||
}
|
||||
|
||||
// Object is dbus_introspect's answer.
|
||||
type Object struct {
|
||||
Bus string `json:"bus"`
|
||||
Service string `json:"service"`
|
||||
Path string `json:"path"`
|
||||
Interfaces []Interface `json:"interfaces"`
|
||||
Children []string `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
// ParseIntrospection reads `busctl call … Introspect --json=short` ({"type":"s","data":["<xml>"]}).
|
||||
func ParseIntrospection(out string) (introspect.Node, error) {
|
||||
var reply struct {
|
||||
Data []string `json:"data"`
|
||||
}
|
||||
var node introspect.Node
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &reply); err != nil || len(reply.Data) != 1 {
|
||||
return node, fmt.Errorf("the introspection answer is not a single string")
|
||||
}
|
||||
if err := xml.Unmarshal([]byte(reply.Data[0]), &node); err != nil {
|
||||
return node, fmt.Errorf("the introspection document does not parse: %w", err)
|
||||
}
|
||||
return node, nil
|
||||
}
|
||||
|
||||
// Shape turns an introspection document into the tool's answer.
|
||||
func Shape(bus, service, path string, node introspect.Node) Object {
|
||||
o := Object{Bus: bus, Service: service, Path: path, Interfaces: []Interface{}}
|
||||
for _, i := range node.Interfaces {
|
||||
iface := Interface{Name: i.Name}
|
||||
for _, m := range i.Methods {
|
||||
mem := Member{Name: m.Name}
|
||||
for _, a := range m.Args {
|
||||
s := strings.TrimSpace(a.Name + " " + a.Type)
|
||||
if a.Direction == "out" {
|
||||
mem.Out = append(mem.Out, s)
|
||||
} else {
|
||||
mem.In = append(mem.In, s)
|
||||
}
|
||||
}
|
||||
iface.Methods = append(iface.Methods, mem)
|
||||
}
|
||||
for _, p := range i.Properties {
|
||||
iface.Properties = append(iface.Properties, Property{Name: p.Name, Type: p.Type, Access: p.Access})
|
||||
}
|
||||
for _, s := range i.Signals {
|
||||
mem := Member{Name: s.Name}
|
||||
for _, a := range s.Args {
|
||||
mem.Args = append(mem.Args, strings.TrimSpace(a.Name+" "+a.Type))
|
||||
}
|
||||
iface.Signals = append(iface.Signals, mem)
|
||||
}
|
||||
o.Interfaces = append(o.Interfaces, iface)
|
||||
}
|
||||
for _, c := range node.Children {
|
||||
if len(o.Children) >= AnswerCap {
|
||||
break
|
||||
}
|
||||
o.Children = append(o.Children, c.Name)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// Introspect asks one object what it offers, as this account, without starting a service that is not
|
||||
// running (--auto-start=no): looking must not change what runs.
|
||||
func (m *Machine) Introspect(ctx context.Context, bus, service, path string) (Object, error) {
|
||||
if !busNameRE.MatchString(service) {
|
||||
return Object{}, fmt.Errorf("%q is not a bus name", service)
|
||||
}
|
||||
if path == "" {
|
||||
path = "/"
|
||||
}
|
||||
if !objectPathRE.MatchString(path) {
|
||||
return Object{}, fmt.Errorf("%q is not an object path", path)
|
||||
}
|
||||
args, err := m.busArgs(bus)
|
||||
if err != nil {
|
||||
return Object{}, err
|
||||
}
|
||||
out, err := m.Run(ctx, "busctl", append(args, "--json=short", "--no-pager", "--auto-start=no", "call",
|
||||
service, path, "org.freedesktop.DBus.Introspectable", "Introspect")...)
|
||||
if err != nil {
|
||||
return Object{}, err
|
||||
}
|
||||
node, err := ParseIntrospection(out)
|
||||
if err != nil {
|
||||
return Object{}, err
|
||||
}
|
||||
return Shape(orWord(bus, "system"), service, path, node), nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// BusUnits are the system bus's units as the journal knows them: dbus-broker's own name, and the
|
||||
// alias every implementation answers to.
|
||||
var BusUnits = []string{"dbus-broker.service", "dbus.service"}
|
||||
|
||||
// JournalLines is the most journal entries one read takes.
|
||||
const JournalLines = 2000
|
||||
|
||||
// Denial is one policy denial as the bus logged it: the header of the message it refused, never its
|
||||
// body, which the bus does not log either.
|
||||
type Denial struct {
|
||||
At string `json:"at"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Sender string `json:"sender,omitempty"`
|
||||
Destination string `json:"destination,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Interface string `json:"interface,omitempty"`
|
||||
Member string `json:"member,omitempty"`
|
||||
Policy string `json:"policy,omitempty"`
|
||||
}
|
||||
|
||||
// key is what makes two denials the same example: who was refused what, ignoring the sender's unique
|
||||
// name, which differs at every connection.
|
||||
func (d Denial) key() string {
|
||||
return d.Action + "|" + d.Type + "|" + d.Destination + "|" + d.Interface + "|" + d.Member
|
||||
}
|
||||
|
||||
// journalEntry is the part of a journal entry the module reads. MESSAGE is read only to recognise a
|
||||
// denial; it is never answered or published.
|
||||
type journalEntry struct {
|
||||
Cursor string `json:"__CURSOR"`
|
||||
Realtime string `json:"__REALTIME_TIMESTAMP"`
|
||||
Message any `json:"MESSAGE"`
|
||||
Action string `json:"DBUS_BROKER_TRANSMIT_ACTION"`
|
||||
Type string `json:"DBUS_BROKER_MESSAGE_TYPE"`
|
||||
Sender string `json:"DBUS_BROKER_SENDER_UNIQUE_NAME"`
|
||||
Destination string `json:"DBUS_BROKER_MESSAGE_DESTINATION"`
|
||||
Path string `json:"DBUS_BROKER_MESSAGE_PATH"`
|
||||
Interface string `json:"DBUS_BROKER_MESSAGE_INTERFACE"`
|
||||
Member string `json:"DBUS_BROKER_MESSAGE_MEMBER"`
|
||||
Policy string `json:"DBUS_BROKER_POLICY_TYPE"`
|
||||
}
|
||||
|
||||
// IsDenial is whether a bus's log line is a policy denial: dbus-broker's "A security policy denied",
|
||||
// or the reference daemon's "Rejected send message".
|
||||
func IsDenial(message string) bool {
|
||||
return strings.Contains(message, "security policy denied") || strings.Contains(message, "Rejected send message") ||
|
||||
strings.Contains(message, "Rejected receive message")
|
||||
}
|
||||
|
||||
// ParseDenials reads journalctl's JSON lines and answers the denials among them and the last cursor.
|
||||
func ParseDenials(out string) ([]Denial, string) {
|
||||
var got []Denial
|
||||
cursor := ""
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || line[0] != '{' {
|
||||
continue
|
||||
}
|
||||
var e journalEntry
|
||||
if json.Unmarshal([]byte(line), &e) != nil {
|
||||
continue
|
||||
}
|
||||
if e.Cursor != "" {
|
||||
cursor = e.Cursor
|
||||
}
|
||||
msg, _ := e.Message.(string) // a binary MESSAGE comes as an array of bytes and is no denial
|
||||
if !IsDenial(msg) {
|
||||
continue
|
||||
}
|
||||
at := ""
|
||||
if us, err := strconv.ParseInt(e.Realtime, 10, 64); err == nil {
|
||||
at = time.UnixMicro(us).UTC().Format(time.RFC3339)
|
||||
}
|
||||
got = append(got, Denial{At: at, Action: e.Action, Type: e.Type, Sender: e.Sender,
|
||||
Destination: e.Destination, Path: e.Path, Interface: e.Interface, Member: e.Member, Policy: e.Policy})
|
||||
}
|
||||
return got, cursor
|
||||
}
|
||||
|
||||
func journalArgs() []string {
|
||||
args := []string{"--no-pager", "-o", "json", "-n", strconv.Itoa(JournalLines)}
|
||||
for _, u := range BusUnits {
|
||||
args = append(args, "-u", u)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// Denials is the watcher's Journal on this machine: journalctl as the operator's account, which
|
||||
// reads the system journal through its group.
|
||||
func (m *Machine) Denials(ctx context.Context, after string, since time.Time) ([]Denial, string, error) {
|
||||
args := journalArgs()
|
||||
if after != "" {
|
||||
args = append(args, "--after-cursor", after)
|
||||
} else {
|
||||
args = append(args, "--since", "@"+strconv.FormatInt(since.Unix(), 10))
|
||||
}
|
||||
out, err := m.Run(ctx, "journalctl", args...)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
d, cursor := ParseDenials(out)
|
||||
return d, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Run on a real machine with MESH_LIVE=1: every tool reads this machine's buses, and the watcher's
|
||||
// connection answers. Nothing is changed.
|
||||
func TestLiveTools(t *testing.T) {
|
||||
if os.Getenv("MESH_LIVE") == "" {
|
||||
t.Skip("set MESH_LIVE=1 on a machine with a system bus")
|
||||
}
|
||||
ctx := context.Background()
|
||||
m := Here()
|
||||
b, err := DialSystemBus()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer b.Close()
|
||||
if err := b.Ping(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, _ := b.ID(ctx)
|
||||
pid, _ := b.PID(ctx, busName)
|
||||
t.Logf("bus %s, driver pid %d in %s", id, pid, m.UnitOf(pid))
|
||||
show := func(name string, v any, err error) {
|
||||
raw, _ := json.Marshal(v)
|
||||
if len(raw) > 1500 {
|
||||
raw = append(raw[:1500], "…"...)
|
||||
}
|
||||
t.Logf("%s: %v\n%s", name, err, raw)
|
||||
}
|
||||
n, err := m.Names(ctx, "system")
|
||||
show("names system", n, err)
|
||||
n, err = m.Names(ctx, "session")
|
||||
show("names session", n, err)
|
||||
o, err := m.Introspect(ctx, "system", "org.freedesktop.login1", "/org/freedesktop/login1")
|
||||
show("introspect", o, err)
|
||||
w, err := m.Monitor(ctx, "system", 2, "", nil)
|
||||
show("monitor", w, err)
|
||||
show("health", m.Health(ctx, nil), nil)
|
||||
show("check", m.Check(ctx, nil), nil)
|
||||
}
|
||||
|
||||
// Run with MESH_LIVE=1: the watcher connects, pings and baselines the names, and says nothing.
|
||||
func TestLiveWatcher(t *testing.T) {
|
||||
if os.Getenv("MESH_LIVE") == "" {
|
||||
t.Skip("set MESH_LIVE=1 on a machine with a system bus")
|
||||
}
|
||||
m := Here()
|
||||
var said []string
|
||||
w := NewWatcher(m, func(e string, b any) error { said = append(said, e); return nil }, DialSystemBus, m.Denials)
|
||||
w.state = filepath.Join(t.TempDir(), "bus")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), PingEvery+2*time.Second)
|
||||
defer cancel()
|
||||
w.Run(ctx)
|
||||
s := w.Snapshot()
|
||||
t.Logf("%+v said %v", s, said)
|
||||
if s.BusID == "" || s.LastPingAt == "" || s.Stalled || s.Services == 0 {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CommandTimeout bounds every command a tool runs: a bus that hangs must cost a tool call twenty
|
||||
// seconds, never the runtime's thirty.
|
||||
const CommandTimeout = 20 * time.Second
|
||||
|
||||
// ReadCap is the most of one command's output the module reads. An introspection document of the
|
||||
// service manager is about 100 KiB; nothing the module asks is near a mebibyte.
|
||||
const ReadCap = 1024 * 1024
|
||||
|
||||
// AnswerCap is the most entries a tool answers in one list (names, messages, denials).
|
||||
const AnswerCap = 500
|
||||
|
||||
// Runner runs one command and answers its standard output. Injected, so every tool is tested against
|
||||
// recorded answers rather than this machine's bus.
|
||||
type Runner func(ctx context.Context, name string, args ...string) (string, error)
|
||||
|
||||
// Streamer runs one command for at most the context's time and hands each line of its output to
|
||||
// line, which says whether it wants more. The end of the time is the normal end, not an error.
|
||||
// Injected, so dbus_monitor is tested without a bus.
|
||||
type Streamer func(ctx context.Context, line func(string) bool, name string, args ...string) error
|
||||
|
||||
// ExecRunner runs a command, bounded by CommandTimeout. A failure carries what it said on stderr.
|
||||
func ExecRunner(ctx context.Context, name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, CommandTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
cmd.Env = append(os.Environ(), "LC_ALL=C", "SYSTEMD_PAGER=", "SYSTEMD_COLORS=0")
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||
err := cmd.Run()
|
||||
out := capped(stdout.String(), ReadCap)
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return out, fmt.Errorf("%s did not answer within %s", name, CommandTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
said := strings.TrimSpace(stderr.String())
|
||||
if said == "" {
|
||||
said = strings.TrimSpace(stdout.String())
|
||||
}
|
||||
return out, fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, capped(said, 2048))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ExecStreamer runs a command until the context ends, line by line. A line longer than ReadCap is
|
||||
// skipped, never held: a monitored message's line carries its body, which the module never keeps.
|
||||
func ExecStreamer(ctx context.Context, line func(string) bool, name string, args ...string) error {
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
cmd.Env = append(os.Environ(), "LC_ALL=C", "SYSTEMD_PAGER=", "SYSTEMD_COLORS=0")
|
||||
// A terminate, which sudo passes on to what it runs; a kill would leave a root monitor behind.
|
||||
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
|
||||
cmd.WaitDelay = 2 * time.Second
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
r := bufio.NewReaderSize(out, 64*1024)
|
||||
var cur []byte
|
||||
tooLong := false
|
||||
for {
|
||||
chunk, isPrefix, err := r.ReadLine()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if !tooLong {
|
||||
cur = append(cur, chunk...)
|
||||
if len(cur) > ReadCap {
|
||||
cur, tooLong = cur[:0], true
|
||||
}
|
||||
}
|
||||
if isPrefix {
|
||||
continue
|
||||
}
|
||||
if !tooLong && !line(string(cur)) {
|
||||
break
|
||||
}
|
||||
cur, tooLong = cur[:0], false
|
||||
}
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
werr := cmd.Wait()
|
||||
if ctx.Err() != nil {
|
||||
return nil // the time ran out: the normal end of a bounded watch
|
||||
}
|
||||
if werr != nil && stderr.Len() > 0 {
|
||||
return fmt.Errorf("%s: %w: %s", name, werr, capped(strings.TrimSpace(stderr.String()), 2048))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func capped(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "\n… (cut)"
|
||||
}
|
||||
|
||||
// Machine is what the module reads and acts on: a filesystem root (the real one, or a test's tree),
|
||||
// a way to run commands, a way to stream one, and the environment the runtime gave it.
|
||||
type Machine struct {
|
||||
Root string
|
||||
Run Runner
|
||||
Stream Streamer
|
||||
Env func(string) string
|
||||
UID int
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Here is the machine this process runs on.
|
||||
func Here() *Machine {
|
||||
return &Machine{Root: "/", Run: ExecRunner, Stream: ExecStreamer, Env: os.Getenv, UID: os.Getuid(), Now: time.Now}
|
||||
}
|
||||
|
||||
func (m *Machine) path(p string) string { return filepath.Join(m.Root, p) }
|
||||
|
||||
func (m *Machine) read(p string) string {
|
||||
b, err := os.ReadFile(m.path(p))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func (m *Machine) exists(p string) bool {
|
||||
_, err := os.Stat(m.path(p))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (m *Machine) glob(pattern string) []string {
|
||||
got, _ := filepath.Glob(m.path(pattern))
|
||||
out := make([]string, 0, len(got))
|
||||
for _, g := range got {
|
||||
rel, err := filepath.Rel(m.Root, g)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, "/"+rel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// privileged runs a command as root without asking for a password (sudo -n), as the other modules'
|
||||
// tools do: the runtime runs as the operator's account, and watching the system bus is root's.
|
||||
func (m *Machine) privileged(ctx context.Context, name string, args ...string) (string, error) {
|
||||
return m.Run(ctx, "sudo", append([]string{"-n", name}, args...)...)
|
||||
}
|
||||
|
||||
// Buses are the two buses a tool can be pointed at.
|
||||
var Buses = []string{"system", "session"}
|
||||
|
||||
// ErrNoSession is the answer on a machine where this account has no session bus: the servers.
|
||||
var ErrNoSession = errors.New("no session bus for this account on this machine")
|
||||
|
||||
// SessionAddress is the account's session bus: the runtime's DBUS_SESSION_BUS_ADDRESS, else the
|
||||
// user manager's socket under XDG_RUNTIME_DIR or /run/user/<uid>. Only a socket that exists counts.
|
||||
func (m *Machine) SessionAddress() (string, error) {
|
||||
if a := m.Env("DBUS_SESSION_BUS_ADDRESS"); strings.HasPrefix(a, "unix:path=") {
|
||||
p := strings.TrimPrefix(a, "unix:path=")
|
||||
if i := strings.IndexByte(p, ','); i >= 0 {
|
||||
p = p[:i]
|
||||
}
|
||||
if m.exists(p) {
|
||||
return a, nil
|
||||
}
|
||||
} else if a != "" {
|
||||
return a, nil // an abstract or other address: taken as given
|
||||
}
|
||||
dir := m.Env("XDG_RUNTIME_DIR")
|
||||
if dir == "" {
|
||||
dir = "/run/user/" + strconv.Itoa(m.UID)
|
||||
}
|
||||
if p := dir + "/bus"; m.exists(p) {
|
||||
return "unix:path=" + p, nil
|
||||
}
|
||||
return "", fmt.Errorf("%w (no socket at %s/bus)", ErrNoSession, dir)
|
||||
}
|
||||
|
||||
// busArgs are busctl's words for one bus.
|
||||
func (m *Machine) busArgs(bus string) ([]string, error) {
|
||||
switch bus {
|
||||
case "", "system":
|
||||
return []string{"--system"}, nil
|
||||
case "session":
|
||||
a, err := m.SessionAddress()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []string{"--address=" + a}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("bus is system or session, not %q", bus)
|
||||
}
|
||||
|
||||
// UnitOf is the systemd unit a process runs in, from its cgroup: readable for any process.
|
||||
func (m *Machine) UnitOf(pid uint32) string {
|
||||
if pid == 0 {
|
||||
return ""
|
||||
}
|
||||
return UnitFromCgroup(m.read(fmt.Sprintf("/proc/%d/cgroup", pid)))
|
||||
}
|
||||
|
||||
// ProcessName is a process's command name.
|
||||
func (m *Machine) ProcessName(pid uint32) string {
|
||||
if pid == 0 {
|
||||
return ""
|
||||
}
|
||||
return m.read(fmt.Sprintf("/proc/%d/comm", pid))
|
||||
}
|
||||
|
||||
// UnitFromCgroup is the innermost service, socket or scope in a cgroup v2 path.
|
||||
func UnitFromCgroup(cgroup string) string {
|
||||
for _, line := range strings.Split(cgroup, "\n") {
|
||||
if !strings.HasPrefix(line, "0::") {
|
||||
continue
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(line, "0::"), "/")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
p := parts[i]
|
||||
if strings.HasSuffix(p, ".service") || strings.HasSuffix(p, ".scope") {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// BootID is this boot's id: a bus that changed across a boot did not restart, the machine did.
|
||||
func (m *Machine) BootID() string { return m.read("/proc/sys/kernel/random/boot_id") }
|
||||
@@ -0,0 +1,26 @@
|
||||
// The dbus module's Go bundle (novox/hq ADR 0215): the holder of node-message-bus. One process the
|
||||
// node's runtime launches as the operator's account, serving the module's tools over MCP on stdio and
|
||||
// running its watcher beside them, which publishes what matters about the system bus, never its
|
||||
// traffic.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
m := Here()
|
||||
w := NewWatcher(m, func(eventType string, body any) error { return stdio.Emit(eventType, body) },
|
||||
DialSystemBus, m.Denials)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go w.Run(ctx)
|
||||
if err := stdio.Serve("", Tools(m, w)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package main
|
||||
|
||||
// The dbus module's shape (novox/hq ADR 0215): it holds node-message-bus, owns the bus's packages,
|
||||
// declares the bus running and never restarts or reloads it, and publishes only its curated events.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type manifestShape struct {
|
||||
Module string `json:"module"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Claims []map[string]any `json:"claims"`
|
||||
Emits []string `json:"emits"`
|
||||
Consumes []string `json:"consumes"`
|
||||
Tools []string `json:"tools"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
func manifest(t *testing.T) (manifestShape, string) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m manifestShape
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m, string(raw)
|
||||
}
|
||||
|
||||
func TestItHoldsTheMessageBusSeatWithOnlyWhatItNeeds(t *testing.T) {
|
||||
m, _ := manifest(t)
|
||||
if m.Module != "dbus" || len(m.Claims) != 1 || m.Claims[0]["name"] != "node-message-bus" || m.Claims[0]["scope"] != "node" {
|
||||
t.Fatalf("claims: %+v", m.Claims)
|
||||
}
|
||||
if _, serves := m.Claims[0]["serves"]; serves {
|
||||
t.Error("the seat receives nothing yet (ADR 0215 §4) and serves no verbs")
|
||||
}
|
||||
if !reflect.DeepEqual(m.Capabilities, []string{"package-manager", "service-manager"}) {
|
||||
t.Fatalf("capabilities: %v", m.Capabilities)
|
||||
}
|
||||
}
|
||||
|
||||
func TestItOwnsTheBusImplementationsPackages(t *testing.T) {
|
||||
m, _ := manifest(t)
|
||||
var pkgs []string
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
pkgs = append(pkgs, r["package"].(string))
|
||||
if r["absent"] == true {
|
||||
t.Errorf("%v is declared absent", r["package"])
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Strings(pkgs)
|
||||
if !reflect.DeepEqual(pkgs, Packages) {
|
||||
t.Fatalf("packages %v, the check reads %v", pkgs, Packages)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTheBusIsNeverRestartedOrReloaded is ADR 0215 §2: the bus is declared running, with no trigger
|
||||
// that would restart or reload it, and no boot state: dbus.service is an alias and dbus-broker.service
|
||||
// is started at boot through dbus.socket, so enabling would write an alias link the machines do not
|
||||
// have today.
|
||||
func TestTheBusIsNeverRestartedOrReloaded(t *testing.T) {
|
||||
m, raw := manifest(t)
|
||||
if strings.Contains(raw, "restart-on") || strings.Contains(raw, "reload-on") {
|
||||
t.Fatal("the manifest carries a restart or reload trigger")
|
||||
}
|
||||
var services []map[string]any
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "service" {
|
||||
services = append(services, r)
|
||||
}
|
||||
}
|
||||
if len(services) != 1 {
|
||||
t.Fatalf("services: %v", services)
|
||||
}
|
||||
s := services[0]
|
||||
if s["unit"] != SystemUnit || s["state"] != "running" {
|
||||
t.Fatalf("%v", s)
|
||||
}
|
||||
if _, ok := s["boot"]; ok {
|
||||
t.Fatal("a boot state on the bus would have the host enable it")
|
||||
}
|
||||
for k := range s {
|
||||
if k != "id" && k != "type" && k != "unit" && k != "state" {
|
||||
t.Errorf("the bus's service carries %q", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestItEmitsTheCuratedEventsAndConsumesNothing(t *testing.T) {
|
||||
m, _ := manifest(t)
|
||||
if !reflect.DeepEqual(m.Emits, Emits) {
|
||||
t.Fatalf("emits %v, the watcher publishes %v", m.Emits, Emits)
|
||||
}
|
||||
if len(m.Consumes) != 0 {
|
||||
t.Fatalf("consumes %v", m.Consumes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolsAreTheManifests(t *testing.T) {
|
||||
m, _ := manifest(t)
|
||||
served := map[string]bool{}
|
||||
for _, tool := range Tools(testMachine(t, nil), nil) {
|
||||
if served[tool.Name] {
|
||||
t.Errorf("%s is served twice", tool.Name)
|
||||
}
|
||||
served[tool.Name] = true
|
||||
if !strings.HasPrefix(tool.Name, "dbus_") {
|
||||
t.Errorf("%s is not named dbus_<verb>", tool.Name)
|
||||
}
|
||||
}
|
||||
for _, want := range m.Tools {
|
||||
if !served[want] {
|
||||
t.Errorf("the manifest lists %s and the bundle does not serve it", want)
|
||||
}
|
||||
delete(served, want)
|
||||
}
|
||||
for extra := range served {
|
||||
t.Errorf("the bundle serves %s, which the manifest does not list", extra)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheBundleIsTheBuildersShape(t *testing.T) {
|
||||
m, _ := manifest(t)
|
||||
if len(m.Build.Artifacts) != 1 {
|
||||
t.Fatalf("%v", m.Build.Artifacts)
|
||||
}
|
||||
a := m.Build.Artifacts[0]
|
||||
for k, v := range map[string]string{"kind": "bundle", "language": "go", "system": "arch", "from": "cmd/dbus-tools", "binary": "dbus-tools"} {
|
||||
if a[k] != v {
|
||||
t.Errorf("%s is %v, want %s", k, a[k], v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNothingInstallationSpecific holds the manifest to the catalogue's rule: no node names, domains
|
||||
// or home paths.
|
||||
func TestNothingInstallationSpecific(t *testing.T) {
|
||||
_, raw := manifest(t)
|
||||
for _, re := range []*regexp.Regexp{regexp.MustCompile(`/home/`), regexp.MustCompile(`\.(be|internal|com)\b`)} {
|
||||
if loc := re.FindString(raw); loc != "" {
|
||||
t.Errorf("the manifest carries %q", loc)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MaxMonitorSeconds bounds a watch of the bus: long enough to catch an exchange, short enough that
|
||||
// nobody leaves a monitor running.
|
||||
const MaxMonitorSeconds = 15
|
||||
|
||||
// MonitorLimit is the most messages busctl reads in one watch before it stops by itself.
|
||||
const MonitorLimit = 20000
|
||||
|
||||
// Header is what dbus_monitor answers of one message: who sent what to whom. The body is never read
|
||||
// into it: the struct has no field for it, so a payload is dropped as each line is decoded.
|
||||
type Header struct {
|
||||
Time string `json:"time,omitempty"`
|
||||
Type string `json:"type"`
|
||||
Sender string `json:"sender,omitempty"`
|
||||
Destination string `json:"destination,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Interface string `json:"interface,omitempty"`
|
||||
Member string `json:"member,omitempty"`
|
||||
ErrorName string `json:"error_name,omitempty"`
|
||||
}
|
||||
|
||||
type monitorLine struct {
|
||||
Type string `json:"type"`
|
||||
Sender string `json:"sender"`
|
||||
Destination string `json:"destination"`
|
||||
Path string `json:"path"`
|
||||
Interface string `json:"interface"`
|
||||
Member string `json:"member"`
|
||||
ErrorName string `json:"error_name"`
|
||||
Realtime int64 `json:"timestamp-realtime"`
|
||||
}
|
||||
|
||||
// ParseHeader reads one line of `busctl monitor --json=short` into its header alone.
|
||||
func ParseHeader(line string) (Header, bool) {
|
||||
var l monitorLine
|
||||
if json.Unmarshal([]byte(line), &l) != nil || l.Type == "" {
|
||||
return Header{}, false
|
||||
}
|
||||
h := Header{Type: l.Type, Sender: l.Sender, Destination: l.Destination, Path: l.Path,
|
||||
Interface: l.Interface, Member: l.Member, ErrorName: l.ErrorName}
|
||||
if l.Realtime > 0 {
|
||||
h.Time = time.UnixMicro(l.Realtime).UTC().Format("15:04:05.000000")
|
||||
}
|
||||
return h, true
|
||||
}
|
||||
|
||||
// Watch is dbus_monitor's answer.
|
||||
type Watch struct {
|
||||
Bus string `json:"bus"`
|
||||
Seconds int `json:"seconds"`
|
||||
Match string `json:"match,omitempty"`
|
||||
Names []string `json:"names,omitempty"`
|
||||
Total int `json:"total"`
|
||||
Messages []Header `json:"messages"`
|
||||
Cut bool `json:"cut,omitempty"`
|
||||
Note string `json:"note"`
|
||||
}
|
||||
|
||||
// Monitor watches one bus for a few seconds and answers the headers of what passed. The system bus is
|
||||
// watched as root (sudo -n): only root may become a monitor there. The session bus is the account's
|
||||
// own. The bodies, which carry secrets, notification text and the clipboard, are never kept.
|
||||
func (m *Machine) Monitor(ctx context.Context, bus string, seconds int, match string, names []string) (Watch, error) {
|
||||
if seconds < 1 || seconds > MaxMonitorSeconds {
|
||||
return Watch{}, fmt.Errorf("seconds is 1 to %d", MaxMonitorSeconds)
|
||||
}
|
||||
if len(match) > 512 || strings.ContainsAny(match, "\n\x00") {
|
||||
return Watch{}, fmt.Errorf("the match rule is not one line of at most 512 characters")
|
||||
}
|
||||
for _, n := range names {
|
||||
if !busNameRE.MatchString(n) {
|
||||
return Watch{}, fmt.Errorf("%q is not a bus name", n)
|
||||
}
|
||||
}
|
||||
args, err := m.busArgs(bus)
|
||||
if err != nil {
|
||||
return Watch{}, err
|
||||
}
|
||||
cmd := append([]string{"timeout", strconv.Itoa(seconds) + "s", "busctl"}, args...)
|
||||
cmd = append(cmd, "--json=short", "--no-pager", "--limit-messages="+strconv.Itoa(MonitorLimit), "monitor")
|
||||
if match != "" {
|
||||
cmd = append(cmd, "--match="+match)
|
||||
}
|
||||
cmd = append(cmd, names...)
|
||||
if orWord(bus, "system") == "system" {
|
||||
cmd = append([]string{"sudo", "-n"}, cmd...)
|
||||
}
|
||||
w := Watch{Bus: orWord(bus, "system"), Seconds: seconds, Match: match, Names: names, Messages: []Header{},
|
||||
Note: "headers only; message bodies are never read into the answer"}
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Duration(seconds)*time.Second+5*time.Second)
|
||||
defer cancel()
|
||||
err = m.Stream(ctx, func(line string) bool {
|
||||
h, ok := ParseHeader(line)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
w.Total++
|
||||
if len(w.Messages) < AnswerCap {
|
||||
w.Messages = append(w.Messages, h)
|
||||
} else {
|
||||
w.Cut = true
|
||||
}
|
||||
return true
|
||||
}, cmd[0], cmd[1:]...)
|
||||
return w, err
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// busctlName is one line of `busctl list --json`.
|
||||
type busctlName struct {
|
||||
Name string `json:"name"`
|
||||
PID *uint32 `json:"pid"`
|
||||
Process *string `json:"process"`
|
||||
User *string `json:"user"`
|
||||
Connection string `json:"connection"`
|
||||
Unit *string `json:"unit"`
|
||||
}
|
||||
|
||||
// Name is one well-known name on a bus, with what holds it.
|
||||
type Name struct {
|
||||
Name string `json:"name"`
|
||||
PID uint32 `json:"pid,omitempty"`
|
||||
Process string `json:"process,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
Unit string `json:"unit,omitempty"`
|
||||
Connection string `json:"connection,omitempty"`
|
||||
}
|
||||
|
||||
// Names is dbus_names's answer.
|
||||
type Names struct {
|
||||
Bus string `json:"bus"`
|
||||
Running []Name `json:"running"`
|
||||
ActivatableNotRunning []string `json:"activatable_not_running"`
|
||||
Connections int `json:"connections"`
|
||||
Cut bool `json:"cut,omitempty"`
|
||||
}
|
||||
|
||||
// ParseNames reads `busctl list --json=short`: the well-known names running, the activatable names
|
||||
// that are not, and how many connections (unique names) the bus has.
|
||||
func ParseNames(bus, out string) (Names, error) {
|
||||
var raw []busctlName
|
||||
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &raw); err != nil {
|
||||
return Names{}, fmt.Errorf("busctl list answered what is not its JSON: %w", err)
|
||||
}
|
||||
n := Names{Bus: bus, Running: []Name{}, ActivatableNotRunning: []string{}}
|
||||
for _, r := range raw {
|
||||
switch {
|
||||
case r.Name == busName: // the bus itself, which busctl attributes to the service manager
|
||||
case strings.HasPrefix(r.Name, ":"):
|
||||
n.Connections++
|
||||
case r.Connection == "(activatable)" || r.PID == nil:
|
||||
n.ActivatableNotRunning = append(n.ActivatableNotRunning, r.Name)
|
||||
default:
|
||||
n.Running = append(n.Running, Name{Name: r.Name, PID: deref(r.PID), Process: derefS(r.Process),
|
||||
User: derefS(r.User), Unit: derefS(r.Unit), Connection: r.Connection})
|
||||
}
|
||||
}
|
||||
sort.Slice(n.Running, func(i, j int) bool { return n.Running[i].Name < n.Running[j].Name })
|
||||
sort.Strings(n.ActivatableNotRunning)
|
||||
if len(n.Running) > AnswerCap {
|
||||
n.Running, n.Cut = n.Running[:AnswerCap], true
|
||||
}
|
||||
if len(n.ActivatableNotRunning) > AnswerCap {
|
||||
n.ActivatableNotRunning, n.Cut = n.ActivatableNotRunning[:AnswerCap], true
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Names lists one bus's names as this account sees them.
|
||||
func (m *Machine) Names(ctx context.Context, bus string) (Names, error) {
|
||||
args, err := m.busArgs(bus)
|
||||
if err != nil {
|
||||
return Names{}, err
|
||||
}
|
||||
out, err := m.Run(ctx, "busctl", append(args, "--json=short", "--no-pager", "list")...)
|
||||
if err != nil {
|
||||
return Names{}, err
|
||||
}
|
||||
return ParseNames(orWord(bus, "system"), out)
|
||||
}
|
||||
|
||||
func deref(p *uint32) uint32 {
|
||||
if p == nil {
|
||||
return 0
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
func derefS(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
return *p
|
||||
}
|
||||
|
||||
func orWord(s, word string) string {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return word
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Recorded answers, trimmed, from a workstation of 2026-10-05.
|
||||
const busctlList = `[{"name":":1.0","pid":456,"process":"systemd-timesyn","user":"systemd-timesync","connection":":1.0","unit":"systemd-timesyncd.service","session":null,"description":null},` +
|
||||
`{"name":"fi.w1.wpa_supplicant1","pid":1442,"process":"wpa_supplicant","user":"root","connection":":1.23","unit":"wpa_supplicant.service","session":null,"description":null},` +
|
||||
`{"name":"org.blueman.Mechanism","pid":null,"process":null,"user":null,"connection":"(activatable)","unit":null,"session":null,"description":null},` +
|
||||
`{"name":":1.11","pid":975,"process":"polkitd","user":"polkitd","connection":":1.11","unit":"polkit.service","session":null,"description":null},` +
|
||||
`{"name":"org.freedesktop.DBus","pid":807,"process":"dbus-broker-lau","user":"root","connection":"org.freedesktop.DBus","unit":"dbus-broker.service","session":null,"description":null}]`
|
||||
|
||||
func TestNamesAreSplitIntoRunningActivatableAndConnections(t *testing.T) {
|
||||
n, err := ParseNames("system", busctlList)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n.Connections != 2 || len(n.Running) != 1 || n.Running[0].Name != "fi.w1.wpa_supplicant1" ||
|
||||
n.Running[0].Unit != "wpa_supplicant.service" || n.Running[0].PID != 1442 {
|
||||
t.Fatalf("%+v", n)
|
||||
}
|
||||
if !reflect.DeepEqual(n.ActivatableNotRunning, []string{"org.blueman.Mechanism"}) {
|
||||
t.Fatalf("%v", n.ActivatableNotRunning)
|
||||
}
|
||||
}
|
||||
|
||||
const introspection = `{"type":"s","data":["<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\" \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n<node>\n <interface name=\"org.freedesktop.login1.Manager\">\n <property name=\"IdleHint\" type=\"b\" access=\"read\"></property>\n <method name=\"Inhibit\">\n <arg type=\"s\" name=\"what\" direction=\"in\"/>\n <arg type=\"h\" name=\"pipe_fd\" direction=\"out\"/>\n </method>\n <signal name=\"PrepareForSleep\">\n <arg type=\"b\" name=\"start\"/>\n </signal>\n </interface>\n <node name=\"session\"/>\n <node name=\"seat\"/>\n</node>\n"]}`
|
||||
|
||||
func TestAnIntrospectionIsShapedWithoutValues(t *testing.T) {
|
||||
node, err := ParseIntrospection(introspection)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o := Shape("system", "org.freedesktop.login1", "/org/freedesktop/login1", node)
|
||||
if len(o.Interfaces) != 1 || !reflect.DeepEqual(o.Children, []string{"session", "seat"}) {
|
||||
t.Fatalf("%+v", o)
|
||||
}
|
||||
i := o.Interfaces[0]
|
||||
if !reflect.DeepEqual(i.Methods[0], Member{Name: "Inhibit", In: []string{"what s"}, Out: []string{"pipe_fd h"}}) ||
|
||||
!reflect.DeepEqual(i.Properties[0], Property{Name: "IdleHint", Type: "b", Access: "read"}) ||
|
||||
!reflect.DeepEqual(i.Signals[0], Member{Name: "PrepareForSleep", Args: []string{"start b"}}) {
|
||||
t.Fatalf("%+v", i)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntrospectRefusesWhatIsNotANameOrAPathAndNeverStartsAService(t *testing.T) {
|
||||
var asked []string
|
||||
m := testMachine(t, nil)
|
||||
m.Run = func(_ context.Context, name string, args ...string) (string, error) {
|
||||
asked = append([]string{name}, args...)
|
||||
return introspection, nil
|
||||
}
|
||||
if _, err := m.Introspect(context.Background(), "system", "--address=x", "/"); err == nil {
|
||||
t.Fatal("an option was taken for a bus name")
|
||||
}
|
||||
if _, err := m.Introspect(context.Background(), "system", "org.freedesktop.login1", "relative"); err == nil {
|
||||
t.Fatal("a relative path was taken")
|
||||
}
|
||||
if _, err := m.Introspect(context.Background(), "system", "org.freedesktop.login1", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(strings.Join(asked, " "), "--auto-start=no") || asked[len(asked)-3] != "/" {
|
||||
t.Fatalf("%v", asked)
|
||||
}
|
||||
}
|
||||
|
||||
const monitorLines = `{"type":"method_call","endian":"l","flags":0,"version":1,"cookie":186058,"timestamp-realtime":1791193058632202,"sender":":1.797","destination":"org.freedesktop.UPower","path":"/org/freedesktop/UPower","interface":"org.freedesktop.UPower","member":"GetDisplayDevice","payload":{"type":"","data":[]}}
|
||||
{"type":"signal","endian":"l","flags":1,"version":1,"cookie":7,"timestamp-realtime":1791193058632725,"sender":":1.40","path":"/org/freedesktop/Notifications","interface":"org.freedesktop.Notifications","member":"Notify","payload":{"type":"susssasa{sv}i","data":["app",0,"","the secret notification text","the clipboard's password",[],{},5000]}}
|
||||
not json at all
|
||||
{"type":"error","endian":"l","flags":1,"version":1,"cookie":9,"sender":":1.9","destination":":1.797","error_name":"org.freedesktop.DBus.Error.AccessDenied","payload":{"type":"s","data":["the reason, with a token"]}}`
|
||||
|
||||
func TestAMonitoredMessageIsItsHeaderOnly(t *testing.T) {
|
||||
var asked []string
|
||||
m := testMachine(t, nil)
|
||||
m.Stream = func(ctx context.Context, line func(string) bool, name string, args ...string) error {
|
||||
asked = append([]string{name}, args...)
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
t.Error("the watch has no deadline")
|
||||
}
|
||||
for _, l := range strings.Split(monitorLines, "\n") {
|
||||
if !line(l) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
w, err := m.Monitor(context.Background(), "system", 3, "type='signal'", []string{"org.freedesktop.Notifications"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(w)
|
||||
for _, secret := range []string{"secret notification", "password", "token", "payload", "data"} {
|
||||
if strings.Contains(string(raw), secret) {
|
||||
t.Errorf("the answer carries %q: %s", secret, raw)
|
||||
}
|
||||
}
|
||||
if w.Total != 3 || w.Messages[1].Member != "Notify" || w.Messages[2].ErrorName != "org.freedesktop.DBus.Error.AccessDenied" {
|
||||
t.Fatalf("%+v", w)
|
||||
}
|
||||
cmd := strings.Join(asked, " ")
|
||||
if !strings.HasPrefix(cmd, "sudo -n timeout 3s busctl --system") || !strings.Contains(cmd, "--match=type='signal'") ||
|
||||
!strings.HasSuffix(cmd, "org.freedesktop.Notifications") {
|
||||
t.Fatalf("%s", cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMonitorIsBoundedAndTheSessionBusIsTheAccounts(t *testing.T) {
|
||||
m := testMachine(t, map[string]string{"/run/user/1000/bus": ""})
|
||||
var asked string
|
||||
m.Stream = func(_ context.Context, _ func(string) bool, name string, args ...string) error {
|
||||
asked = name + " " + strings.Join(args, " ")
|
||||
return nil
|
||||
}
|
||||
for _, s := range []int{0, MaxMonitorSeconds + 1} {
|
||||
if _, err := m.Monitor(context.Background(), "system", s, "", nil); err == nil {
|
||||
t.Errorf("%d seconds were accepted", s)
|
||||
}
|
||||
}
|
||||
if _, err := m.Monitor(context.Background(), "session", 2, "", []string{"-x"}); err == nil {
|
||||
t.Error("an option was taken for a name")
|
||||
}
|
||||
if _, err := m.Monitor(context.Background(), "session", 2, "", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.HasPrefix(asked, "sudo") || !strings.Contains(asked, "--address=unix:path=/run/user/1000/bus") {
|
||||
t.Fatalf("%s", asked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestASessionBusIsFoundOrSaidMissing(t *testing.T) {
|
||||
m := testMachine(t, nil)
|
||||
if _, err := m.SessionAddress(); !errors.Is(err, ErrNoSession) {
|
||||
t.Fatalf("a server without a session said %v", err)
|
||||
}
|
||||
m = testMachine(t, map[string]string{"/run/user/1000/bus": ""})
|
||||
if a, err := m.SessionAddress(); err != nil || a != "unix:path=/run/user/1000/bus" {
|
||||
t.Fatalf("%q %v", a, err)
|
||||
}
|
||||
m.Env = func(k string) string {
|
||||
if k == "DBUS_SESSION_BUS_ADDRESS" {
|
||||
return "unix:path=/run/user/1000/bus,guid=abc"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if a, _ := m.SessionAddress(); a != "unix:path=/run/user/1000/bus,guid=abc" {
|
||||
t.Fatalf("%q", a)
|
||||
}
|
||||
}
|
||||
|
||||
const journalLines = `{"__CURSOR":"s=1;i=1","__REALTIME_TIMESTAMP":"1791192960341045","MESSAGE":"Ready","_PID":"807"}
|
||||
{"__CURSOR":"s=1;i=2","__REALTIME_TIMESTAMP":"1791192960341045","MESSAGE":"A security policy denied :1.1199 to send method call /org/freedesktop/DBus:org.freedesktop.DBus.Debug.Stats.GetStats to org.freedesktop.DBus.","DBUS_BROKER_TRANSMIT_ACTION":"send","DBUS_BROKER_MESSAGE_TYPE":"method_call","DBUS_BROKER_SENDER_UNIQUE_NAME":":1.1199","DBUS_BROKER_MESSAGE_DESTINATION":"org.freedesktop.DBus","DBUS_BROKER_MESSAGE_PATH":"/org/freedesktop/DBus","DBUS_BROKER_MESSAGE_INTERFACE":"org.freedesktop.DBus.Debug.Stats","DBUS_BROKER_MESSAGE_MEMBER":"GetStats","DBUS_BROKER_POLICY_TYPE":"internal"}
|
||||
{"__CURSOR":"s=1;i=3","MESSAGE":[65,66]}`
|
||||
|
||||
func TestDenialsAreReadFromTheJournalByTheirFields(t *testing.T) {
|
||||
d, cursor := ParseDenials(journalLines)
|
||||
if cursor != "s=1;i=3" || len(d) != 1 {
|
||||
t.Fatalf("%q %+v", cursor, d)
|
||||
}
|
||||
want := Denial{At: "2026-10-05T09:36:00Z", Action: "send", Type: "method_call", Sender: ":1.1199",
|
||||
Destination: "org.freedesktop.DBus", Path: "/org/freedesktop/DBus", Interface: "org.freedesktop.DBus.Debug.Stats",
|
||||
Member: "GetStats", Policy: "internal"}
|
||||
if d[0] != want {
|
||||
t.Fatalf("%+v", d[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheJournalIsReadFromTheCursorOn(t *testing.T) {
|
||||
m := testMachine(t, nil)
|
||||
var asked []string
|
||||
m.Run = func(_ context.Context, name string, args ...string) (string, error) {
|
||||
asked = append([]string{name}, args...)
|
||||
return journalLines, nil
|
||||
}
|
||||
_, next, _ := m.Denials(context.Background(), "", time.Unix(100, 0))
|
||||
if !strings.Contains(strings.Join(asked, " "), "--since @100") {
|
||||
t.Fatalf("%v", asked)
|
||||
}
|
||||
m.Denials(context.Background(), next, time.Time{})
|
||||
if !strings.Contains(strings.Join(asked, " "), "--after-cursor s=1;i=3") || !strings.Contains(strings.Join(asked, " "), "-u dbus-broker.service") {
|
||||
t.Fatalf("%v", asked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUnitIsReadFromACgroup(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"0::/system.slice/bluetooth.service\n": "bluetooth.service",
|
||||
"0::/user.slice/user-1000.slice/user@1000.service/app.slice/dunst.service": "dunst.service",
|
||||
"0::/user.slice/user-1000.slice/session-2.scope": "session-2.scope",
|
||||
"0::/init.scope": "init.scope",
|
||||
"": "",
|
||||
} {
|
||||
if got := UnitFromCgroup(in); got != want {
|
||||
t.Errorf("%q: %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestShowBlocksAreReadInOrder(t *testing.T) {
|
||||
b := ParseShow("Id=dbus-org.freedesktop.resolve1.service\nLoadState=not-found\n\nId=systemd-hostnamed.service\nLoadState=loaded\n")
|
||||
if len(b) != 2 || b[0]["LoadState"] != "not-found" || b[1]["Id"] != "systemd-hostnamed.service" {
|
||||
t.Fatalf("%v", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunningBusOlderThanItsPackageIsSaid(t *testing.T) {
|
||||
p := ParseDesc("%NAME%\ndbus-broker\n\n%VERSION%\n37-3\n\n%INSTALLDATE%\n1772097880\n")
|
||||
if p.Name != "dbus-broker" || p.Version != "37-3" || p.Installed.Unix() != 1772097880 {
|
||||
t.Fatalf("%+v", p)
|
||||
}
|
||||
if due, _ := RebootDue(time.Unix(1791123478, 0), []Package{p}); due {
|
||||
t.Fatal("a bus started after its package was said to be older")
|
||||
}
|
||||
due, detail := RebootDue(time.Unix(1772000000, 0), []Package{p})
|
||||
if !due || !strings.Contains(detail, "reboot is due") || !strings.Contains(detail, "dbus-broker 37-3") {
|
||||
t.Fatalf("%v %s", due, detail)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionsAreCountedFromStatsOrNames(t *testing.T) {
|
||||
stats := `{"type":"a{sv}","data":[{"org.bus1.DBus.Debug.Stats.PeerAccounting":{"type":"a(sa{sv}a{su})","data":[[":1.0",{},{}],[":1.1",{},{}],[":1.7",{},{}]]}}]}`
|
||||
if n, ok := CountConnections(stats); !ok || n != 3 {
|
||||
t.Fatalf("%d %v", n, ok)
|
||||
}
|
||||
if n, ok := CountConnections(`{"type":"a{sv}","data":[{"ActiveConnections":{"type":"u","data":12}}]}`); !ok || n != 12 {
|
||||
t.Fatalf("%d %v", n, ok)
|
||||
}
|
||||
if n, ok := CountUniqueNames(`{"type":"as","data":[["org.freedesktop.DBus",":1.0","org.bluez",":1.5"]]}`); !ok || n != 2 {
|
||||
t.Fatalf("%d %v", n, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatsAreNeverAskedAsTheAccount(t *testing.T) {
|
||||
m := testMachine(t, nil)
|
||||
var calls []string
|
||||
m.Run = func(_ context.Context, name string, args ...string) (string, error) {
|
||||
line := name + " " + strings.Join(args, " ")
|
||||
calls = append(calls, line)
|
||||
if name == "sudo" {
|
||||
return "", errors.New("sudo: a password is required")
|
||||
}
|
||||
if strings.Contains(line, "ListNames") {
|
||||
return `{"type":"as","data":[[":1.0",":1.1"]]}`, nil
|
||||
}
|
||||
return "Id=dbus-broker.service\nActiveState=active\nMainPID=807\nActiveEnterTimestamp=@1791123478\n", nil
|
||||
}
|
||||
h := m.Health(context.Background(), nil)
|
||||
for _, c := range calls {
|
||||
if strings.Contains(c, "GetStats") && !strings.HasPrefix(c, "sudo -n ") {
|
||||
t.Fatalf("Debug.Stats asked as the account, which the bus logs as a denial: %s", c)
|
||||
}
|
||||
}
|
||||
if h["connections"] != 2 || h["unit"] != "dbus-broker.service" {
|
||||
t.Fatalf("%v", h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCheckReadsPackagesUnitsServiceFilesAndDenials(t *testing.T) {
|
||||
m := testMachine(t, map[string]string{
|
||||
"/var/lib/pacman/local/dbus-1.16.2-1/desc": "%NAME%\ndbus\n\n%VERSION%\n1.16.2-1\n\n%INSTALLDATE%\n1741340000\n",
|
||||
"/var/lib/pacman/local/dbus-broker-37-3/desc": "%NAME%\ndbus-broker\n\n%VERSION%\n37-3\n\n%INSTALLDATE%\n1800000000\n",
|
||||
"/var/lib/pacman/local/dbus-broker-units-37-3/desc": "%NAME%\ndbus-broker-units\n\n%VERSION%\n37-3\n\n%INSTALLDATE%\n1772097880\n",
|
||||
"/usr/share/dbus-1/system-services/org.bluez.service": "[D-BUS Service]\nName=org.bluez\nExec=/bin/false\nUser=root\nSystemdService=dbus-org.bluez.service\n",
|
||||
"/usr/share/dbus-1/system-services/org.example.service": "[D-BUS Service]\nName=org.example\nSystemdService=example.service\n",
|
||||
"/usr/share/dbus-1/system-services/org.freedesktop.systemd1.service": "[D-BUS Service]\nName=org.freedesktop.systemd1\nExec=/bin/false\n",
|
||||
})
|
||||
m.Run = func(_ context.Context, name string, args ...string) (string, error) {
|
||||
line := strings.Join(args, " ")
|
||||
switch {
|
||||
case name == "journalctl":
|
||||
return journalLines, nil
|
||||
case strings.Contains(line, "Id,LoadState"):
|
||||
return "Id=dbus-org.bluez.service\nLoadState=not-found\n\nId=example.service\nLoadState=not-found\n", nil
|
||||
default:
|
||||
return "Id=dbus-broker.service\nActiveState=active\nMainPID=807\nActiveEnterTimestamp=@1791123478\n", nil
|
||||
}
|
||||
}
|
||||
got := m.Check(context.Background(), nil)
|
||||
byName := map[string]Check{}
|
||||
for _, c := range got["checks"].([]Check) {
|
||||
byName[c.Name] = c
|
||||
}
|
||||
if !byName["package dbus-broker-units"].OK || !byName["system bus"].OK {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if c := byName["running bus is the installed one"]; c.OK || !strings.Contains(c.Detail, "dbus-broker 37-3") {
|
||||
t.Fatalf("an upgraded broker was not said: %+v", c)
|
||||
}
|
||||
if c := byName["activatable services"]; c.OK || !strings.Contains(c.Detail, "org.example → example.service") || strings.Contains(c.Detail, "bluez") {
|
||||
t.Fatalf("%+v", c)
|
||||
}
|
||||
if c := byName["policy denials in the last hour"]; c.OK || !strings.Contains(c.Detail, "GetStats") {
|
||||
t.Fatalf("%+v", c)
|
||||
}
|
||||
if !strings.Contains(strings.Join(got["notes"].([]string), " "), "org.bluez → dbus-org.bluez.service") {
|
||||
t.Fatalf("%v", got["notes"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
var busArg = map[string]any{"type": "string", "enum": Buses,
|
||||
"description": "system (the default) or session (this account's login session bus, where one exists)"}
|
||||
|
||||
func busOf(args map[string]any) string {
|
||||
b, _ := args["bus"].(string)
|
||||
return b
|
||||
}
|
||||
|
||||
// Tools are the module's tools over MCP (novox/hq ADR 0215): the names on either bus, what an object
|
||||
// offers, a bounded watch of message headers, the module's check, and the bus's health.
|
||||
func Tools(m *Machine, w *Watcher) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{
|
||||
Name: "dbus_names",
|
||||
Description: "Every well-known name on the system or session bus: its owner's pid, process, user and " +
|
||||
"systemd unit, the activatable names that are not running, and how many connections the bus has. " +
|
||||
"Read as the operator's account.",
|
||||
Input: map[string]any{"type": "object", "properties": map[string]any{"bus": busArg}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
return m.Names(context.Background(), busOf(args))
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "dbus_introspect",
|
||||
Description: "What one object on a bus offers: its interfaces with their methods (arguments in and out), " +
|
||||
"properties (type and access, never their values) and signals, and its child objects. A service " +
|
||||
"that is not running is not started for it.",
|
||||
Input: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"bus": busArg,
|
||||
"service": map[string]any{"type": "string", "description": "the bus name, e.g. org.freedesktop.login1"},
|
||||
"path": map[string]any{"type": "string", "description": "the object path (default /)"},
|
||||
},
|
||||
"required": []string{"service"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
service, _ := args["service"].(string)
|
||||
path, _ := args["path"].(string)
|
||||
return m.Introspect(context.Background(), busOf(args), service, path)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "dbus_monitor",
|
||||
Description: fmt.Sprintf("Watch a bus for a few seconds (at most %d) and answer the headers of the "+
|
||||
"messages that passed: type, sender, destination, path, interface, member. Never a message's body, "+
|
||||
"which carries secrets, notification text and the clipboard. Optional match rule and names to "+
|
||||
"narrow it. The system bus is watched as root through sudo -n.", MaxMonitorSeconds),
|
||||
Input: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"bus": busArg,
|
||||
"seconds": map[string]any{"type": "integer", "description": fmt.Sprintf("how long (default 5, at most %d)", MaxMonitorSeconds)},
|
||||
"match": map[string]any{"type": "string", "description": "a D-Bus match rule, e.g. type='signal',interface='org.freedesktop.login1.Manager'"},
|
||||
"names": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "only messages to or from these bus names"},
|
||||
},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
s := 5
|
||||
if v, ok := args["seconds"].(float64); ok {
|
||||
s = int(v)
|
||||
}
|
||||
match, _ := args["match"].(string)
|
||||
var names []string
|
||||
if list, ok := args["names"].([]any); ok {
|
||||
for _, n := range list {
|
||||
if str, ok := n.(string); ok {
|
||||
names = append(names, str)
|
||||
}
|
||||
}
|
||||
}
|
||||
return m.Monitor(context.Background(), busOf(args), s, match, names)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "dbus_check",
|
||||
Description: "Whether this machine's message bus is as the mesh expects: the bus's packages installed, " +
|
||||
"dbus-broker running behind dbus.service, whether the running bus is older than its installed " +
|
||||
"package (then a reboot is due: the bus is never restarted live), activatable services whose " +
|
||||
"unit does not exist, policy denials in the last hour, and the watcher's state.",
|
||||
Run: func(map[string]any) (any, error) { return m.Check(context.Background(), w), nil },
|
||||
},
|
||||
{
|
||||
Name: "dbus_health",
|
||||
Description: "The system bus's health now: a ping's round trip, how many connections it has, its unit, " +
|
||||
"pid and uptime, and what the watcher last saw.",
|
||||
Run: func(map[string]any) (any, error) { return m.Health(context.Background(), w), nil },
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,619 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The watcher publishes what matters about the machine's system bus as this module's events
|
||||
// (novox/hq ADR 0215 §3): its health, a well-known service appearing or leaving, and a policy
|
||||
// denial. It reads only the bus driver's own answers and signals and the bus unit's journal. It never
|
||||
// becomes a monitor and never sees another peer's messages, so traffic cannot leave the machine
|
||||
// through it: the event bodies are built from names, pids, units and the denial's header fields.
|
||||
|
||||
// Event types, as the module's manifest declares them in `emits`.
|
||||
const (
|
||||
BusStalled = "bus.stalled"
|
||||
BusRecovered = "bus.recovered"
|
||||
BusRestarted = "bus.restarted"
|
||||
ServiceAppeared = "service.appeared"
|
||||
ServiceLeft = "service.left"
|
||||
PolicyDenied = "policy.denied"
|
||||
)
|
||||
|
||||
// Emits is every event the watcher publishes, in the manifest's order.
|
||||
var Emits = []string{BusStalled, BusRecovered, BusRestarted, ServiceAppeared, ServiceLeft, PolicyDenied}
|
||||
|
||||
const (
|
||||
// PingEvery is how often the bus is pinged.
|
||||
PingEvery = 10 * time.Second
|
||||
// StallAfter is how long a ping may take before the bus counts as stalled.
|
||||
StallAfter = 3 * time.Second
|
||||
// Debounce is how long a name must stay as it is before its change is said: a service restarted
|
||||
// within it, or one that flaps, says nothing.
|
||||
Debounce = 10 * time.Second
|
||||
// DenialsEvery is how often the journal is read for policy denials.
|
||||
DenialsEvery = 30 * time.Second
|
||||
// DenialEventEvery is the least time between two policy.denied events; denials in between are
|
||||
// counted into the next one.
|
||||
DenialEventEvery = 5 * time.Minute
|
||||
// MaxQueue is the most events kept while the mesh's bus does not take them; the oldest go first.
|
||||
MaxQueue = 1000
|
||||
// DenialExamples is the most distinct denials one policy.denied names.
|
||||
DenialExamples = 5
|
||||
)
|
||||
|
||||
// NameChange is the bus driver's NameOwnerChanged: a name, its old owner and its new one.
|
||||
type NameChange struct{ Name, Old, New string }
|
||||
|
||||
// Bus is the system bus as the watcher uses it, behind an interface so it is tested without one.
|
||||
type Bus interface {
|
||||
Ping(ctx context.Context) error
|
||||
ID(ctx context.Context) (string, error)
|
||||
PID(ctx context.Context, name string) (uint32, error)
|
||||
Names(ctx context.Context) ([]string, error)
|
||||
Activatable(ctx context.Context) ([]string, error)
|
||||
// Changes closes when the connection is lost.
|
||||
Changes() <-chan NameChange
|
||||
Close()
|
||||
}
|
||||
|
||||
// Emitter publishes one event and returns once the mesh's bus has it.
|
||||
type Emitter func(eventType string, body any) error
|
||||
|
||||
// Journal answers the policy denials in the bus unit's journal after a cursor (or, with none, since
|
||||
// a time), and the cursor to continue from.
|
||||
type Journal func(ctx context.Context, after string, since time.Time) ([]Denial, string, error)
|
||||
|
||||
type queued struct {
|
||||
Type string
|
||||
Body map[string]any
|
||||
}
|
||||
|
||||
type owner struct {
|
||||
PID uint32
|
||||
Process string
|
||||
Unit string
|
||||
}
|
||||
|
||||
// Watcher is the long-running half of the module.
|
||||
type Watcher struct {
|
||||
m *Machine
|
||||
emit Emitter
|
||||
dial func() (Bus, error)
|
||||
journal Journal
|
||||
now func() time.Time
|
||||
state string // where the last seen bus identity is kept, across restarts of the runtime
|
||||
retry time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
bus Bus
|
||||
queue []queued
|
||||
dropped int
|
||||
issue string
|
||||
|
||||
connected bool
|
||||
stalled bool
|
||||
stallSince time.Time
|
||||
stallReason string
|
||||
lastPing time.Duration
|
||||
lastPingAt time.Time
|
||||
busID string
|
||||
brokerPID uint32
|
||||
|
||||
baselined bool
|
||||
current map[string]bool
|
||||
published map[string]owner
|
||||
dirty map[string]time.Time
|
||||
activatable map[string]bool
|
||||
|
||||
cursor string
|
||||
denials int
|
||||
denialSince time.Time
|
||||
examples []Denial
|
||||
lastDenial time.Time
|
||||
|
||||
kick chan struct{}
|
||||
}
|
||||
|
||||
// NewWatcher is a watcher for this machine, emitting through emit, reaching the bus through dial and
|
||||
// the journal through journal.
|
||||
func NewWatcher(m *Machine, emit Emitter, dial func() (Bus, error), journal Journal) *Watcher {
|
||||
home, _ := os.UserHomeDir()
|
||||
now := time.Now
|
||||
if m != nil && m.Now != nil {
|
||||
now = m.Now
|
||||
}
|
||||
return &Watcher{m: m, emit: emit, dial: dial, journal: journal, now: now,
|
||||
state: filepath.Join(home, ".local", "state", "mesh-dbus", "bus"), retry: 5 * time.Second,
|
||||
current: map[string]bool{}, published: map[string]owner{}, dirty: map[string]time.Time{},
|
||||
activatable: map[string]bool{}, kick: make(chan struct{}, 1)}
|
||||
}
|
||||
|
||||
// Snapshot is what dbus_check and dbus_health show of the watcher.
|
||||
type Snapshot struct {
|
||||
Connected bool `json:"connected"`
|
||||
Stalled bool `json:"stalled"`
|
||||
StalledSince string `json:"stalled_since,omitempty"`
|
||||
StallReason string `json:"stall_reason,omitempty"`
|
||||
LastPingMS float64 `json:"last_ping_ms"`
|
||||
LastPingAt string `json:"last_ping_at,omitempty"`
|
||||
BusID string `json:"bus_id,omitempty"`
|
||||
BrokerPID uint32 `json:"broker_pid,omitempty"`
|
||||
Services int `json:"well_known_names"`
|
||||
Pending int `json:"pending_events"`
|
||||
Dropped int `json:"dropped_events,omitempty"`
|
||||
Problem string `json:"problem,omitempty"`
|
||||
}
|
||||
|
||||
func (w *Watcher) Snapshot() Snapshot {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
s := Snapshot{Connected: w.connected, Stalled: w.stalled, StallReason: w.stallReason,
|
||||
LastPingMS: float64(w.lastPing.Microseconds()) / 1000, BusID: w.busID, BrokerPID: w.brokerPID,
|
||||
Services: len(w.published), Pending: len(w.queue), Dropped: w.dropped, Problem: w.issue}
|
||||
if w.stalled {
|
||||
s.StalledSince = w.stallSince.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if !w.lastPingAt.IsZero() {
|
||||
s.LastPingAt = w.lastPingAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (w *Watcher) problem(s string) {
|
||||
w.mu.Lock()
|
||||
w.issue = s
|
||||
w.mu.Unlock()
|
||||
}
|
||||
|
||||
// enqueue adds an event in order, stamped with when it happened. A full queue lets the oldest go and
|
||||
// counts it: a mesh bus gone for a day must not grow the process without bound.
|
||||
func (w *Watcher) enqueue(eventType string, body map[string]any) {
|
||||
if body == nil {
|
||||
body = map[string]any{}
|
||||
}
|
||||
body["at"] = w.now().UTC().Format(time.RFC3339)
|
||||
w.mu.Lock()
|
||||
w.queue = append(w.queue, queued{eventType, body})
|
||||
if len(w.queue) > MaxQueue {
|
||||
w.dropped += len(w.queue) - MaxQueue
|
||||
w.queue = w.queue[len(w.queue)-MaxQueue:]
|
||||
}
|
||||
w.mu.Unlock()
|
||||
select {
|
||||
case w.kick <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// flush publishes what waits, in order, and stops at the first the mesh's bus does not take.
|
||||
func (w *Watcher) flush() {
|
||||
for {
|
||||
w.mu.Lock()
|
||||
if len(w.queue) == 0 {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
next := w.queue[0]
|
||||
w.mu.Unlock()
|
||||
if err := w.emit(next.Type, next.Body); err != nil {
|
||||
w.problem("the mesh's bus did not take " + next.Type + ": " + err.Error())
|
||||
return
|
||||
}
|
||||
w.mu.Lock()
|
||||
if len(w.queue) > 0 {
|
||||
w.queue = w.queue[1:]
|
||||
}
|
||||
if len(w.queue) == 0 && strings.HasPrefix(w.issue, "the mesh's bus") {
|
||||
w.issue = ""
|
||||
}
|
||||
w.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// flusher publishes on its own, so an emit waiting on the runtime never delays a ping.
|
||||
func (w *Watcher) flusher(ctx context.Context) {
|
||||
tick := time.NewTicker(5 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-w.kick:
|
||||
case <-tick.C:
|
||||
}
|
||||
w.flush()
|
||||
}
|
||||
}
|
||||
|
||||
// markStalled says bus.stalled once, until the bus answers again.
|
||||
func (w *Watcher) markStalled(reason string) {
|
||||
w.mu.Lock()
|
||||
if w.stalled {
|
||||
w.stallReason = reason
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
w.stalled, w.stallSince, w.stallReason = true, w.now(), reason
|
||||
w.mu.Unlock()
|
||||
w.enqueue(BusStalled, map[string]any{"reason": reason})
|
||||
}
|
||||
|
||||
// answered says bus.recovered when a stalled bus answers again.
|
||||
func (w *Watcher) answered() {
|
||||
w.mu.Lock()
|
||||
if !w.stalled {
|
||||
w.mu.Unlock()
|
||||
return
|
||||
}
|
||||
since := w.stallSince
|
||||
w.stalled, w.stallReason = false, ""
|
||||
w.mu.Unlock()
|
||||
w.enqueue(BusRecovered, map[string]any{"stalled_since": since.UTC().Format(time.RFC3339),
|
||||
"stalled_seconds": int(w.now().Sub(since).Seconds())})
|
||||
}
|
||||
|
||||
// ping asks the bus driver to answer within StallAfter.
|
||||
func (w *Watcher) ping(b Bus) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StallAfter)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := b.Ping(ctx)
|
||||
took := time.Since(start)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
w.markStalled("the bus did not answer a ping within " + StallAfter.String())
|
||||
} else {
|
||||
w.markStalled("the bus answered a ping with an error: " + err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
w.mu.Lock()
|
||||
w.lastPing, w.lastPingAt = took, w.now()
|
||||
w.mu.Unlock()
|
||||
w.answered()
|
||||
}
|
||||
|
||||
// PingNow pings the bus on the watcher's connection, for dbus_health.
|
||||
func (w *Watcher) PingNow() (time.Duration, error) {
|
||||
w.mu.Lock()
|
||||
b := w.bus
|
||||
w.mu.Unlock()
|
||||
if b == nil {
|
||||
return 0, errNotConnected
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StallAfter)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
err := b.Ping(ctx)
|
||||
return time.Since(start), err
|
||||
}
|
||||
|
||||
type watcherError string
|
||||
|
||||
func (e watcherError) Error() string { return string(e) }
|
||||
|
||||
const errNotConnected = watcherError("the watcher is not connected to the system bus")
|
||||
|
||||
// identity notes the bus's id and the bus driver's pid, and says bus.restarted when either changed
|
||||
// within one boot: after a boot both change, and that is the machine's news, not the bus's.
|
||||
func (w *Watcher) identity(id string, pid uint32) {
|
||||
boot := w.m.BootID()
|
||||
w.mu.Lock()
|
||||
prevID, prevPID := w.busID, w.brokerPID
|
||||
w.busID, w.brokerPID = id, pid
|
||||
w.mu.Unlock()
|
||||
prevBoot := boot
|
||||
if prevID == "" {
|
||||
if b, err := os.ReadFile(w.state); err == nil {
|
||||
f := strings.Fields(string(b))
|
||||
if len(f) == 3 {
|
||||
prevBoot, prevID = f[0], f[1]
|
||||
prevPID = parsePID(f[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
if prevID != "" && prevBoot == boot && (prevID != id || prevPID != pid) {
|
||||
w.enqueue(BusRestarted, map[string]any{"previous_bus_id": prevID, "bus_id": id,
|
||||
"previous_pid": prevPID, "pid": pid, "unit": w.m.UnitOf(pid)})
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(w.state), 0o755); err == nil {
|
||||
_ = os.WriteFile(w.state, []byte(boot+" "+id+" "+itoa(pid)+"\n"), 0o644)
|
||||
}
|
||||
}
|
||||
|
||||
// IsWellKnown is whether a name is a service's name rather than a connection's: unique names (":1.42")
|
||||
// come and go with every client and are never said, nor is the bus driver's own.
|
||||
func IsWellKnown(name string) bool {
|
||||
return name != "" && !strings.HasPrefix(name, ":") && name != busName
|
||||
}
|
||||
|
||||
// connected baselines the names after a (re)connect. The first time it says nothing; after a lost
|
||||
// connection the difference with what was said is debounced like any other change, so a service that
|
||||
// did not come back with a restarted bus is said to have left.
|
||||
func (w *Watcher) connectedTo(b Bus) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StallAfter)
|
||||
defer cancel()
|
||||
names, err := b.Names(ctx)
|
||||
if err != nil {
|
||||
w.problem("listing the bus's names: " + err.Error())
|
||||
return
|
||||
}
|
||||
act, _ := b.Activatable(ctx)
|
||||
now := w.now()
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.activatable = map[string]bool{}
|
||||
for _, n := range act {
|
||||
w.activatable[n] = true
|
||||
}
|
||||
cur := map[string]bool{}
|
||||
for _, n := range names {
|
||||
if IsWellKnown(n) {
|
||||
cur[n] = true
|
||||
}
|
||||
}
|
||||
if !w.baselined {
|
||||
w.baselined = true
|
||||
w.current = cur
|
||||
for n := range cur {
|
||||
w.published[n] = owner{}
|
||||
w.dirty[n] = time.Time{} // resolved silently at the next settle
|
||||
}
|
||||
return
|
||||
}
|
||||
for n := range cur {
|
||||
if _, said := w.published[n]; !said {
|
||||
w.dirty[n] = now
|
||||
}
|
||||
}
|
||||
for n := range w.published {
|
||||
if !cur[n] {
|
||||
w.dirty[n] = now
|
||||
}
|
||||
}
|
||||
w.current = cur
|
||||
}
|
||||
|
||||
// observe takes one NameOwnerChanged. Only well-known names count.
|
||||
func (w *Watcher) observe(c NameChange) {
|
||||
if !IsWellKnown(c.Name) {
|
||||
return
|
||||
}
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if c.New != "" {
|
||||
w.current[c.Name] = true
|
||||
} else {
|
||||
delete(w.current, c.Name)
|
||||
}
|
||||
w.dirty[c.Name] = w.now()
|
||||
}
|
||||
|
||||
// settle says what changed and stayed changed for Debounce. A name's owner is resolved when it is
|
||||
// said, so the event names the process and the unit that holds it.
|
||||
func (w *Watcher) settle(b Bus) {
|
||||
now := w.now()
|
||||
w.mu.Lock()
|
||||
var due []string
|
||||
for n, at := range w.dirty {
|
||||
if now.Sub(at) >= Debounce {
|
||||
due = append(due, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(due)
|
||||
w.mu.Unlock()
|
||||
for _, n := range due {
|
||||
w.mu.Lock()
|
||||
present := w.current[n]
|
||||
was, said := w.published[n]
|
||||
silent := w.dirty[n].IsZero()
|
||||
delete(w.dirty, n)
|
||||
activatable := w.activatable[n]
|
||||
w.mu.Unlock()
|
||||
switch {
|
||||
case present && (!said || silent):
|
||||
o := w.resolve(b, n)
|
||||
w.mu.Lock()
|
||||
w.published[n] = o
|
||||
w.mu.Unlock()
|
||||
if !silent {
|
||||
w.enqueue(ServiceAppeared, o.body(n, activatable))
|
||||
}
|
||||
case !present && said:
|
||||
w.mu.Lock()
|
||||
delete(w.published, n)
|
||||
w.mu.Unlock()
|
||||
w.enqueue(ServiceLeft, was.body(n, activatable))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Watcher) resolve(b Bus, name string) owner {
|
||||
if b == nil {
|
||||
return owner{}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), StallAfter)
|
||||
defer cancel()
|
||||
pid, err := b.PID(ctx, name)
|
||||
if err != nil {
|
||||
return owner{}
|
||||
}
|
||||
return owner{PID: pid, Process: w.m.ProcessName(pid), Unit: w.m.UnitOf(pid)}
|
||||
}
|
||||
|
||||
func (o owner) body(name string, activatable bool) map[string]any {
|
||||
body := map[string]any{"name": name, "activatable": activatable}
|
||||
if o.PID != 0 {
|
||||
body["pid"] = o.PID
|
||||
}
|
||||
if o.Process != "" {
|
||||
body["process"] = o.Process
|
||||
}
|
||||
if o.Unit != "" {
|
||||
body["unit"] = o.Unit
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// readDenials takes the denials logged since the last read, and says policy.denied at most once per
|
||||
// DenialEventEvery, with the count and a few distinct examples: a client denied in a loop must not
|
||||
// flood the mesh's bus.
|
||||
func (w *Watcher) readDenials(ctx context.Context, start time.Time) {
|
||||
if w.journal == nil {
|
||||
return
|
||||
}
|
||||
w.mu.Lock()
|
||||
cursor := w.cursor
|
||||
w.mu.Unlock()
|
||||
got, next, err := w.journal(ctx, cursor, start)
|
||||
if err != nil {
|
||||
w.problem("reading the bus's journal: " + err.Error())
|
||||
return
|
||||
}
|
||||
now := w.now()
|
||||
w.mu.Lock()
|
||||
if next != "" {
|
||||
w.cursor = next
|
||||
}
|
||||
if strings.HasPrefix(w.issue, "reading the bus's journal") {
|
||||
w.issue = ""
|
||||
}
|
||||
for _, d := range got {
|
||||
if w.denials == 0 {
|
||||
w.denialSince = now
|
||||
}
|
||||
w.denials++
|
||||
if len(w.examples) < DenialExamples && !containsDenial(w.examples, d) {
|
||||
w.examples = append(w.examples, d)
|
||||
}
|
||||
}
|
||||
due := w.denials > 0 && (w.lastDenial.IsZero() || now.Sub(w.lastDenial) >= DenialEventEvery)
|
||||
var body map[string]any
|
||||
if due {
|
||||
body = map[string]any{"count": w.denials, "since": w.denialSince.UTC().Format(time.RFC3339),
|
||||
"examples": w.examples}
|
||||
w.denials, w.examples, w.lastDenial = 0, nil, now
|
||||
}
|
||||
w.mu.Unlock()
|
||||
if due {
|
||||
w.enqueue(PolicyDenied, body)
|
||||
}
|
||||
}
|
||||
|
||||
// Run watches until ctx ends. Without the system bus it says the bus stalled, and tries again every
|
||||
// few seconds; a lost connection is followed at once by a new one.
|
||||
func (w *Watcher) Run(ctx context.Context) {
|
||||
go w.flusher(ctx)
|
||||
start := w.now()
|
||||
tick := time.NewTicker(PingEvery)
|
||||
defer tick.Stop()
|
||||
denials := time.NewTicker(DenialsEvery)
|
||||
defer denials.Stop()
|
||||
retry := time.NewTimer(0)
|
||||
defer retry.Stop()
|
||||
var changes <-chan NameChange
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
w.mu.Lock()
|
||||
b := w.bus
|
||||
w.bus, w.connected = nil, false
|
||||
w.mu.Unlock()
|
||||
if b != nil {
|
||||
b.Close()
|
||||
}
|
||||
w.flush()
|
||||
return
|
||||
case <-retry.C:
|
||||
b, err := w.dial()
|
||||
if err != nil {
|
||||
w.markStalled("the system bus is not reachable: " + err.Error())
|
||||
retry.Reset(w.retry)
|
||||
continue
|
||||
}
|
||||
idCtx, cancel := context.WithTimeout(ctx, StallAfter)
|
||||
id, idErr := b.ID(idCtx)
|
||||
pid, _ := b.PID(idCtx, busName)
|
||||
cancel()
|
||||
if idErr != nil {
|
||||
b.Close()
|
||||
w.markStalled("the system bus did not say its id: " + idErr.Error())
|
||||
retry.Reset(w.retry)
|
||||
continue
|
||||
}
|
||||
w.mu.Lock()
|
||||
w.bus, w.connected = b, true
|
||||
w.mu.Unlock()
|
||||
changes = b.Changes()
|
||||
w.identity(id, pid)
|
||||
w.connectedTo(b)
|
||||
w.answered()
|
||||
w.settle(b)
|
||||
case c, open := <-changes:
|
||||
if !open {
|
||||
w.mu.Lock()
|
||||
b := w.bus
|
||||
w.bus, w.connected = nil, false
|
||||
w.mu.Unlock()
|
||||
if b != nil {
|
||||
b.Close()
|
||||
}
|
||||
changes = nil
|
||||
retry.Reset(time.Second)
|
||||
continue
|
||||
}
|
||||
w.observe(c)
|
||||
case <-tick.C:
|
||||
w.mu.Lock()
|
||||
b := w.bus
|
||||
w.mu.Unlock()
|
||||
if b != nil {
|
||||
w.ping(b)
|
||||
w.settle(b)
|
||||
}
|
||||
case <-denials.C:
|
||||
w.readDenials(ctx, start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func containsDenial(list []Denial, d Denial) bool {
|
||||
for _, x := range list {
|
||||
if x.key() == d.key() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parsePID(s string) uint32 {
|
||||
var n uint32
|
||||
for _, c := range s {
|
||||
if c < '0' || c > '9' {
|
||||
return 0
|
||||
}
|
||||
n = n*10 + uint32(c-'0')
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func itoa(n uint32) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
var b [10]byte
|
||||
i := len(b)
|
||||
for n > 0 {
|
||||
i--
|
||||
b[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
}
|
||||
return string(b[i:])
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fakeBus is a system bus in memory: names with their owners' pids, a ping that can hang, and the
|
||||
// NameOwnerChanged stream.
|
||||
type fakeBus struct {
|
||||
mu sync.Mutex
|
||||
id string
|
||||
pid uint32
|
||||
names map[string]uint32
|
||||
hang bool
|
||||
changes chan NameChange
|
||||
}
|
||||
|
||||
func newFakeBus(id string, pid uint32, names map[string]uint32) *fakeBus {
|
||||
return &fakeBus{id: id, pid: pid, names: names, changes: make(chan NameChange, 64)}
|
||||
}
|
||||
|
||||
func (f *fakeBus) Ping(ctx context.Context) error {
|
||||
f.mu.Lock()
|
||||
hang := f.hang
|
||||
f.mu.Unlock()
|
||||
if hang {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (f *fakeBus) ID(context.Context) (string, error) { return f.id, nil }
|
||||
func (f *fakeBus) PID(_ context.Context, name string) (uint32, error) {
|
||||
if name == busName {
|
||||
return f.pid, nil
|
||||
}
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if p, ok := f.names[name]; ok {
|
||||
return p, nil
|
||||
}
|
||||
return 0, errors.New("no such name")
|
||||
}
|
||||
func (f *fakeBus) Names(context.Context) ([]string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
out := []string{busName, ":1.0", ":1.1"}
|
||||
for n := range f.names {
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (f *fakeBus) Activatable(context.Context) ([]string, error) {
|
||||
return []string{"org.freedesktop.hostname1"}, nil
|
||||
}
|
||||
func (f *fakeBus) Changes() <-chan NameChange { return f.changes }
|
||||
func (f *fakeBus) Close() {}
|
||||
|
||||
// meshBus records what was published, and can refuse.
|
||||
type meshBus struct {
|
||||
mu sync.Mutex
|
||||
down bool
|
||||
types []string
|
||||
bodies []map[string]any
|
||||
}
|
||||
|
||||
func (b *meshBus) emit(t string, body any) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.down {
|
||||
return errors.New("no bus")
|
||||
}
|
||||
b.types = append(b.types, t)
|
||||
m, _ := body.(map[string]any)
|
||||
b.bodies = append(b.bodies, m)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *meshBus) seen() []string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return append([]string(nil), b.types...)
|
||||
}
|
||||
|
||||
// clock is a time the test moves.
|
||||
type clock struct{ t time.Time }
|
||||
|
||||
func (c *clock) now() time.Time { return c.t }
|
||||
func (c *clock) advance(d time.Duration) { c.t = c.t.Add(d) }
|
||||
|
||||
func testMachine(t *testing.T, files map[string]string) *Machine {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
for p, c := range files {
|
||||
full := filepath.Join(root, p)
|
||||
os.MkdirAll(filepath.Dir(full), 0o755)
|
||||
os.WriteFile(full, []byte(c), 0o644)
|
||||
}
|
||||
return &Machine{Root: root, Env: func(string) string { return "" }, UID: 1000, Now: time.Now}
|
||||
}
|
||||
|
||||
func testWatcher(t *testing.T, b *meshBus, c *clock) *Watcher {
|
||||
m := testMachine(t, map[string]string{
|
||||
"/proc/sys/kernel/random/boot_id": "boot-1\n",
|
||||
"/proc/700/comm": "systemd-logind\n",
|
||||
"/proc/700/cgroup": "0::/system.slice/systemd-logind.service\n",
|
||||
"/proc/900/comm": "bluetoothd\n",
|
||||
"/proc/900/cgroup": "0::/system.slice/bluetooth.service\n",
|
||||
})
|
||||
w := NewWatcher(m, b.emit, nil, nil)
|
||||
w.now = c.now
|
||||
w.state = filepath.Join(t.TempDir(), "bus")
|
||||
return w
|
||||
}
|
||||
|
||||
func start() *clock { return &clock{t: time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)} }
|
||||
|
||||
func TestTheFirstConnectionSaysNothingAboutNames(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{"org.freedesktop.login1": 700})
|
||||
w.identity("id-1", 500)
|
||||
w.connectedTo(fb)
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); len(got) != 0 {
|
||||
t.Fatalf("the baseline was announced: %v", got)
|
||||
}
|
||||
if w.Snapshot().Services != 1 {
|
||||
t.Fatalf("%+v", w.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceAppearingIsSaidOnceItStaysWithItsUnit(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{})
|
||||
w.connectedTo(fb)
|
||||
fb.names["org.bluez"] = 900
|
||||
w.observe(NameChange{Name: "org.bluez", New: ":1.9"})
|
||||
c.advance(Debounce / 2)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); len(got) != 0 {
|
||||
t.Fatalf("said before the debounce: %v", got)
|
||||
}
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{ServiceAppeared}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
body := mb.bodies[0]
|
||||
if body["name"] != "org.bluez" || body["unit"] != "bluetooth.service" || body["process"] != "bluetoothd" || body["pid"] != uint32(900) {
|
||||
t.Fatalf("%v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFlapIsDebouncedAway(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{"org.freedesktop.login1": 700})
|
||||
w.connectedTo(fb)
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
// logind restarted: left and back within the debounce, and a newcomer that came and went.
|
||||
w.observe(NameChange{Name: "org.freedesktop.login1", Old: ":1.5"})
|
||||
c.advance(time.Second)
|
||||
w.observe(NameChange{Name: "org.freedesktop.login1", New: ":1.80"})
|
||||
w.observe(NameChange{Name: "org.example.Brief", New: ":1.81"})
|
||||
w.observe(NameChange{Name: "org.example.Brief", Old: ":1.81"})
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); len(got) != 0 {
|
||||
t.Fatalf("a flap was said: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceLeavingIsSaidWithTheUnitItHad(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{"org.freedesktop.login1": 700})
|
||||
w.connectedTo(fb)
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
delete(fb.names, "org.freedesktop.login1")
|
||||
w.observe(NameChange{Name: "org.freedesktop.login1", Old: ":1.5"})
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{ServiceLeft}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if mb.bodies[0]["unit"] != "systemd-logind.service" {
|
||||
t.Fatalf("%v", mb.bodies[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestUniqueNamesAndTheDriverAreNeverSaid(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{})
|
||||
w.connectedTo(fb)
|
||||
w.observe(NameChange{Name: ":1.42", New: ":1.42"})
|
||||
w.observe(NameChange{Name: ":1.42", Old: ":1.42"})
|
||||
w.observe(NameChange{Name: busName, New: busName})
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); len(got) != 0 {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
for _, n := range []string{":1.1", busName, ""} {
|
||||
if IsWellKnown(n) {
|
||||
t.Errorf("%q counted as a service", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPingThatHangsIsAStallAndAnAnswerARecovery(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, nil)
|
||||
fb.hang = true
|
||||
begun := time.Now()
|
||||
w.ping(fb)
|
||||
w.ping(fb)
|
||||
if time.Since(begun) > 2*StallAfter+time.Second {
|
||||
t.Fatal("a ping waited longer than its bound")
|
||||
}
|
||||
c.advance(42 * time.Second)
|
||||
fb.hang = false
|
||||
w.ping(fb)
|
||||
w.ping(fb)
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{BusStalled, BusRecovered}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if mb.bodies[1]["stalled_seconds"] != 42 || w.Snapshot().Stalled {
|
||||
t.Fatalf("%v %+v", mb.bodies[1], w.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestARestartWithinABootIsSaidAndABootIsNot(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
w.identity("id-1", 500)
|
||||
w.identity("id-1", 500) // a reconnect to the same bus
|
||||
w.identity("id-2", 501) // the bus came back as another
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{BusRestarted}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if mb.bodies[0]["previous_bus_id"] != "id-1" || mb.bodies[0]["pid"] != uint32(501) {
|
||||
t.Fatalf("%v", mb.bodies[0])
|
||||
}
|
||||
|
||||
// The runtime restarts: the bus it remembers is the one still running, so nothing is said.
|
||||
again := NewWatcher(w.m, mb.emit, nil, nil)
|
||||
again.state, again.now = w.state, c.now
|
||||
again.identity("id-2", 501)
|
||||
// After a boot both change, and that is not the bus's restart.
|
||||
os.WriteFile(filepath.Join(w.m.Root, "/proc/sys/kernel/random/boot_id"), []byte("boot-2\n"), 0o644)
|
||||
third := NewWatcher(w.m, mb.emit, nil, nil)
|
||||
third.state, third.now = w.state, c.now
|
||||
third.identity("id-3", 400)
|
||||
again.flush()
|
||||
third.flush()
|
||||
if got := mb.seen(); len(got) != 1 {
|
||||
t.Fatalf("a runtime restart or a boot was taken for the bus's restart: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceThatDidNotComeBackAfterAReconnectHasLeft(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{"org.freedesktop.login1": 700, "org.bluez": 900})
|
||||
w.connectedTo(fb)
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
back := newFakeBus("id-2", 501, map[string]uint32{"org.freedesktop.login1": 700})
|
||||
w.connectedTo(back)
|
||||
c.advance(Debounce)
|
||||
w.settle(back)
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{ServiceLeft}) || mb.bodies[0]["name"] != "org.bluez" {
|
||||
t.Fatalf("%v %v", got, mb.bodies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsWaitInOrderWhileTheMeshBusIsGone(t *testing.T) {
|
||||
mb, c := &meshBus{down: true}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
w.markStalled("test")
|
||||
c.advance(time.Minute)
|
||||
w.answered()
|
||||
w.flush()
|
||||
if s := w.Snapshot(); s.Pending != 2 || s.Problem == "" {
|
||||
t.Fatalf("what the mesh's bus did not take is not kept and said: %+v", s)
|
||||
}
|
||||
mb.mu.Lock()
|
||||
mb.down = false
|
||||
mb.mu.Unlock()
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{BusStalled, BusRecovered}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if s := w.Snapshot(); s.Pending != 0 || s.Problem != "" {
|
||||
t.Fatalf("%+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFullQueueLetsTheOldestGo(t *testing.T) {
|
||||
mb, c := &meshBus{down: true}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
for i := 0; i < MaxQueue+5; i++ {
|
||||
w.enqueue(ServiceAppeared, map[string]any{"i": i})
|
||||
}
|
||||
s := w.Snapshot()
|
||||
if s.Pending != MaxQueue || s.Dropped != 5 || w.queue[0].Body["i"] != 5 {
|
||||
t.Fatalf("%+v first %v", s, w.queue[0].Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDenialsAreSaidAtMostOncePerWindowWithACount(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
batches := [][]Denial{
|
||||
{{Type: "method_call", Interface: "org.example.A", Member: "Do", Destination: "org.example"}},
|
||||
{{Type: "method_call", Interface: "org.example.A", Member: "Do", Destination: "org.example"},
|
||||
{Type: "method_call", Interface: "org.example.B", Member: "Other", Destination: "org.example"}},
|
||||
{{Type: "method_call", Interface: "org.example.A", Member: "Do", Destination: "org.example"}},
|
||||
}
|
||||
n := 0
|
||||
w.journal = func(ctx context.Context, after string, since time.Time) ([]Denial, string, error) {
|
||||
if n > 0 && after != "c"+string(rune('0'+n-1)) {
|
||||
t.Errorf("read %d did not continue from the cursor: %q", n, after)
|
||||
}
|
||||
d := batches[n]
|
||||
n++
|
||||
return d, "c" + string(rune('0'+n-1)), nil
|
||||
}
|
||||
w.readDenials(context.Background(), c.t)
|
||||
c.advance(DenialsEvery)
|
||||
w.readDenials(context.Background(), c.t)
|
||||
c.advance(DenialEventEvery)
|
||||
w.readDenials(context.Background(), c.t)
|
||||
w.flush()
|
||||
if got := mb.seen(); !reflect.DeepEqual(got, []string{PolicyDenied, PolicyDenied}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if mb.bodies[0]["count"] != 1 || mb.bodies[1]["count"] != 3 {
|
||||
t.Fatalf("%v", mb.bodies)
|
||||
}
|
||||
if ex := mb.bodies[1]["examples"].([]Denial); len(ex) != 2 {
|
||||
t.Fatalf("the same denial is one example: %v", ex)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoEventCarriesTraffic holds every event body to names, pids, units, times, counts and the
|
||||
// header fields of a denial: nothing in the watcher can carry a message's body.
|
||||
func TestNoEventCarriesTraffic(t *testing.T) {
|
||||
mb, c := &meshBus{}, start()
|
||||
w := testWatcher(t, mb, c)
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{})
|
||||
w.connectedTo(fb)
|
||||
fb.names["org.bluez"] = 900
|
||||
w.observe(NameChange{Name: "org.bluez", New: ":1.9"})
|
||||
c.advance(Debounce)
|
||||
w.settle(fb)
|
||||
w.markStalled("x")
|
||||
w.answered()
|
||||
w.identity("a", 1)
|
||||
w.identity("b", 2)
|
||||
w.journal = func(context.Context, string, time.Time) ([]Denial, string, error) {
|
||||
d, cur := ParseDenials(`{"__CURSOR":"c","MESSAGE":"A security policy denied :1.9 to send method call /p:i.m to d.","DBUS_BROKER_MESSAGE_MEMBER":"m","SECRET_BODY":"hunter2"}`)
|
||||
return d, cur, nil
|
||||
}
|
||||
w.readDenials(context.Background(), c.t)
|
||||
w.flush()
|
||||
allowed := map[string]bool{"at": true, "name": true, "pid": true, "process": true, "unit": true, "activatable": true,
|
||||
"reason": true, "stalled_since": true, "stalled_seconds": true, "previous_bus_id": true, "bus_id": true,
|
||||
"previous_pid": true, "count": true, "since": true, "examples": true}
|
||||
if len(mb.types) != 5 {
|
||||
t.Fatalf("%v", mb.types)
|
||||
}
|
||||
for i, b := range mb.bodies {
|
||||
for k := range b {
|
||||
if !allowed[k] {
|
||||
t.Errorf("%s carries %q", mb.types[i], k)
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(b)
|
||||
if strings.Contains(string(raw), "hunter2") || strings.Contains(string(raw), "security policy") {
|
||||
t.Errorf("%s carries what the bus logged verbatim: %s", mb.types[i], raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunWithoutABusSaysItStalledAndReconnects(t *testing.T) {
|
||||
mb := &meshBus{}
|
||||
m := testMachine(t, map[string]string{"/proc/sys/kernel/random/boot_id": "b\n"})
|
||||
fb := newFakeBus("id-1", 500, map[string]uint32{})
|
||||
var dials int
|
||||
w := NewWatcher(m, mb.emit, func() (Bus, error) {
|
||||
dials++
|
||||
if dials == 1 {
|
||||
return nil, errors.New("no socket")
|
||||
}
|
||||
return fb, nil
|
||||
}, nil)
|
||||
w.state = filepath.Join(t.TempDir(), "bus")
|
||||
w.retry = 20 * time.Millisecond
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go func() { w.Run(ctx); close(done) }()
|
||||
deadline := time.Now().Add(6 * time.Second)
|
||||
for time.Now().Before(deadline) && !w.Snapshot().Connected {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if !w.Snapshot().Connected {
|
||||
t.Fatal("the watcher did not reconnect")
|
||||
}
|
||||
close(fb.changes) // the bus goes away
|
||||
for time.Now().Before(deadline) && w.Snapshot().Connected {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
got := mb.seen()
|
||||
if len(got) < 2 || got[0] != BusStalled || got[1] != BusRecovered {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
module dbus
|
||||
|
||||
go 1.22
|
||||
|
||||
require (
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.7
|
||||
github.com/godbus/dbus/v5 v5.1.0
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user