From e70bf0ffaac0f076faf028eb4553acce24556e05 Mon Sep 17 00:00:00 2001 From: Ilia Ross Date: Wed, 30 Sep 2026 00:05:56 +0200 Subject: [PATCH] Add `get_unit_state` to read fresh systemd unit properties --- systemd/systemd-lib.pl | 27 +++++++++++++++++++++++++++ systemd/t/run-tests.t | 24 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/systemd/systemd-lib.pl b/systemd/systemd-lib.pl index 8cbe8a777..2ca27a756 100644 --- a/systemd/systemd-lib.pl +++ b/systemd/systemd-lib.pl @@ -662,6 +662,33 @@ my $out = backquote_logged( return (!$?, $out); } +=head2 get_unit_state(name) + +Returns a fresh hash of LoadState, UnitFileState, ActiveState, SubState and +MainPID, followed by an error string. Missing units have LoadState not-found; +command or validation failures return undef and an error. No inventory cache +is used, so callers can verify a change immediately. + +=cut +sub get_unit_state +{ +my ($name) = @_; +return (undef, $text{'systemd_ename'}) if (!valid_unit_name($name)); +my $out = backquote_logged("systemctl show --no-pager ". + "--property=LoadState,UnitFileState,ActiveState,SubState,MainPID ". + quotemeta($name)." 2>&1 {SubState}, 'listening', 'socket readiness is exposed'); + like($commands[-1], qr/--property=LoadState,UnitFileState,ActiveState,SubState,MainPID/, 'only requested properties are read'); + $reply = "LoadState=loaded\nUnitFileState=enabled\nActiveState=inactive\n"; + ($state, $error) = get_unit_state('demo.socket'); + is($state->{ActiveState}, 'inactive', 'state is not cached'); + $reply = "LoadState=not-found\nActiveState=inactive\n"; $status = 1024; + ($state, $error) = get_unit_state('missing.service'); + is($state->{LoadState}, 'not-found', 'missing unit is a valid discovery result'); + $reply = 'Failed to connect to bus'; + ($state, $error) = get_unit_state('demo.socket'); + ok(!defined($state), 'bus failure returns no state'); + like($error, qr/connect to bus/, 'bus error is preserved'); + ($state, $error) = get_unit_state('bad;unit.service'); + is($error, 'bad unit name', 'invalid state lookup is rejected'); +} + { my @cmds; my $reloaded = 0;