Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

services: keep the systemd client live only while its data is on screen

oxydizerf4be1f9c7a56
diff --git a/TESTING.md b/TESTING.md
index 398f669..2912299 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -115,7 +115,7 @@ GLES requires a render node; `--persistence-only` runs the restart/control check
maximize/fullscreen placement, restore, window rules and depth), `taskbar_peek.py`,
`taskbar_title_repaint.py`, `window_urgency.py`, `start_menu.py`,
`power_menu.py` (only ever activates Log Out), `control_center.py`,
-`control_center.py --services-only` (private systemd and polkit fixture: availability, in-table loading, unlock/lock and prompt cancellation, startup settings, Notify service types and isolated drop-in edits, runtime actions, authorization refusal, analysis, live updates and lifetime),
+`control_center.py --services-only` (private systemd and polkit fixture: availability, in-table loading, unlock/lock and prompt cancellation, startup settings, Notify service types and isolated drop-in edits, runtime actions, authorization refusal, analysis, in-place state updates and coalesced reloads, signal-flood resistance, nothing read until the page is shown or while it is hidden, no RefUnit or unloaded-unit reads, the IPC lease, and lifetime),
`calendar_popup.py`, `bluetooth.py` (private BlueZ service; Settings device search,
radio, discovery cleanup, battery updates, PIN/passkey/confirmation pairing,
connect/disconnect, trust, removal, permissions and service restarts), `wifi_popup.py` (private NetworkManager service; popup and
diff --git a/src/Server.zig b/src/Server.zig
index 29818c0..dd3b562 100644
--- a/src/Server.zig
+++ b/src/Server.zig
@@ -847,7 +847,6 @@ pub fn getSystemd(server: *Server) !*@import("systemd.zig").Client {
if (server.systemd_client) |client| return client;
const client = try @import("systemd.zig").Client.create(server);
server.systemd_client = client;
- client.watching = true;
return client;
}
diff --git a/src/control_center/AGENTS.md b/src/control_center/AGENTS.md
index 29d7314..4cc9b1b 100644
--- a/src/control_center/AGENTS.md
+++ b/src/control_center/AGENTS.md
@@ -13,5 +13,23 @@ Settings is an ordinary window with a compositor-drawn body (`Backend.shell`).
* `close()` frees the content and `Toplevel.destroy`s the window (which may
animate from a snapshot): clear `backend.shell.control_center` and the
node's scene data first, and never close from inside a widget callback.
+* **The Services client (`systemd.zig`) is live only while its page is on screen**
+ (`show` from `services.build`, `hide` from `selectPage`/`detachSettings`) or
+ while an IPC query holds a 15 s `lease`. Live means the signal matches,
+ `Subscribe` and a load; dark means `Unsubscribe`, matches removed and the data
+ dropped. Never `RefUnit` or `LoadUnit`: systemd loads the unit *and its whole
+ dependency closure*, then asks polkit on every call (about 49 ms of PID 1 plus
+ polkitd each, denied when non-interactive, so nothing is ever pinned), and the
+ load/collect churn is broadcast to every subscriber and fed back into the
+ refresh. An unloaded unit is only its unit-file state; nothing is asked of it.
+ A load is ListUnits (its state fields are the rows), ListUnitFiles, then `Get`
+ of Transient, TriggeredBy and Type for each *loaded* unit, once (cached;
+ `refresh`/daemon reload re-read). Signals apply the values they carry; anything
+ else only sets `dirty`, and one reload runs after `settle_ms`. systemd
+ broadcasts thousands of UnitNew/UnitRemoved a second under bulk loads, so no
+ signal may cost a call of its own and none may restart a load. The fake in
+ `control_center.py` emits no such floods; a pass-through proxy that decodes bus
+ messages shows the real traffic without root (`BecomeMonitor` and
+ `Debug.Stats` need it).
* Saving a theme slider rebuilds the page on release: `panel.rebuildTree`
carries named sliders' state across (`src/ui/AGENTS.md`, "Sliders").
diff --git a/src/control_center/panel.zig b/src/control_center/panel.zig
index 995c328..d5d3f01 100644
--- a/src/control_center/panel.zig
+++ b/src/control_center/panel.zig
@@ -640,6 +640,8 @@ pub const ControlCenter = struct {
pub fn selectPage(cc: *ControlCenter, page: Page) void {
cc.shortcuts.cancel();
+ // The service list is only kept live while its page is on screen.
+ if (cc.page == .services and page != .services) if (cc.systemd_client) |client| client.hide();
if (cc.page == .network and page != .network) cc.network.clearForm();
if (cc.page == .bluetooth and page != .bluetooth) {
if (cc.server.bluetooth) |m| m.closed();
diff --git a/src/control_center/sections/services.zig b/src/control_center/sections/services.zig
index 4980813..ce8407c 100644
--- a/src/control_center/sections/services.zig
+++ b/src/control_center/sections/services.zig
@@ -131,7 +131,7 @@ pub fn build(s: *Section, cc: *panel.ControlCenter) void {
};
}
fn tree(s: *Section, cc: *panel.ControlCenter, client: *systemd.Client, a: std.mem.Allocator, saved: ?ui.layout.TextInputData) !W {
- client.open();
+ client.show();
const units = client.snapshot.units.items;
const narrow = cc.panel_box.width < 1040;
const gutter = ui.widgets.scrollbar.gutter(ui.theme.global.scrollbar_width);
diff --git a/src/ipc/settings.zig b/src/ipc/settings.zig
index c22768f..df88a0f 100644
--- a/src/ipc/settings.zig
+++ b/src/ipc/settings.zig
@@ -9,7 +9,7 @@ const gpa = @import("../main.zig").gpa;
pub fn services(server: *Server, a: std.mem.Allocator) !protocol.Response {
const client = server.getSystemd() catch return .{ .err = "ServicesUnavailable" };
- client.open();
+ client.lease();
if (!client.busy() and !client.awaitingList() and !client.analyzed) client.analyze();
const units = client.snapshot.units.items;
const result = try a.alloc(protocol.ServiceData, units.len);
diff --git a/src/systemd.zig b/src/systemd.zig
index cdc2c65..7b73c7b 100644
--- a/src/systemd.zig
+++ b/src/systemd.zig
@@ -3,6 +3,26 @@
//! All requests target the discovered unique owner; generations discard replies
//! from a previous daemon. The Settings window owns this connection.
//!
+//! The client is live only while something shows its data: the Services page
+//! (`show`/`hide`) or a recent IPC query (`lease`). Going live adds the signal
+//! matches, calls Manager.Subscribe and loads the list; going dark removes the
+//! matches, calls Unsubscribe and drops the data. A closed Settings window or a
+//! page nobody looks at costs systemd and polkit nothing.
+//!
+//! Loading is two list calls (ListUnits, whose state fields are the rows'
+//! state, and ListUnitFiles for the startup setting) plus three single-property
+//! reads for each *loaded* unit, once. Unloaded units are never asked about:
+//! they show the unit-file state and "Not loaded", and are never loaded on the
+//! user's behalf (that needs RefUnit, which systemd checks with polkit on every
+//! call; refreshing hundreds of unloaded units that way pinned PID 1 and polkitd).
+//! After the load, signals update rows in place: PropertiesChanged carries the
+//! new state, UnitRemoved unloads its row. Whatever a signal cannot say by itself
+//! (a unit that appeared, a name that was only invalidated, new unit files, a
+//! finished daemon reload) marks the list dirty, and one reload runs after a short
+//! settling time, however many signals arrive. systemd broadcasts thousands of
+//! UnitNew/UnitRemoved a second while anything loads units in bulk, so no signal
+//! may cost a call of its own. Nothing polls.
+//!
//! Changes are locked until the user unlocks them: that asks polkit once for
//! manage-unit-files, whose `imply` annotation also covers manage-units and
//! reload-daemon, so later enable/disable/start/stop/restart calls reuse the
@@ -11,6 +31,7 @@
const std = @import("std");
const dbus = @import("dbus");
const wire = dbus.wire;
+const wl = @import("wayland").server.wl;
const gpa = @import("main.zig").gpa;
const panel = @import("control_center/panel.zig");
const name = "org.freedesktop.systemd1";
@@ -23,6 +44,17 @@ const polkit_path = "/org/freedesktop/PolicyKit1/Authority";
const polkit_authority = polkit_name ++ ".Authority";
const unlock_action = "org.freedesktop.systemd1.manage-unit-files";
const unlock_cancellation = "rediwm-settings-services-unlock";
+const manager_match = "type='signal',sender='" ++ name ++ "',interface='" ++ manager ++ "'";
+const properties_match = "type='signal',sender='" ++ name ++ "',interface='" ++ properties ++ "',path_namespace='" ++ path ++ "/unit'";
+/// How long an IPC query keeps the list live after its last call.
+const lease_ms: i32 = 15000;
+/// How long changes the signals could not describe are allowed to pile up before
+/// the list is read again: at most one reload per this long.
+const settle_ms: i32 = 400;
+const max_in_flight = 8;
+/// Text copied into a snapshot's arena (replaced text stays there) beyond which
+/// the list is rebuilt rather than grown.
+const copied_limit: usize = 1 << 21;
pub const service_types: []const []const u8 = &.{ "exec", "dbus", "simple", "forking", "notify", "oneshot", "idle", "notify-reload" };
@@ -43,6 +75,8 @@ pub const Unit = struct {
transient: bool = false,
trigger: []const u8 = "",
time_us: ?u64 = null,
+ /// Type, Transient and TriggeredBy were requested for this loaded unit.
+ has_details: bool = false,
pub fn enabled(u: Unit) bool {
return std.mem.eql(u8, u.startup, "enabled") or std.mem.eql(u8, u.startup, "enabled-runtime");
@@ -57,16 +91,37 @@ pub const Unit = struct {
}
};
+/// What systemd reports for state, load and startup, as static text. Rows hold
+/// these instead of copies, so a service that flips between states all day adds
+/// nothing to the arena.
+const words = [_][]const u8{
+ "active", "inactive", "failed", "activating", "deactivating", "reloading", "maintenance",
+ "refreshing", "loaded", "not-found", "bad-setting", "error", "masked", "merged",
+ "stub", "unloaded", "running", "exited", "dead", "start", "stop",
+ "start-pre", "start-post", "stop-sigterm", "stop-sigkill", "stop-post", "final-sigterm", "final-sigkill",
+ "auto-restart", "condition", "reload", "cleaning", "enabled", "disabled", "static",
+ "indirect", "generated", "transient", "alias", "linked", "enabled-runtime", "masked-runtime",
+ "linked-runtime", "bad", "unknown",
+};
+fn intern(value: []const u8) ?[]const u8 {
+ for (words) |word| if (std.mem.eql(u8, word, value)) return word;
+ return null;
+}
+
const Snapshot = struct {
arena: std.heap.ArenaAllocator = .init(gpa),
units: std.ArrayList(Unit) = .empty,
index: std.StringHashMapUnmanaged(usize) = .empty,
+ /// Bytes copied into the arena so far, replaced text included.
+ copied: usize = 0,
fn deinit(s: *Snapshot) void {
s.arena.deinit();
s.* = .{};
}
fn copy(s: *Snapshot, value: []const u8) ![]const u8 {
+ if (intern(value)) |word| return word;
+ s.copied += value.len;
return s.arena.allocator().dupe(u8, value);
}
fn get(s: *Snapshot, unit_name: []const u8) !*Unit {
@@ -76,11 +131,134 @@ const Snapshot = struct {
try s.index.put(s.arena.allocator(), owned, s.units.items.len - 1);
return &s.units.items[s.units.items.len - 1];
}
+ /// The loaded unit at an object path, if it is one of the rows.
+ fn at(s: *Snapshot, object: []const u8) ?*Unit {
+ for (s.units.items) |*unit| if (unit.path.len > 0 and std.mem.eql(u8, unit.path, object)) return unit;
+ return null;
+ }
+ /// Drops rows that are neither loaded nor backed by a unit file. Rows move,
+ /// so never while a request holds a row's index (loading or analyzing).
+ fn prune(s: *Snapshot) void {
+ var kept: usize = 0;
+ for (s.units.items) |unit| {
+ if (unit.path.len == 0 and std.mem.eql(u8, unit.startup, "unknown")) continue;
+ s.units.items[kept] = unit;
+ kept += 1;
+ }
+ if (kept == s.units.items.len) return;
+ s.units.items.len = kept;
+ s.index.clearRetainingCapacity();
+ for (s.units.items, 0..) |unit, i| s.index.putAssumeCapacity(unit.name, i);
+ }
};
+/// A unit that is not loaded: what ListUnitFiles alone says about it.
+fn markUnloaded(unit: *Unit) void {
+ unit.path = "";
+ unit.description = "Not loaded";
+ unit.load = "unloaded";
+ unit.active = "inactive";
+ unit.sub = "dead";
+ unit.service_type = "";
+ unit.trigger = "";
+ unit.transient = false;
+ unit.has_details = false;
+}
+
+/// One readable property of a loaded unit, with where it lives on the bus.
+const Prop = enum {
+ description,
+ active,
+ sub,
+ load,
+ transient,
+ trigger,
+ service_type,
+
+ fn interface(p: Prop) []const u8 {
+ return if (p == .service_type) name ++ ".Service" else name ++ ".Unit";
+ }
+ fn key(p: Prop) []const u8 {
+ return switch (p) {
+ .description => "Description",
+ .active => "ActiveState",
+ .sub => "SubState",
+ .load => "LoadState",
+ .transient => "Transient",
+ .trigger => "TriggeredBy",
+ .service_type => "Type",
+ };
+ }
+ fn signature(p: Prop) []const u8 {
+ return switch (p) {
+ .transient => "b",
+ .trigger => "as",
+ else => "s",
+ };
+ }
+ fn of(on: []const u8, member: []const u8) ?Prop {
+ for (std.enums.values(Prop)) |p| {
+ if (std.mem.eql(u8, p.interface(), on) and std.mem.eql(u8, p.key(), member)) return p;
+ }
+ return null;
+ }
+};
+/// What the table shows that ListUnits does not say.
+const detail_props = [_]Prop{ .transient, .trigger, .service_type };
+
+/// Sets `prop` from the value `r` is positioned at (signature `sig`), reporting
+/// whether the row changed.
+fn apply(s: *Snapshot, unit: *Unit, prop: Prop, sig: []const u8, r: *wire.Reader) !bool {
+ if (!std.mem.eql(u8, sig, prop.signature())) {
+ try r.skip(sig);
+ return false;
+ }
+ switch (prop) {
+ .transient => {
+ const value = try r.boolean();
+ const differs = unit.transient != value;
+ unit.transient = value;
+ return differs;
+ },
+ .trigger => {
+ var items = try r.array(4);
+ var joined: std.ArrayList(u8) = .empty;
+ const a = s.arena.allocator();
+ while (items.offset < items.bytes.len) {
+ const trigger = try items.string();
+ if (joined.items.len > 0) try joined.appendSlice(a, ", ");
+ try joined.appendSlice(a, trigger);
+ }
+ if (std.mem.eql(u8, unit.trigger, joined.items)) return false;
+ s.copied += joined.items.len;
+ unit.trigger = joined.items;
+ return true;
+ },
+ else => {
+ const value = try r.string();
+ const field: *[]const u8 = switch (prop) {
+ .description => &unit.description,
+ .active => &unit.active,
+ .sub => &unit.sub,
+ .load => &unit.load,
+ else => &unit.service_type,
+ };
+ if (std.mem.eql(u8, field.*, value)) return false;
+ field.* = try s.copy(value);
+ return true;
+ },
+ }
+}
+
pub const Action = enum { enable, disable, start, stop, restart };
-const Kind = enum { subscribe, units, files, pin, load, detail, service, timing, boot, action, reload, unlock };
-const Request = struct { client: *Client, generation: u64, kind: Kind, index: usize = 0 };
+const Kind = enum { subscribe, units, files, detail, timing, boot, action, reload, unlock };
+const Request = struct {
+ client: *Client,
+ generation: u64,
+ kind: Kind,
+ index: usize = 0,
+ prop: Prop = .transient,
+};
pub const Client = struct {
server: *@import("Server.zig"),
@@ -88,11 +266,24 @@ pub const Client = struct {
owner: ?[]u8 = null,
generation: u64 = 0,
closing: bool = false,
+ /// The Services page is on screen.
+ visible: bool = false,
+ /// An IPC query asked recently; `lease_timer` ends it.
+ leased: bool = false,
+ lease_timer: ?*wl.EventSource = null,
+ /// Signals reported changes only a new list can describe; `settle_timer` runs it.
+ dirty: bool = false,
+ settle_timer: ?*wl.EventSource = null,
+ /// Matches added and Subscribe sent: exactly while visible or leased.
watching: bool = false,
subscribed: bool = false,
snapshot: Snapshot = .{},
staging: Snapshot = .{},
loading: bool = false,
+ /// ListUnits has been merged into `staging`: it is the freshest data there is.
+ staging_listed: bool = false,
+ /// A full load re-reads every loaded unit's details, not only new ones.
+ force_details: bool = false,
analyzing: bool = false,
analyzed: bool = false,
boot_pending: bool = false,
@@ -104,8 +295,11 @@ pub const Client = struct {
edited_unit: ?[]u8 = null,
edited_type: ?usize = null,
action_job: ?[]u8 = null,
+ /// Something changed while a load or analysis was running.
again: bool = false,
+ again_force: bool = false,
next_detail: usize = 0,
+ next_step: usize = 0,
pending_details: usize = 0,
boot_us: ?u64 = null,
message: [256]u8 = undefined,
@@ -126,6 +320,8 @@ pub const Client = struct {
self.closing = true;
edit.cancel(self);
self.cancelUnlock();
+ if (self.lease_timer) |timer| timer.remove();
+ if (self.settle_timer) |timer| timer.remove();
if (self.edited_unit) |unit| gpa.free(unit);
if (self.conn) |conn| conn.destroy();
if (self.owner) |old| gpa.free(old);
@@ -158,24 +354,94 @@ pub const Client = struct {
if (cc.page == .services) cc.refresh();
};
}
- pub fn open(self: *Client) void {
- if (self.watching or !self.available()) return;
+ /// The Services page is on screen: go live. Idempotent; the page calls it
+ /// on every build.
+ pub fn show(self: *Client) void {
+ self.visible = true;
+ self.sync();
+ }
+ /// The page was left or Settings closed.
+ pub fn hide(self: *Client) void {
+ self.visible = false;
+ self.sync();
+ }
+ /// An IPC reader is not a page: keep the list live for a while after each
+ /// query, then let it go.
+ pub fn lease(self: *Client) void {
+ if (self.lease_timer == null) {
+ self.lease_timer = self.server.wl_server.getEventLoop().addTimer(*Client, leaseExpired, self) catch return;
+ }
+ self.lease_timer.?.timerUpdate(lease_ms) catch return;
+ self.leased = true;
+ self.sync();
+ }
+ fn leaseExpired(self: *Client) c_int {
+ self.leased = false;
+ self.sync();
+ return 0;
+ }
+ /// Live exactly while a page or a lease wants the data. Going live waits for
+ /// systemd to be found; `setOwner` calls this again then.
+ fn sync(self: *Client) void {
+ const wanted = (self.visible or self.leased) and !self.closing;
+ if (wanted == self.watching) return;
+ if (wanted) {
+ if (self.available()) self.startWatching();
+ } else self.stopWatching();
+ }
+ fn startWatching(self: *Client) void {
+ const conn = self.conn orelse return;
self.watching = true;
+ _ = conn.addMatch(manager_match, null, null) catch {
+ self.inform("Could not subscribe to service updates.");
+ return;
+ };
+ _ = conn.addMatch(properties_match, null, null) catch {
+ self.inform("Could not subscribe to service updates.");
+ return;
+ };
self.subscribe() catch self.inform("Could not subscribe to service updates.");
}
+ fn stopWatching(self: *Client) void {
+ self.watching = false;
+ if (self.conn) |conn| {
+ _ = conn.removeMatch(manager_match, null, null) catch {};
+ _ = conn.removeMatch(properties_match, null, null) catch {};
+ // Whether or not the Subscribe reply landed: systemd keeps a subscriber
+ // until it unsubscribes or disconnects, and a second Subscribe is an error.
+ if (self.owner) |owner| {
+ const body: wire.Writer = .{ .allocator = gpa };
+ _ = conn.call(owner, path, manager, "Unsubscribe", "", &body, null, null, 5000) catch {};
+ }
+ }
+ self.resetState();
+ }
fn subscribe(self: *Client) !void {
const body: wire.Writer = .{ .allocator = gpa };
try self.call(.subscribe, 0, path, manager, "Subscribe", "", &body, false);
}
+ /// Re-reads everything, details included: the user asked, or systemd reloaded.
pub fn refresh(self: *Client) void {
+ self.reload(true);
+ }
+ /// Lists units and unit files again; details are only read for loaded units
+ /// that have none yet, unless `force`.
+ fn reload(self: *Client, force: bool) void {
if (!self.available() or !self.subscribed) return;
if (self.busy()) {
self.again = true;
+ self.again_force = self.again_force or force;
return;
}
self.again = false;
+ self.again_force = false;
self.loading = true;
+ self.force_details = force;
self.staging.deinit();
+ self.staging_listed = false;
+ self.next_detail = 0;
+ self.next_step = 0;
+ self.pending_details = 0;
const body: wire.Writer = .{ .allocator = gpa };
self.call(.units, 0, path, manager, "ListUnits", "", &body, false) catch {
self.loading = false;
@@ -193,22 +459,25 @@ pub const Client = struct {
self.pending_details = 0;
for (self.snapshot.units.items) |*unit| unit.time_us = null;
self.boot_pending = true;
- self.getProperties(.boot, 0, path, manager) catch {
+ self.getAll(.boot, 0, path, manager) catch {
self.boot_pending = false;
self.inform("Boot summary is unavailable.");
};
- self.pump();
+ self.pumpTiming();
self.changed();
}
pub fn detachSettings(self: *Client) void {
self.cancelUnlock();
self.lock();
- if (self.edit_request != null) {
+ const editing = self.edit_request != null;
+ if (editing) {
edit.cancel(self);
self.action_pending = false;
self.edited_type = null;
- self.refresh();
}
+ self.visible = false;
+ self.sync();
+ if (editing and self.watching) self.reload(false);
}
pub fn lock(self: *Client) void {
if (!self.unlocked) return;
@@ -280,6 +549,7 @@ pub const Client = struct {
pub fn setMode(self: *Client, unit_name: []const u8, mode: @import("ipc/protocol.zig").ServiceMode) !void {
if (mode == .deferred) return error.UnsupportedServiceMode;
if (!self.available()) return error.ServicesUnavailable;
+ self.lease();
if (self.busy() or self.awaitingList()) return error.ServicesBusy;
const i = self.snapshot.index.get(unit_name) orelse return error.UnknownService;
const unit = self.snapshot.units.items[i];
@@ -340,7 +610,7 @@ pub const Client = struct {
"Authentication was cancelled or denied. Notify setting is unchanged."
else
"Could not save Notify. Service editing requires systemd 256 or newer.");
- self.refresh();
+ self.reload(false);
return;
}
const empty: wire.Writer = .{ .allocator = gpa };
@@ -352,58 +622,87 @@ pub const Client = struct {
self.changed();
}
fn call(self: *Client, kind: Kind, index: usize, object: []const u8, interface: []const u8, method: []const u8, signature: []const u8, body: *const wire.Writer, auth: bool) !void {
+ return self.send(.{ .client = self, .generation = self.generation, .kind = kind, .index = index }, object, interface, method, signature, body, auth);
+ }
+ fn send(self: *Client, template: Request, object: []const u8, interface: []const u8, method: []const u8, signature: []const u8, body: *const wire.Writer, auth: bool) !void {
const destination = self.owner orelse return error.Disconnected;
const req = try gpa.create(Request);
errdefer gpa.destroy(req);
- req.* = .{ .client = self, .generation = self.generation, .kind = kind, .index = index };
+ req.* = template;
_ = try self.conn.?.callWithFlags(destination, object, interface, method, signature, body, req, reply, if (auth) 120000 else 10000, if (auth) wire.flag_allow_interactive_authorization else 0);
}
- fn getProperties(self: *Client, kind: Kind, index: usize, object: []const u8, interface: []const u8) !void {
+ fn getAll(self: *Client, kind: Kind, index: usize, object: []const u8, interface: []const u8) !void {
var body: wire.Writer = .{ .allocator = gpa };
defer body.deinit();
try body.string(interface);
try self.call(kind, index, object, properties, "GetAll", "s", &body, false);
}
+ /// One property of the loaded unit at `index` of `staging`.
+ fn getDetail(self: *Client, index: usize, object: []const u8, prop: Prop) !void {
+ var body: wire.Writer = .{ .allocator = gpa };
+ defer body.deinit();
+ try body.string(prop.interface());
+ try body.string(prop.key());
+ try self.send(.{ .client = self, .generation = self.generation, .kind = .detail, .index = index, .prop = prop }, object, properties, "Get", "ss", &body, false);
+ }
+ /// Reads the details of the next loaded units still lacking them, a few at a
+ /// time, and swaps the finished list in. Unloaded units are skipped: nothing
+ /// is asked of a unit systemd has not loaded.
fn pump(self: *Client) void {
- const units = if (self.analyzing) self.snapshot.units.items else self.staging.units.items;
+ const units = self.staging.units.items;
+ while (self.pending_details < max_in_flight and self.next_detail < units.len) {
+ const i = self.next_detail;
+ const unit = &units[i];
+ if (self.next_step == 0 and (unit.path.len == 0 or unit.has_details)) {
+ self.next_detail += 1;
+ continue;
+ }
+ const prop = detail_props[self.next_step];
+ self.next_step += 1;
+ if (self.next_step == detail_props.len) {
+ self.next_step = 0;
+ self.next_detail += 1;
+ }
+ unit.has_details = true;
+ self.getDetail(i, unit.path, prop) catch continue;
+ self.pending_details += 1;
+ }
+ if (self.pending_details != 0) return;
+ for (self.staging.units.items) |*unit| {
+ if (self.snapshot.index.get(unit.name)) |i| unit.time_us = self.snapshot.units.items[i].time_us;
+ }
+ self.snapshot.deinit();
+ self.snapshot = self.staging;
+ self.staging = .{};
+ self.staging_listed = false;
+ self.loading = false;
+ // Units that unloaded during the load and have no file are done with.
+ self.snapshot.prune();
+ if (self.edited_type) |expected| {
+ self.edited_type = null;
+ const i = self.snapshot.index.get(self.edited_unit.?);
+ if (i == null or !std.mem.eql(u8, self.snapshot.units.items[i.?].service_type, service_types[expected]))
+ self.inform("Notify override saved, but the selected type is not active in systemd. Check other service overrides.");
+ }
+ self.changed();
+ if (self.again) self.reload(self.again_force);
+ }
+ /// Startup times for the loaded units, on request.
+ fn pumpTiming(self: *Client) void {
+ const units = self.snapshot.units.items;
while (self.pending_details < 4 and self.next_detail < units.len) {
const i = self.next_detail;
self.next_detail += 1;
- if (units[i].path.len == 0) {
- if (self.analyzing or std.mem.startsWith(u8, units[i].startup, "masked")) continue;
- var body: wire.Writer = .{ .allocator = gpa };
- defer body.deinit();
- body.string(units[i].name) catch continue;
- // Keep newly loaded inactive units alive while Settings uses
- // them. The bus disconnect drops these references, preventing
- // UnitNew/UnitRemoved from causing a refresh/GC feedback loop.
- self.call(.pin, i, path, manager, "RefUnit", "s", &body, false) catch continue;
- } else {
- self.getProperties(if (self.analyzing) .timing else .detail, i, units[i].path, name ++ ".Unit") catch continue;
- }
+ if (units[i].path.len == 0) continue;
+ self.getAll(.timing, i, units[i].path, name ++ ".Unit") catch continue;
self.pending_details += 1;
}
if (self.pending_details != 0 or self.boot_pending) return;
- if (self.analyzing) {
- self.analyzing = false;
- self.analyzed = true;
- } else {
- for (self.staging.units.items) |*unit| {
- if (self.snapshot.index.get(unit.name)) |i| unit.time_us = self.snapshot.units.items[i].time_us;
- }
- self.snapshot.deinit();
- self.snapshot = self.staging;
- self.staging = .{};
- self.loading = false;
- if (self.edited_type) |expected| {
- self.edited_type = null;
- const i = self.snapshot.index.get(self.edited_unit.?);
- if (i == null or !std.mem.eql(u8, self.snapshot.units.items[i.?].service_type, service_types[expected]))
- self.inform("Notify override saved, but the selected type is not active in systemd. Check other service overrides.");
- }
- }
+ self.analyzing = false;
+ self.analyzed = true;
+ self.snapshot.prune();
self.changed();
- if (self.again) self.refresh();
+ if (self.again) self.reload(self.again_force);
}
fn reply(ctx: ?*anyopaque, _: *dbus.Connection, result: dbus.Connection.Failure!wire.Message) void {
const req: *Request = @ptrCast(@alignCast(ctx orelse return));
@@ -415,7 +714,13 @@ pub const Client = struct {
return;
};
if (msg.kind == .error_reply) {
- self.failed(req, msg.headers.error_name orelse "Service request failed.");
+ const error_name = msg.headers.error_name orelse "Service request failed.";
+ // Left over from an earlier visit that never unsubscribed: still subscribed.
+ if (req.kind == .subscribe and std.mem.eql(u8, error_name, name ++ ".AlreadySubscribed")) {
+ self.accept(req, msg) catch {};
+ return;
+ }
+ self.failed(req, error_name);
return;
}
// polkit answers the unlock check; everything else must be systemd.
@@ -428,15 +733,20 @@ pub const Client = struct {
self.unlocking = false;
self.inform("Could not request authentication. Check that polkit is running.");
},
- .pin, .load, .detail, .service, .timing => {
+ .detail => {
+ // Not every loaded unit has every property (a masked service has no Type).
self.pending_details -= 1;
- if (req.kind == .timing) self.inform("Some startup times are unavailable.");
self.pump();
},
+ .timing => {
+ self.pending_details -= 1;
+ self.inform("Some startup times are unavailable.");
+ self.pumpTiming();
+ },
.boot => {
self.boot_pending = false;
self.inform("Boot summary is unavailable.");
- self.pump();
+ self.pumpTiming();
},
.action, .reload => {
self.action_pending = false;
@@ -444,7 +754,7 @@ pub const Client = struct {
self.edited_type = null;
self.inform("Notify override saved, but systemd could not reload it. Try Refresh after a daemon reload.");
} else self.inform(reason);
- self.refresh();
+ self.reload(false);
},
else => {
self.loading = false;
@@ -457,7 +767,7 @@ pub const Client = struct {
switch (req.kind) {
.subscribe => {
self.subscribed = true;
- self.refresh();
+ self.reload(true);
},
.units => {
if (!std.mem.eql(u8, msg.headers.signature, "a(ssssssouso)")) return error.InvalidMessage;
@@ -482,37 +792,38 @@ pub const Client = struct {
unit.sub = try self.staging.copy(sub);
unit.path = try self.staging.copy(object);
}
+ self.staging_listed = true;
const empty: wire.Writer = .{ .allocator = gpa };
try self.call(.files, 0, path, manager, "ListUnitFiles", "", &empty, false);
},
.files => {
if (!std.mem.eql(u8, msg.headers.signature, "a(ss)")) return error.InvalidMessage;
- var array = try body.array(8);
- while (array.offset < array.bytes.len) {
- try array.alignTo(8);
- const id = std.fs.path.basename(try array.string());
- const state = try array.string();
- if (!std.mem.endsWith(u8, id, ".service")) continue;
- const unit = try self.staging.get(id);
- unit.startup = try self.staging.copy(state);
- }
+ try mergeFiles(&self.staging, &body);
+ // What the last list learned about a still-loaded unit stands
+ // until systemd reloads or the user refreshes.
+ if (!self.force_details) for (self.staging.units.items) |*unit| {
+ const i = self.snapshot.index.get(unit.name) orelse continue;
+ const old = self.snapshot.units.items[i];
+ if (!old.has_details or unit.path.len == 0 or !std.mem.eql(u8, old.path, unit.path)) continue;
+ unit.service_type = try self.staging.copy(old.service_type);
+ unit.trigger = try self.staging.copy(old.trigger);
+ unit.transient = old.transient;
+ unit.has_details = true;
+ };
self.next_detail = 0;
+ self.next_step = 0;
self.pending_details = 0;
self.pump();
},
- .pin => {
- var request: wire.Writer = .{ .allocator = gpa };
- defer request.deinit();
- try request.string(self.staging.units.items[req.index].name);
- try self.call(.load, req.index, path, manager, "LoadUnit", "s", &request, false);
- },
- .load => {
- if (!std.mem.eql(u8, msg.headers.signature, "o")) return error.InvalidMessage;
- const unit = &self.staging.units.items[req.index];
- unit.path = try self.staging.copy(try body.string());
- try self.getProperties(.detail, req.index, unit.path, name ++ ".Unit");
+ .detail => {
+ if (!std.mem.eql(u8, msg.headers.signature, "v")) return error.InvalidMessage;
+ const sig = try body.variant();
+ if (req.index < self.staging.units.items.len)
+ _ = try apply(&self.staging, &self.staging.units.items[req.index], req.prop, sig, &body);
+ self.pending_details -= 1;
+ self.pump();
},
- .detail, .service, .timing, .boot => {
+ .timing, .boot => {
if (!std.mem.eql(u8, msg.headers.signature, "a{sv}")) return error.InvalidMessage;
var entries = try body.array(8);
var start: u64 = 0;
@@ -526,40 +837,16 @@ pub const Client = struct {
if (std.mem.eql(u8, key, "InactiveExitTimestampMonotonic")) start = value;
if (std.mem.eql(u8, key, "ActiveEnterTimestampMonotonic")) end = value;
if (req.kind == .boot and std.mem.eql(u8, key, "FinishTimestampMonotonic")) self.boot_us = if (value > 0) value else null;
- } else if (req.kind == .service and std.mem.eql(u8, key, "Type") and std.mem.eql(u8, sig, "s")) {
- self.staging.units.items[req.index].service_type = try self.staging.copy(try entries.string());
- } else if (req.kind == .detail and std.mem.eql(u8, key, "LoadState") and std.mem.eql(u8, sig, "s")) {
- self.staging.units.items[req.index].load = try self.staging.copy(try entries.string());
- } else if (req.kind == .detail and std.mem.eql(u8, key, "Transient") and std.mem.eql(u8, sig, "b")) {
- self.staging.units.items[req.index].transient = try entries.boolean();
- } else if (req.kind == .detail and std.mem.eql(u8, sig, "s")) {
- const value = try self.staging.copy(try entries.string());
- const unit = &self.staging.units.items[req.index];
- if (std.mem.eql(u8, key, "Description")) unit.description = value;
- if (std.mem.eql(u8, key, "ActiveState")) unit.active = value;
- if (std.mem.eql(u8, key, "SubState")) unit.sub = value;
- } else if (req.kind == .detail and std.mem.eql(u8, key, "TriggeredBy") and std.mem.eql(u8, sig, "as")) {
- var triggers = try entries.array(4);
- var value: std.ArrayList(u8) = .empty;
- const a = self.staging.arena.allocator();
- while (triggers.offset < triggers.bytes.len) {
- const trigger = try triggers.string();
- if (value.items.len > 0) try value.appendSlice(a, ", ");
- try value.appendSlice(a, trigger);
- }
- self.staging.units.items[req.index].trigger = value.items;
} else try entries.skip(sig);
}
if (req.kind == .boot) {
self.boot_pending = false;
- self.pump();
- } else if (req.kind == .detail) {
- try self.getProperties(.service, req.index, self.staging.units.items[req.index].path, name ++ ".Service");
} else {
- if (req.kind == .timing) self.snapshot.units.items[req.index].time_us = if (start > 0 and end > start) end - start else null;
+ if (req.index < self.snapshot.units.items.len)
+ self.snapshot.units.items[req.index].time_us = if (start > 0 and end > start) end - start else null;
self.pending_details -= 1;
- self.pump();
}
+ self.pumpTiming();
},
.action => {
if (req.index == 1) {
@@ -570,8 +857,8 @@ pub const Client = struct {
self.action_job = null;
self.action_job = try gpa.dupe(u8, try body.string());
self.action_pending = false;
+ // The unit's new state arrives as a signal.
self.inform("Request accepted. Status updates when the job completes.");
- self.refresh();
}
},
.unlock => {
@@ -586,36 +873,50 @@ pub const Client = struct {
.reload => {
self.action_pending = false;
self.inform(if (req.index == 1) "Notify setting saved. Applies on the next service start." else "Startup setting saved. Running status is unchanged.");
- self.refresh();
+ self.reload(true);
},
}
}
fn fromOwner(self: *Client, msg: wire.Message) bool {
return std.mem.eql(u8, self.owner orelse return false, msg.headers.sender orelse return false);
}
- fn setOwner(self: *Client, unique: []const u8) void {
+ /// Forgets everything read from systemd and everything still on its way.
+ fn resetState(self: *Client) void {
+ self.dirty = false;
+ if (self.settle_timer) |timer| timer.timerUpdate(0) catch {};
edit.cancel(self);
- self.cancelUnlock();
self.edited_type = null;
if (self.edited_unit) |unit| gpa.free(unit);
self.edited_unit = null;
self.generation += 1;
if (self.action_job) |job| gpa.free(job);
self.action_job = null;
- if (self.owner) |old| gpa.free(old);
- self.owner = if (unique.len > 0) gpa.dupe(u8, unique) catch null else null;
self.snapshot.deinit();
self.staging.deinit();
self.loading = false;
+ self.staging_listed = false;
self.analyzing = false;
self.analyzed = false;
self.boot_pending = false;
self.action_pending = false;
self.subscribed = false;
+ self.again = false;
+ self.again_force = false;
+ self.next_detail = 0;
+ self.next_step = 0;
self.pending_details = 0;
self.boot_us = null;
self.message_len = 0;
- if (self.available() and self.watching) self.subscribe() catch {};
+ }
+ fn setOwner(self: *Client, unique: []const u8) void {
+ self.cancelUnlock();
+ self.resetState();
+ if (self.owner) |old| gpa.free(old);
+ self.owner = if (unique.len > 0) gpa.dupe(u8, unique) catch null else null;
+ // A new daemon has no subscribers: ask again if anything still wants it.
+ if (self.available() and self.watching) {
+ self.subscribe() catch {};
+ } else self.sync();
if (!self.closing) if (self.server.input.open_control_center) |cc| {
cc.refresh();
};
@@ -633,9 +934,8 @@ pub const Client = struct {
}
fn setup(self: *Client, conn: *dbus.Connection) !void {
try conn.registerSignal(.{ .owner = self, .callback = signal });
+ // Only the owner of the name is tracked until the page asks for more.
_ = try conn.addMatch("type='signal',sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',member='NameOwnerChanged',arg0='" ++ name ++ "'", null, null);
- _ = try conn.addMatch("type='signal',sender='" ++ name ++ "',interface='" ++ manager ++ "'", null, null);
- _ = try conn.addMatch("type='signal',sender='" ++ name ++ "',interface='" ++ properties ++ "',path_namespace='" ++ path ++ "/unit'", null, null);
var body: wire.Writer = .{ .allocator = gpa };
defer body.deinit();
try body.string(name);
@@ -663,10 +963,8 @@ pub const Client = struct {
// Type is a constant property until daemon reload; systemd
// does not have to emit Service.PropertiesChanged for it.
if (std.mem.eql(u8, member, "Reloading")) {
- if (!try body.boolean()) self.refresh();
- return;
- }
- if (std.mem.eql(u8, member, "JobRemoved")) {
+ if (!try body.boolean()) self.reload(true);
+ } else if (std.mem.eql(u8, member, "JobRemoved")) {
_ = try body.uint32();
const job = try body.string();
_ = try body.string();
@@ -678,12 +976,93 @@ pub const Client = struct {
self.action_job = null;
}
}
+ } else if (std.mem.eql(u8, member, "UnitNew")) {
+ // Mounts, targets and the rest are not rows; only a service is news.
+ if (std.mem.endsWith(u8, try body.string(), ".service")) self.markDirty();
+ } else if (std.mem.eql(u8, member, "UnitRemoved")) {
+ self.unitRemoved(try body.string());
+ } else if (std.mem.eql(u8, member, "UnitFilesChanged")) {
+ self.markDirty();
}
- if (std.mem.eql(u8, member, "UnitNew") or std.mem.eql(u8, member, "UnitRemoved") or std.mem.eql(u8, member, "UnitFilesChanged") or std.mem.eql(u8, member, "JobRemoved")) self.refresh();
} else if (std.mem.eql(u8, interface, properties) and std.mem.eql(u8, member, "PropertiesChanged")) {
- const changed_interface = try body.string();
- if (std.mem.eql(u8, changed_interface, name ++ ".Unit") or std.mem.eql(u8, changed_interface, name ++ ".Service")) self.refresh();
+ try self.propertiesChanged(msg.headers.path orelse return, &body);
}
}
}
+ // Live updates go to the freshest data there is: the half-built list once
+ // ListUnits is in it, else the current one. They never restart a load, and
+ // none of them makes a call: see `markDirty`.
+ fn fresh(self: *Client) *Snapshot {
+ return if (self.loading and self.staging_listed) &self.staging else &self.snapshot;
+ }
+ /// Something changed that a signal cannot describe. Read the list again after
+ /// a settling time, once however many signals ask.
+ fn markDirty(self: *Client) void {
+ if (self.dirty) return;
+ if (self.settle_timer == null) {
+ self.settle_timer = self.server.wl_server.getEventLoop().addTimer(*Client, settled, self) catch return;
+ }
+ self.settle_timer.?.timerUpdate(settle_ms) catch return;
+ self.dirty = true;
+ }
+ fn settled(self: *Client) c_int {
+ self.dirty = false;
+ self.reload(false);
+ return 0;
+ }
+ fn unitRemoved(self: *Client, id: []const u8) void {
+ if (!std.mem.endsWith(u8, id, ".service")) return;
+ const snap = self.fresh();
+ const i = snap.index.get(id) orelse return;
+ markUnloaded(&snap.units.items[i]);
+ // Rows move when pruned: not in a half-built list, not while timing.
+ if (snap == &self.snapshot and !self.analyzing) snap.prune();
+ self.changed();
+ }
+ fn propertiesChanged(self: *Client, object: []const u8, body: *wire.Reader) !void {
+ if (!std.mem.startsWith(u8, object, path ++ "/unit/")) return;
+ const on = try body.string();
+ // Only an interface the table reads is worth a look.
+ if (!std.mem.eql(u8, on, name ++ ".Unit") and !std.mem.eql(u8, on, name ++ ".Service")) return;
+ const snap = self.fresh();
+ const unit = snap.at(object) orelse return;
+ var touched = false;
+ var delivered: std.EnumSet(Prop) = .initEmpty();
+ var values = try body.array(8);
+ while (values.offset < values.bytes.len) {
+ try values.alignTo(8);
+ const member = try values.string();
+ const sig = try values.variant();
+ if (Prop.of(on, member)) |prop| {
+ delivered.insert(prop);
+ if (try apply(snap, unit, prop, sig, &values)) touched = true;
+ } else try values.skip(sig);
+ }
+ // systemd lists properties like Description as invalidated on ordinary
+ // changes. Only a name the table shows live that did not arrive with its
+ // value needs another look.
+ var stale = try body.array(4);
+ while (stale.offset < stale.bytes.len) {
+ const prop = Prop.of(on, try stale.string()) orelse continue;
+ if (delivered.contains(prop) or !(prop == .active or prop == .sub or prop == .service_type)) continue;
+ // A new Type is part of the details, which are only read once.
+ if (prop == .service_type) unit.has_details = false;
+ self.markDirty();
+ }
+ if (touched) self.changed();
+ if (self.snapshot.copied > copied_limit) self.reload(false);
+ }
};
+
+/// Applies ListUnitFiles to `snap`: every service file gets its startup state.
+fn mergeFiles(snap: *Snapshot, body: *wire.Reader) !void {
+ var array = try body.array(8);
+ while (array.offset < array.bytes.len) {
+ try array.alignTo(8);
+ const id = std.fs.path.basename(try array.string());
+ const state = try array.string();
+ if (!std.mem.endsWith(u8, id, ".service")) continue;
+ const unit = try snap.get(id);
+ unit.startup = try snap.copy(state);
+ }
+}
diff --git a/tests/control_center.py b/tests/control_center.py
index 3e11c12..cf079b0 100644
--- a/tests/control_center.py
+++ b/tests/control_center.py
@@ -426,7 +426,7 @@ UNIT = NAME + ".Unit"
SERVICE = NAME + ".Service"
conn = Gio.bus_get_sync(Gio.BusType.SESSION)
xml = """<node><interface name='org.freedesktop.systemd1.Manager'>
-<method name='Subscribe'/><method name='Reload'/>
+<method name='Subscribe'/><method name='Unsubscribe'/><method name='Reload'/>
<method name='LoadUnit'><arg type='s' direction='in'/><arg type='o' direction='out'/></method>
<method name='RefUnit'><arg type='s' direction='in'/></method>
<method name='ListUnits'><arg type='a(ssssssouso)' direction='out'/></method>
@@ -445,6 +445,10 @@ unit_xml = """<node><interface name='org.freedesktop.systemd1.Unit'>
<property name='ActiveEnterTimestampMonotonic' type='t' access='read'/>
<property name='TriggeredBy' type='as' access='read'/>
<property name='LoadState' type='s' access='read'/>
+<property name='Description' type='s' access='read'/>
+<property name='ActiveState' type='s' access='read'/>
+<property name='SubState' type='s' access='read'/>
+<property name='Transient' type='b' access='read'/>
</interface></node>"""
service_xml = """<node><interface name='org.freedesktop.systemd1.Service'>
<property name='Type' type='s' access='read'/>
@@ -469,23 +473,39 @@ types.update({'alpha.service': 'notify', 'beta.service': 'exec', 'slow.service':
types.update({'worker-00.service': 'idle', 'worker-01.service': 'notify-reload'})
log = open(os.environ['SYSTEMD_TEST_LOG'], 'a', buffering=1)
delay_next = False
+subscribed = False
+no_file = set()
+unloaded = set()
def record(method, args=None, flags=0):
log.write(json.dumps({'method': method, 'args': args, 'flags': flags}) + '\n')
+# Signals go out whether or not anyone subscribed: a client that is not meant to
+# be listening has to have dropped its own matches.
def emit(member, signature='()', values=()):
conn.emit_signal(None, PATH, IFACE, member, GLib.Variant(signature, values))
+def changed(key, **values):
+ conn.emit_signal(None, paths[key], 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (UNIT, {k: GLib.Variant('s', v) for k, v in values.items()}, [])))
def method(c, sender, object_path, iface, member, params, invocation):
- global delay_next
+ global delay_next, subscribed
args = params.unpack()
record(member, args, int(invocation.get_message().get_flags()))
- if member == 'ListUnits':
- rows = [(key, v[0], 'loaded', v[1], v[2], '', paths[key], 0, '', '/') for key,v in units.items()]
+ if member == 'Subscribe':
+ if subscribed:
+ invocation.return_dbus_error('org.freedesktop.systemd1.AlreadySubscribed', 'Client is already subscribed.')
+ else:
+ subscribed = True
+ invocation.return_value(GLib.Variant('()', ()))
+ elif member == 'Unsubscribe':
+ subscribed = False
+ invocation.return_value(GLib.Variant('()', ()))
+ elif member == 'ListUnits':
+ rows = [(key, v[0], 'loaded', v[1], v[2], '', paths[key], 0, '', '/') for key,v in units.items() if key not in unloaded]
if delay_next:
delay_next = False
GLib.timeout_add(1000, lambda: (invocation.return_value(GLib.Variant('(a(ssssssouso))', (rows,))), False)[1])
else:
invocation.return_value(GLib.Variant('(a(ssssssouso))', (rows,)))
elif member == 'ListUnitFiles':
- rows = [('/usr/lib/systemd/system/' + key, v[3]) for key,v in units.items()]
+ rows = [('/usr/lib/systemd/system/' + key, v[3]) for key,v in units.items() if key not in no_file]
rows.append(('/usr/lib/systemd/system/unloaded.service', 'disabled'))
invocation.return_value(GLib.Variant('(a(ss))', (rows,)))
elif member == 'LoadUnit':
@@ -508,6 +528,7 @@ def method(c, sender, object_path, iface, member, params, invocation):
units[key][1:3] = ['inactive', 'dead'] if member == 'StopUnit' else ['active', 'running']
job = PATH + '/job/1'
invocation.return_value(GLib.Variant('(o)', (job,)))
+ changed(key, ActiveState=units[key][1], SubState=units[key][2])
GLib.timeout_add(30, lambda: (emit('JobRemoved', '(uoss)', (1, job, key, 'done')), False)[1])
else:
invocation.return_value(GLib.Variant('()', ()))
@@ -528,19 +549,26 @@ def authority(c, sender, object_path, iface, member, params, invocation):
pending_check = None
invocation.return_value(GLib.Variant('()', ()))
def prop(c, sender, object_path, iface, key):
- record('Property:' + key)
+ record('Property:' + key, object_path)
if key == 'FinishTimestampMonotonic': return GLib.Variant('t', 3500000)
unit = next(k for k,v in paths.items() if v == object_path)
if key == 'Type': return GLib.Variant('s', types[unit])
if key == 'LoadState': return GLib.Variant('s', 'loaded')
+ if key == 'Transient': return GLib.Variant('b', False)
+ row = units.get(unit, ['Not loaded', 'inactive', 'dead', 'disabled', 0])
+ if key == 'Description': return GLib.Variant('s', row[0])
+ if key == 'ActiveState': return GLib.Variant('s', row[1])
+ if key == 'SubState': return GLib.Variant('s', row[2])
if key == 'TriggeredBy': return GLib.Variant('as', ['alpha.socket'] if unit == 'alpha.service' else [])
duration = units[unit][4] if unit in units else 0
return GLib.Variant('t', 1000000 if key.startswith('Inactive') else 1000000 + duration)
conn.register_object('/org/freedesktop/PolicyKit1/Authority', Gio.DBusNodeInfo.new_for_xml(polkit_xml).interfaces[0], authority, None, None)
conn.register_object(PATH, Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], method, prop, None)
-for object_path in paths.values():
+def register(object_path):
conn.register_object(object_path, Gio.DBusNodeInfo.new_for_xml(unit_xml).interfaces[0], None, prop, None)
conn.register_object(object_path, Gio.DBusNodeInfo.new_for_xml(service_xml).interfaces[0], None, prop, None)
+for object_path in paths.values():
+ register(object_path)
def stdin_ready(*_):
global delay_next
cmd = sys.stdin.readline().strip()
@@ -548,8 +576,33 @@ def stdin_ready(*_):
delay_next = True
record('delay_ready')
elif cmd == 'change':
+ # Names only, as systemd does for properties it does not push the value of.
units['alpha.service'][1:3] = ['failed', 'failed']
- conn.emit_signal(None, paths['alpha.service'], 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (UNIT, {}, ['ActiveState'])))
+ conn.emit_signal(None, paths['alpha.service'], 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (UNIT, {}, ['ActiveState', 'SubState'])))
+ elif cmd == 'flood':
+ # What systemd does while something loads units in bulk: thousands of signals
+ # a second, mostly for mounts and targets, many of them names only.
+ for i in range(1000):
+ emit('UnitNew', '(so)', ('var.mount', PATH + '/unit/var_2emount'))
+ emit('UnitRemoved', '(so)', ('var.mount', PATH + '/unit/var_2emount'))
+ conn.emit_signal(None, paths['alpha.service'], 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (UNIT, {}, ['Description', 'Conditions', 'ActiveState'])))
+ for i in range(300):
+ emit('UnitNew', '(so)', ('worker-05.service', paths['worker-05.service']))
+ record('flood_done')
+ elif cmd == 'new':
+ key = 'fresh.service'
+ units[key] = ['Fresh worker', 'active', 'running', 'static', 0]
+ no_file.add(key)
+ paths[key] = PATH + '/unit/fresh'
+ types[key] = 'simple'
+ register(paths[key])
+ emit('UnitNew', '(so)', (key, paths[key]))
+ elif cmd == 'gone':
+ del units['fresh.service']
+ emit('UnitRemoved', '(so)', ('fresh.service', paths['fresh.service']))
+ elif cmd == 'unload':
+ unloaded.add('beta.service')
+ emit('UnitRemoved', '(so)', ('beta.service', paths['beta.service']))
elif cmd == 'type':
types['alpha.service'] = 'dbus'
conn.emit_signal(None, paths['alpha.service'], 'org.freedesktop.DBus.Properties', 'PropertiesChanged', GLib.Variant('(sa{sv}as)', (SERVICE, {}, ['Type'])))
@@ -660,6 +713,9 @@ def systemd_services(scale):
except ValueError: pass # a writer is mid-append
return result
def checks(): return [r for r in records() if r['method'] == 'CheckAuthorization']
+ def count(method): return len([r for r in records() if r['method'] == method])
+ def reads(): return [r for r in records() if r['method'].startswith('Property:')]
+ unloaded_path = '/org/freedesktop/systemd1/unit/unloaded'
def scroll_service_into_view(name):
for _ in range(40):
widget = ui.find(name)
@@ -684,6 +740,9 @@ def systemd_services(scale):
wait(lambda: not ui.find(name)['is_disabled'], 'control ready: ' + name)
ui.click(scroll_service_into_view(name), panel='control_center', fraction=fraction)
ui.wait_settled('control_center')
+ # Nothing is asked of systemd until the Services page is on screen.
+ time.sleep(.5)
+ assert not [r for r in records() if r['method'] in ('Subscribe', 'ListUnits', 'ListUnitFiles') or r['method'].startswith('Property:')], records()
# While the first list is on its way, its placeholder is a row
# inside the table, not a line above it.
fake.stdin.write('delay\n'); fake.stdin.flush()
@@ -715,12 +774,26 @@ def systemd_services(scale):
assert any(w['name'] == 'unloaded.service' for w in ui.widgets())
assert not any('Property:FinishTimestampMonotonic' == r['method'] for r in records())
+ # One Subscribe and one of each list. RefUnit is never used (systemd
+ # asks polkit about every call, and refreshing hundreds of unloaded
+ # units that way pinned PID 1 and polkitd), nothing is asked of a
+ # unit systemd has not loaded, and details are read once for each
+ # of the 45 loaded ones.
+ assert count('Subscribe') == 1 and count('ListUnits') == 1 and count('ListUnitFiles') == 1, records()
+ assert count('RefUnit') == 0 and count('LoadUnit') == 0
+ assert not [r for r in reads() if r['args'] == unloaded_path], reads()
+ for key in ('Type', 'Transient', 'TriggeredBy'):
+ assert count('Property:' + key) == 45, (key, count('Property:' + key))
+ time.sleep(1.2)
+ assert count('ListUnits') == 1 and len(reads()) == 135, 'an idle list must not poll'
assert ui.find('services_optimize')['is_disabled'] is True
assert ui.find('startup:masked.service')['is_disabled'] is True
assert ui.find('startup:slow.service')['is_disabled'] is True
assert ui.find('notify:alpha.service')['selected_index'] == 4
assert ui.find('notify:beta.service')['selected_index'] == 0
- assert ui.find('notify:unloaded.service')['selected_index'] == 3
+ # Not loaded, so its Type is unknown and read-only.
+ assert ui.find('notify:unloaded.service')['selected_index'] == 8
+ assert ui.find('notify:unloaded.service')['is_disabled'] is True
assert ui.find('notify:masked.service')['is_disabled'] is True
assert any(w['name'] == 'Notify' for w in ui.widgets())
assert ui.find('notify:worker-00.service')['selected_index'] == 6
@@ -755,13 +828,11 @@ def systemd_services(scale):
assert not ui.find('notify:slow.service')['is_disabled']
click('Notify')
rows = [w['name'] for w in ui.widgets() if w['role'] == 'row' and (w['name'] or '').endswith('.service')]
- assert rows[0] == 'beta.service', rows
+ # A service systemd has not loaded has no Type to sort by and none to edit.
+ assert rows[:2] == ['unloaded.service', 'beta.service'], rows
click('Service')
- click('notify:unloaded.service')
- ipc.key_press('Down')
- ipc.key_press('Return')
- wait(lambda: ui.find('notify:unloaded.service')['selected_index'] == 4, 'edit initially unloaded service')
- assert (root / 'etc/systemd/system/unloaded.service.d/zz-rediwm-notify.conf').read_text() == '[Service]\nType=notify\n'
+ assert ui.find('notify:unloaded.service')['is_disabled'] is True
+ assert not (root / 'etc/systemd/system/unloaded.service.d').exists()
assert not any(label == '125 ms' for label in labels())
if dest := os.environ.get('REDIWM_SETTINGS_PREVIEW'):
scroll_service_into_view('services_columns')
@@ -813,11 +884,13 @@ def systemd_services(scale):
click('services_unlock')
wait(lambda: 'Service changes are unlocked for this session.' in labels(), 'unlocked again')
assert len(checks()) == 3, checks()
+ lists = count('ListUnits')
click('services_stop')
wait(lambda: any(r['method'] == 'StopUnit' for r in records()), 'stop requested')
wait(lambda: 'inactive' in labels(), 'stop status')
click('services_start')
wait(lambda: 'active' in labels(), 'start status')
+ assert count('ListUnits') == lists, 'a state change arrives as a signal, not a new list'
click('startup:alpha.service')
ipc.key_press('Down')
ipc.key_press('Return')
@@ -852,13 +925,57 @@ def systemd_services(scale):
fake.stdin.write('spoof\n'); fake.stdin.flush()
time.sleep(.25)
assert len(records()) == before
+ lists, files, types, nreads = count('ListUnits'), count('ListUnitFiles'), count('Property:Type'), len(reads())
fake.stdin.write('change\n'); fake.stdin.flush()
wait(lambda: 'failed' in labels(), 'live state update')
assert ui.find('services_search')['text_length'] == 5
+ assert count('ListUnits') == lists + 1 and count('ListUnitFiles') == files + 1 and len(reads()) == nreads, \
+ 'a change signalled by name is one coalesced reload, and details already read are not read again'
fake.stdin.write('type\n'); fake.stdin.flush()
wait(lambda: ui.find('notify:alpha.service')['selected_index'] == 1, 'live type update')
+ assert count('ListUnits') == lists + 2 and count('Property:Type') == types + 1, 'only the unit whose Type changed is read again'
fake.stdin.write('reload-type\n'); fake.stdin.flush()
wait(lambda: ui.find('notify:alpha.service')['selected_index'] == 2, 'type update after external daemon reload')
+ assert count('ListUnits') == lists + 3 and count('Property:Type') == types + 1 + 45, 'a daemon reload re-reads the list and every detail'
+ # Leaving the page lets go: matches dropped, Unsubscribe sent, later
+ # signals unheard, and coming back loads afresh.
+ subscribes, lists, before = count('Subscribe'), count('ListUnits'), count('Unsubscribe')
+ click('general')
+ wait(lambda: count('Unsubscribe') == before + 1, 'unsubscribed after leaving the page')
+ reads_before = len(reads())
+ fake.stdin.write('change\n'); fake.stdin.flush()
+ time.sleep(.6)
+ assert len(reads()) == reads_before and count('ListUnits') == lists, 'a hidden page must not hear signals'
+ click('services')
+ wait(lambda: any('46 services' in label for label in labels()), 'list after returning to the page')
+ assert count('Subscribe') == subscribes + 1 and count('ListUnits') == lists + 1
+ # systemd broadcasts thousands of UnitNew/UnitRemoved a second while anything
+ # loads units in bulk. No signal may cost a call of its own: the burst below
+ # (3,300 signals) may cause a reload or two, and no detail is read again.
+ lists, nreads = count('ListUnits'), len(reads())
+ fake.stdin.write('flood\n'); fake.stdin.flush()
+ wait(lambda: any(r['method'] == 'flood_done' for r in records()), 'flood sent')
+ time.sleep(2.0)
+ assert count('ListUnits') - lists <= 3, count('ListUnits') - lists
+ assert len(reads()) == nreads, len(reads()) - nreads
+ time.sleep(1.2)
+ lists = count('ListUnits')
+ time.sleep(1.2)
+ assert count('ListUnits') == lists, 'the list settles when the signals stop'
+ # A unit that loads or unloads while the page is open changes one row. The IPC
+ # query below leases the list for a while; Settings closing ends that too.
+ lists = count('ListUnits')
+ fake.stdin.write('new\n'); fake.stdin.flush()
+ wait(lambda: any('47 services' in label for label in labels()), 'new unit appears')
+ fake.stdin.write('gone\n'); fake.stdin.flush()
+ wait(lambda: any('46 services' in label for label in labels()), 'unit without a file disappears')
+ fake.stdin.write('unload\n'); fake.stdin.flush()
+ def service(unit): return next(s for s in ipc.query('get_services')['services'] if s['name'] == unit)
+ wait(lambda: not ipc.query('get_services')['analyzing'], 'analysis settled')
+ wait(lambda: service('beta.service')['description'] == 'Not loaded', 'unloaded unit keeps its row')
+ assert any('46 services' in label for label in labels())
+ assert service('beta.service')['startup'] == 'disabled'
+ assert count('ListUnits') == lists + 1, 'a new unit is one reload; a removed one needs none'
for r in records():
if r['method'] in ('StartUnit', 'StopUnit', 'DisableUnitFiles', 'Reload'):
assert r['flags'] & 4, r
@@ -866,6 +983,10 @@ def systemd_services(scale):
Path(dest).mkdir(parents=True, exist_ok=True)
(Path(dest) / ('services-' + scale + '.png')).unlink(missing_ok=True)
ipc.screenshot(str(Path(dest) / ('services-' + scale + '.png')))
+ # While the page is live exactly one subscription is open. The daemon that
+ # is about to die cannot be unsubscribed from, so it stays counted.
+ dangling = count('Subscribe') - count('Unsubscribe')
+ assert dangling == 1, (count('Subscribe'), count('Unsubscribe'))
stop_process(fake); fake = None
wait(lambda: not any(w['name'] == 'services' for w in ui.widgets()), 'systemd disappears')
assert ipc.get_shell_state()['control_center']['category'] == 'general'
@@ -940,7 +1061,20 @@ def systemd_services(scale):
ipc.close_window(window['id'])
ui.wait_absent('control_center')
assert process.poll() is None
- print('PASS: systemd discovery, in-table loading, unlock/lock, services, Notify reads/edits/sorting, isolated drop-ins, timing, search, actions, authorization refusal, live updates, owner loss and close')
+ # A closed Settings window holds nothing: no matches, no subscription.
+ wait(lambda: count('Subscribe') - count('Unsubscribe') == dangling, 'nothing watches after Settings closes', timeout=20)
+ # An IPC query is not a page: it keeps the list live for its lease
+ # (renewed by each query), then lets go.
+ subscribes, unsubscribes = count('Subscribe'), count('Unsubscribe')
+ assert ipc.query('get_services')['loading'] is True
+ wait(lambda: count('Subscribe') == subscribes + 1, 'IPC query goes live')
+ wait(lambda: not ipc.query('get_services')['loading'], 'IPC list loaded')
+ time.sleep(1.2)
+ assert count('Unsubscribe') == unsubscribes and count('ListUnits') >= 1
+ wait(lambda: count('Unsubscribe') == unsubscribes + 1, 'lease ends and the list is let go', timeout=25)
+ assert not [r for r in reads() if r['args'] == unloaded_path] and count('RefUnit') == 0 and count('LoadUnit') == 0
+ assert process.poll() is None
+ print('PASS: systemd discovery, in-table loading, unlock/lock, services, Notify reads/edits/sorting, isolated drop-ins, timing, search, actions, authorization refusal, live and in-place updates, nothing read until the page is shown or while it is hidden, no RefUnit or unloaded-unit reads, IPC lease, owner loss and close')
except Exception:
log.flush()
print((tmp / 'compositor.log').read_text()[-4000:])