1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include "bus-error.h"
4 #include "bus-locator.h"
5 #include "pretty-print.h"
6 #include "syslog-util.h"
7 #include "systemctl-is-active.h"
8 #include "systemctl-sysv-compat.h"
9 #include "systemctl-util.h"
10 #include "systemctl.h"
11 
check_unit_generic(int code,const UnitActiveState good_states[],int nb_states,char ** args)12 static int check_unit_generic(int code, const UnitActiveState good_states[], int nb_states, char **args) {
13         _cleanup_strv_free_ char **names = NULL;
14         UnitActiveState active_state;
15         sd_bus *bus;
16         int r;
17         bool found = false;
18 
19         r = acquire_bus(BUS_MANAGER, &bus);
20         if (r < 0)
21                 return r;
22 
23         r = expand_unit_names(bus, args, NULL, &names, NULL);
24         if (r < 0)
25                 return log_error_errno(r, "Failed to expand names: %m");
26 
27         STRV_FOREACH(name, names) {
28                 r = get_state_one_unit(bus, *name, &active_state);
29                 if (r < 0)
30                         return r;
31 
32                 if (!arg_quiet)
33                         puts(unit_active_state_to_string(active_state));
34 
35                 for (int i = 0; i < nb_states; ++i)
36                         if (good_states[i] == active_state)
37                                 found = true;
38         }
39 
40         /* use the given return code for the case that we won't find
41          * any unit which matches the list */
42         return found ? 0 : code;
43 }
44 
verb_is_active(int argc,char * argv[],void * userdata)45 int verb_is_active(int argc, char *argv[], void *userdata) {
46         static const UnitActiveState states[] = {
47                 UNIT_ACTIVE,
48                 UNIT_RELOADING,
49         };
50 
51         /* According to LSB: 3, "program is not running" */
52         return check_unit_generic(EXIT_PROGRAM_NOT_RUNNING, states, ELEMENTSOF(states), strv_skip(argv, 1));
53 }
54 
verb_is_failed(int argc,char * argv[],void * userdata)55 int verb_is_failed(int argc, char *argv[], void *userdata) {
56         static const UnitActiveState states[] = {
57                 UNIT_FAILED,
58         };
59 
60         return check_unit_generic(EXIT_PROGRAM_DEAD_AND_PID_EXISTS, states, ELEMENTSOF(states), strv_skip(argv, 1));
61 }
62