Files
systemd/src/systemctl/systemctl-set-property.c
T
Zbigniew Jędrzejewski-Szmek 31ddd87da0 tree-wide: extend verbs functions with extra per-verb data parameter
We often have a pattern where the same verb function is used for
multiple actions. This leads to an antipattern where we figure out what
action needs to be taken from argv[0] multiple times: often once in
parse_argv() to figure out what options are allowed, then once again
implicitly in dispatch_verb(), and then again in the action verb itself.
Let's allow passing a parameter into the verb to simplify this.

This matches a pattern we have in conf-parser.h, where we have both
void *userdata (more global) and void *data (per-config item). Here,
I opted for uintptr_t userdata. It seems that most of the time we'll
want to just pass an enum value. This works OK with no casts. I also
tried a void* and union. In both cases, much more boilerplate is needed:
either a cast or a macro to help avoid compiler warnings. uintptr_t
seems generic enough to cover foreseeable usecases with no fuss.

This is a noop refactoring. See next commit for an example.
2026-03-18 10:28:47 +00:00

74 lines
2.2 KiB
C

/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "sd-bus.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "bus-unit-util.h"
#include "bus-util.h"
#include "errno-util.h"
#include "strv.h"
#include "systemctl.h"
#include "systemctl-set-property.h"
#include "systemctl-util.h"
#include "unit-def.h"
#include "unit-name.h"
static int set_property_one(sd_bus *bus, const char *name, char **properties) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
int r;
r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "SetUnitProperties");
if (r < 0)
return bus_log_create_error(r);
UnitType t = unit_name_to_type(name);
if (t < 0)
return log_error_errno(t, "Invalid unit type: %s", name);
r = sd_bus_message_append(m, "sb", name, arg_runtime);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_message_open_container(m, SD_BUS_TYPE_ARRAY, "(sv)");
if (r < 0)
return bus_log_create_error(r);
r = bus_append_unit_property_assignment_many(m, t, properties);
if (r < 0)
return r;
r = sd_bus_message_close_container(m);
if (r < 0)
return bus_log_create_error(r);
r = sd_bus_call(bus, m, 0, &error, NULL);
if (r < 0)
return log_error_errno(r, "Failed to set unit properties on %s: %s",
name, bus_error_message(&error, r));
return 0;
}
int verb_set_property(int argc, char *argv[], uintptr_t _data, void *userdata) {
sd_bus *bus;
_cleanup_strv_free_ char **names = NULL;
int r;
r = acquire_bus(BUS_MANAGER, &bus);
if (r < 0)
return r;
polkit_agent_open_maybe();
r = expand_unit_names(bus, STRV_MAKE(argv[1]), NULL, &names, NULL);
if (r < 0)
return log_error_errno(r, "Failed to expand '%s' into names: %m", argv[1]);
r = 0;
STRV_FOREACH(name, names)
RET_GATHER(r, set_property_one(bus, *name, strv_skip(argv, 2)));
return r;
}