1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include "analyze-condition.h"
7 #include "analyze-verify-util.h"
9 #include "conf-parser.h"
10 #include "load-fragment.h"
13 static int parse_condition(Unit
*u
, const char *line
) {
17 for (ConditionType t
= 0; t
< _CONDITION_TYPE_MAX
; t
++) {
18 ConfigParserCallback callback
;
22 name
= condition_type_to_string(t
);
23 p
= startswith(line
, name
);
25 target
= &u
->conditions
;
27 name
= assert_type_to_string(t
);
28 p
= startswith(line
, name
);
35 p
+= strspn(p
, WHITESPACE
);
41 p
+= strspn(p
, WHITESPACE
);
43 if (condition_takes_path(t
))
44 callback
= config_parse_unit_condition_path
;
46 callback
= config_parse_unit_condition_string
;
48 return callback(NULL
, "(cmdline)", 0, NULL
, 0, name
, t
, p
, target
, u
);
51 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Cannot parse \"%s\".", line
);
55 static int log_helper(void *userdata
, int level
, int error
, const char *file
, int line
, const char *func
, const char *format
, ...) {
62 /* "upgrade" debug messages */
63 level
= MIN(LOG_INFO
, level
);
66 r
= log_object_internalv(level
, error
, file
, line
, func
,
77 static int verify_conditions(char **lines
, LookupScope scope
, const char *unit
, const char *root
) {
78 _cleanup_(manager_freep
) Manager
*m
= NULL
;
83 _cleanup_strv_free_
char **filenames
= NULL
;
84 _cleanup_free_
char *var
= NULL
;
86 filenames
= strv_new(unit
);
90 r
= verify_generate_path(&var
, filenames
);
92 return log_error_errno(r
, "Failed to generate unit load path: %m");
94 assert_se(set_unit_path(var
) >= 0);
97 r
= manager_new(scope
, MANAGER_TEST_RUN_MINIMAL
, &m
);
99 return log_error_errno(r
, "Failed to initialize manager: %m");
101 log_debug("Starting manager...");
102 r
= manager_startup(m
, /* serialization= */ NULL
, /* fds= */ NULL
, root
);
107 _cleanup_free_
char *prepared
= NULL
;
109 r
= verify_prepare_filename(unit
, &prepared
);
111 return log_error_errno(r
, "Failed to prepare filename %s: %m", unit
);
113 r
= manager_load_startable_unit_or_warn(m
, NULL
, prepared
, &u
);
117 r
= unit_new_for_name(m
, sizeof(Service
), "test.service", &u
);
119 return log_error_errno(r
, "Failed to create test.service: %m");
121 STRV_FOREACH(line
, lines
) {
122 r
= parse_condition(u
, *line
);
128 r
= condition_test_list(u
->asserts
, environ
, assert_type_to_string
, log_helper
, u
);
130 log_notice("Asserts %s.", r
> 0 ? "succeeded" : "failed");
132 q
= condition_test_list(u
->conditions
, environ
, condition_type_to_string
, log_helper
, u
);
134 log_notice("Conditions %s.", q
> 0 ? "succeeded" : "failed");
136 return r
> 0 && q
> 0 ? 0 : -EIO
;
139 int verb_condition(int argc
, char *argv
[], void *userdata
) {
142 r
= verify_conditions(strv_skip(argv
, 1), arg_scope
, arg_unit
, arg_root
);