Debian Codegraph @

src/systemctl/systemctl-is-active.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "sd-bus.h"
4
5 #include "alloc-util.h"
6 #include "bus-error.h"
7 #include "bus-locator.h"
8 #include "bus-unit-util.h"
9 #include "log.h"
10 #include "string-util.h"
11 #include "strv.h"
12 #include "systemctl.h"
13 #include "systemctl-is-active.h"
14 #include "systemctl-util.h"
15 #include "unit-def.h"
16
17 static int check_unit_generic(int code, const UnitActiveState good_states[], size_t nb_states, char **args) {
18 _cleanup_strv_free_ char **names = NULL;
19 UnitActiveState active_state;
20 sd_bus *bus;
21 bool not_found = true, ok = false;
22 int r;
23
24 r = acquire_bus(BUS_MANAGER, &bus);
25 if (r < 0)
26 return r;
27
28 r = expand_unit_names(bus, args, NULL, &names, NULL);
29 if (r < 0)
30 return log_error_errno(r, "Failed to expand names: %m");
31
32 STRV_FOREACH(name, names) {
33 _cleanup_free_ char *load_state = NULL;
34
35 r = get_state_one_unit(bus, *name, &active_state);
36 if (r < 0)
37 return r;
38
39 r = unit_load_state(bus, *name, &load_state);
40 if (r < 0)
41 return r;
42
43 if (!arg_quiet)
44 puts(unit_active_state_to_string(active_state));
45
46 FOREACH_ARRAY(good_state, good_states, nb_states)
47 if (active_state == *good_state) {
48 ok = true;
49 break;
50 }
51
52 if (!streq(load_state, "not-found"))
53 not_found = false;
54 }
55
56 /* We use LSB code 4 ("program or service status is unknown") when the corresponding unit file doesn't exist. */
57 return ok ? EXIT_SUCCESS : not_found ? EXIT_PROGRAM_OR_SERVICES_STATUS_UNKNOWN : code;
58 }
59
60 int verb_is_active(int argc, char *argv[], uintptr_t _data, void *userdata) {
61
62 static const UnitActiveState states[] = {
63 UNIT_ACTIVE,
64 UNIT_RELOADING,
65 UNIT_REFRESHING,
66 };
67
68 /* According to LSB: 3, "program is not running" */
69 return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
70 }
71
72 int verb_is_failed(int argc, char *argv[], uintptr_t _data, void *userdata) {
73
74 static const UnitActiveState states[] = {
75 UNIT_FAILED,
76 };
77
78 int r;
79
80 if (argc > 1)
81 return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
82
83 /* If no unit is provided, we check SystemState property of the manager, i.e. whether there're failed
84 * units. */
85
86 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
87 _cleanup_free_ char *state = NULL;
88 sd_bus *bus;
89
90 r = acquire_bus(BUS_MANAGER, &bus);
91 if (r < 0)
92 return r;
93
94 r = bus_get_property_string(bus, bus_systemd_mgr, "SystemState", &error, &state);
95 if (r < 0)
96 return log_error_errno(r, "Failed to query system state: %s", bus_error_message(&error, r));
97
98 if (!arg_quiet)
99 puts(state);
100
101 return streq(state, "degraded") ? EXIT_SUCCESS : EXIT_FAILURE;
102 }