]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/timer.c
Revert "core: Propagate condition failed state to triggering units."
[thirdparty/systemd.git] / src / core / timer.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
ca78ad1d
ZJS
3#include <sys/stat.h>
4#include <sys/types.h>
5#include <unistd.h>
6
d46de8a1
LP
7#include <errno.h>
8
b5efdb8a 9#include "alloc-util.h"
07630cea
LP
10#include "bus-error.h"
11#include "bus-util.h"
871d7de4 12#include "dbus-timer.h"
6fcbec6f 13#include "dbus-unit.h"
f4f15635 14#include "fs-util.h"
6bedfcbb 15#include "parse-util.h"
744c7693 16#include "random-util.h"
d68c645b 17#include "serialize.h"
a40eb732 18#include "special.h"
8b43440b 19#include "string-table.h"
07630cea 20#include "string-util.h"
b1d4f8e1 21#include "timer.h"
07630cea
LP
22#include "unit-name.h"
23#include "unit.h"
b1d4f8e1 24#include "user-util.h"
c1d9ba99 25#include "virt.h"
871d7de4
LP
26
27static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
28 [TIMER_DEAD] = UNIT_INACTIVE,
29 [TIMER_WAITING] = UNIT_ACTIVE,
30 [TIMER_RUNNING] = UNIT_ACTIVE,
31 [TIMER_ELAPSED] = UNIT_ACTIVE,
fdf20a31 32 [TIMER_FAILED] = UNIT_FAILED
871d7de4
LP
33};
34
718db961
LP
35static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
36
871d7de4
LP
37static void timer_init(Unit *u) {
38 Timer *t = TIMER(u);
39
40 assert(u);
ac155bb8 41 assert(u->load_state == UNIT_STUB);
871d7de4 42
3a43da28
KS
43 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
44 t->next_elapse_realtime = USEC_INFINITY;
bd8f585b 45 t->accuracy_usec = u->manager->default_timer_accuracy_usec;
3e0c30ac 46 t->remain_after_elapse = true;
871d7de4 47}
5cb5a6ff 48
74051b9b 49void timer_free_values(Timer *t) {
871d7de4
LP
50 TimerValue *v;
51
52 assert(t);
53
54 while ((v = t->values)) {
71fda00f 55 LIST_REMOVE(value, t->values, v);
3e044c49 56 calendar_spec_free(v->calendar_spec);
871d7de4
LP
57 free(v);
58 }
74051b9b
LP
59}
60
61static void timer_done(Unit *u) {
62 Timer *t = TIMER(u);
63
64 assert(t);
65
66 timer_free_values(t);
871d7de4 67
5dcadb4c
ZJS
68 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
69 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
06642d17
LP
70
71 free(t->stamp_path);
871d7de4
LP
72}
73
74static int timer_verify(Timer *t) {
75 assert(t);
75193d41 76 assert(UNIT(t)->load_state == UNIT_LOADED);
871d7de4 77
d85ff944
YW
78 if (!t->values && !t->on_clock_change && !t->on_timezone_change)
79 return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
871d7de4
LP
80
81 return 0;
82}
83
6c155fe3
LP
84static int timer_add_default_dependencies(Timer *t) {
85 int r;
19f8d037 86 TimerValue *v;
6c155fe3
LP
87
88 assert(t);
89
4c9ea260
LP
90 if (!UNIT(t)->default_dependencies)
91 return 0;
92
35d8c19a 93 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721
LP
94 if (r < 0)
95 return r;
2a77d31d 96
463d0d15 97 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
5a724170 98 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
36697dc0 99 if (r < 0)
6c155fe3 100 return r;
19f8d037 101
fe934b42
LP
102 LIST_FOREACH(value, v, t->values) {
103 const char *target;
104
105 if (v->base != TIMER_CALENDAR)
106 continue;
107
108 FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
109 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
19f8d037
TGR
110 if (r < 0)
111 return r;
19f8d037 112 }
fe934b42
LP
113
114 break;
115 }
2a77d31d 116 }
6c155fe3 117
5a724170 118 return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
eef85c4a
LP
119}
120
121static int timer_add_trigger_dependencies(Timer *t) {
122 Unit *x;
123 int r;
124
125 assert(t);
126
bc32241e 127 if (UNIT_TRIGGER(UNIT(t)))
eef85c4a
LP
128 return 0;
129
130 r = unit_load_related_unit(UNIT(t), ".service", &x);
131 if (r < 0)
132 return r;
133
134 return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
6c155fe3
LP
135}
136
06642d17
LP
137static int timer_setup_persistent(Timer *t) {
138 int r;
139
140 assert(t);
141
142 if (!t->persistent)
143 return 0;
144
463d0d15 145 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
06642d17 146
eef85c4a 147 r = unit_require_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE);
06642d17
LP
148 if (r < 0)
149 return r;
150
b910cc72 151 t->stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
152 } else {
153 const char *e;
154
155 e = getenv("XDG_DATA_HOME");
156 if (e)
605405c6 157 t->stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
158 else {
159
160 _cleanup_free_ char *h = NULL;
161
162 r = get_home_dir(&h);
23bbb0de 163 if (r < 0)
f2341e0a 164 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
06642d17 165
605405c6 166 t->stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
167 }
168 }
169
170 if (!t->stamp_path)
171 return log_oom();
172
173 return 0;
174}
175
acf24a1a
KG
176static uint64_t timer_get_fixed_delay_hash(Timer *t) {
177 static const uint8_t hash_key[] = {
178 0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
179 0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
180 };
181
182 struct siphash state;
183 sd_id128_t machine_id;
184 uid_t uid;
185 int r;
186
187 assert(t);
188
189 uid = getuid();
190 r = sd_id128_get_machine(&machine_id);
191 if (r < 0) {
192 log_unit_debug_errno(UNIT(t), r,
193 "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
194 machine_id = SD_ID128_NULL;
195 }
196
197 siphash24_init(&state, hash_key);
198 siphash24_compress(&machine_id, sizeof(sd_id128_t), &state);
199 siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
200 siphash24_compress(&uid, sizeof(uid_t), &state);
201 siphash24_compress_string(UNIT(t)->id, &state);
202
203 return siphash24_finalize(&state);
204}
205
871d7de4
LP
206static int timer_load(Unit *u) {
207 Timer *t = TIMER(u);
208 int r;
209
210 assert(u);
ac155bb8 211 assert(u->load_state == UNIT_STUB);
871d7de4 212
c3620770 213 r = unit_load_fragment_and_dropin(u, true);
36697dc0 214 if (r < 0)
871d7de4
LP
215 return r;
216
75193d41
ZJS
217 if (u->load_state != UNIT_LOADED)
218 return 0;
871d7de4 219
75193d41
ZJS
220 /* This is a new unit? Then let's add in some extras */
221 r = timer_add_trigger_dependencies(t);
222 if (r < 0)
223 return r;
57020a3a 224
75193d41
ZJS
225 r = timer_setup_persistent(t);
226 if (r < 0)
227 return r;
06642d17 228
75193d41
ZJS
229 r = timer_add_default_dependencies(t);
230 if (r < 0)
231 return r;
871d7de4
LP
232
233 return timer_verify(t);
234}
235
236static void timer_dump(Unit *u, FILE *f, const char *prefix) {
237 Timer *t = TIMER(u);
3ecaa09b 238 Unit *trigger;
871d7de4 239 TimerValue *v;
034c6ed7 240
3ecaa09b
LP
241 trigger = UNIT_TRIGGER(u);
242
871d7de4
LP
243 fprintf(f,
244 "%sTimer State: %s\n"
067d72c9 245 "%sResult: %s\n"
9f5eb56a 246 "%sUnit: %s\n"
dedabea4
LP
247 "%sPersistent: %s\n"
248 "%sWakeSystem: %s\n"
3e0c30ac 249 "%sAccuracy: %s\n"
efebb613 250 "%sRemainAfterElapse: %s\n"
acf24a1a 251 "%sFixedRandomDelay: %s\n"
efebb613 252 "%sOnClockChange: %s\n"
0810e396 253 "%sOnTimeZoneChange: %s\n",
871d7de4 254 prefix, timer_state_to_string(t->state),
067d72c9 255 prefix, timer_result_to_string(t->result),
9f5eb56a 256 prefix, trigger ? trigger->id : "n/a",
dedabea4
LP
257 prefix, yes_no(t->persistent),
258 prefix, yes_no(t->wake_system),
5291f26d 259 prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
efebb613 260 prefix, yes_no(t->remain_after_elapse),
acf24a1a 261 prefix, yes_no(t->fixed_random_delay),
efebb613
LP
262 prefix, yes_no(t->on_clock_change),
263 prefix, yes_no(t->on_timezone_change));
871d7de4 264
2762ce2d 265 LIST_FOREACH(value, v, t->values)
36697dc0
LP
266 if (v->base == TIMER_CALENDAR) {
267 _cleanup_free_ char *p = NULL;
268
25cb94d4 269 (void) calendar_spec_to_string(v->calendar_spec, &p);
36697dc0
LP
270
271 fprintf(f,
272 "%s%s: %s\n",
273 prefix,
274 timer_base_to_string(v->base),
275 strna(p));
5291f26d 276 } else
36697dc0
LP
277 fprintf(f,
278 "%s%s: %s\n",
279 prefix,
280 timer_base_to_string(v->base),
5291f26d 281 FORMAT_TIMESPAN(v->value, 0));
871d7de4
LP
282}
283
284static void timer_set_state(Timer *t, TimerState state) {
285 TimerState old_state;
034c6ed7 286 assert(t);
871d7de4 287
6fcbec6f
LP
288 if (t->state != state)
289 bus_unit_send_pending_change_signal(UNIT(t), false);
290
871d7de4
LP
291 old_state = t->state;
292 t->state = state;
293
36697dc0 294 if (state != TIMER_WAITING) {
5dcadb4c
ZJS
295 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
296 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
6e2c9ce1
ZJS
297 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
298 t->next_elapse_realtime = USEC_INFINITY;
36697dc0 299 }
871d7de4
LP
300
301 if (state != old_state)
f2341e0a 302 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
871d7de4 303
2ad2e41a 304 unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], 0);
871d7de4
LP
305}
306
aa1f95d2 307static void timer_enter_waiting(Timer *t, bool time_change);
871d7de4 308
be847e82 309static int timer_coldplug(Unit *u) {
871d7de4
LP
310 Timer *t = TIMER(u);
311
312 assert(t);
313 assert(t->state == TIMER_DEAD);
314
3e0c30ac
LP
315 if (t->deserialized_state == t->state)
316 return 0;
871d7de4 317
3e0c30ac 318 if (t->deserialized_state == TIMER_WAITING)
aa1f95d2 319 timer_enter_waiting(t, false);
3e0c30ac
LP
320 else
321 timer_set_state(t, t->deserialized_state);
871d7de4
LP
322
323 return 0;
324}
325
067d72c9 326static void timer_enter_dead(Timer *t, TimerResult f) {
871d7de4
LP
327 assert(t);
328
a0fef983 329 if (t->result == TIMER_SUCCESS)
067d72c9 330 t->result = f;
871d7de4 331
aac99f30 332 unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
067d72c9 333 timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
871d7de4
LP
334}
335
3e0c30ac
LP
336static void timer_enter_elapsed(Timer *t, bool leave_around) {
337 assert(t);
338
339 /* If a unit is marked with RemainAfterElapse=yes we leave it
340 * around even after it elapsed once, so that starting it
341 * later again does not necessarily mean immediate
342 * retriggering. We unconditionally leave units with
343 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
344 * since they might be restarted automatically at any time
345 * later on. */
346
347 if (t->remain_after_elapse || leave_around)
348 timer_set_state(t, TIMER_ELAPSED);
349 else
350 timer_enter_dead(t, TIMER_SUCCESS);
351}
352
744c7693 353static void add_random(Timer *t, usec_t *v) {
744c7693
LP
354 usec_t add;
355
356 assert(t);
3f51aec8 357 assert(v);
744c7693
LP
358
359 if (t->random_usec == 0)
360 return;
361 if (*v == USEC_INFINITY)
362 return;
363
acf24a1a 364 add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_usec;
744c7693
LP
365
366 if (*v + add < *v) /* overflow */
367 *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
368 else
369 *v += add;
370
5291f26d 371 log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
744c7693
LP
372}
373
aa1f95d2 374static void timer_enter_waiting(Timer *t, bool time_change) {
36697dc0 375 bool found_monotonic = false, found_realtime = false;
3e0c30ac 376 bool leave_around = false;
c54be90b 377 triple_timestamp ts;
dedabea4 378 TimerValue *v;
e903182e 379 Unit *trigger;
871d7de4
LP
380 int r;
381
e903182e
LP
382 assert(t);
383
384 trigger = UNIT_TRIGGER(UNIT(t));
385 if (!trigger) {
386 log_unit_error(UNIT(t), "Unit to trigger vanished.");
387 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
388 return;
389 }
390
c54be90b 391 triple_timestamp_get(&ts);
dedabea4 392 t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
871d7de4
LP
393
394 LIST_FOREACH(value, v, t->values) {
871d7de4
LP
395 if (v->disabled)
396 continue;
397
36697dc0 398 if (v->base == TIMER_CALENDAR) {
58afc4f8 399 usec_t b, rebased;
06642d17
LP
400
401 /* If we know the last time this was
402 * triggered, schedule the job based relative
9ea9faff
AJ
403 * to that. If we don't, just start from
404 * the activation time. */
405
406 if (t->last_trigger.realtime > 0)
407 b = t->last_trigger.realtime;
408 else {
409 if (state_translation_table[t->state] == UNIT_ACTIVE)
410 b = UNIT(t)->inactive_exit_timestamp.realtime;
411 else
412 b = ts.realtime;
413 }
06642d17
LP
414
415 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
36697dc0
LP
416 if (r < 0)
417 continue;
418
58afc4f8
LP
419 /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
420 * time has already passed, set the time when systemd first started as the scheduled
421 * time. Note that we base this on the monotonic timestamp of the boot, not the
422 * realtime one, since the wallclock might have been off during boot. */
423 rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
424 CLOCK_MONOTONIC, CLOCK_REALTIME);
425 if (v->next_elapse < rebased)
426 v->next_elapse = rebased;
a87c1d3a 427
36697dc0
LP
428 if (!found_realtime)
429 t->next_elapse_realtime = v->next_elapse;
10717a1a 430 else
36697dc0 431 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
871d7de4 432
36697dc0 433 found_realtime = true;
871d7de4 434
60933bb8
AJ
435 } else {
436 usec_t base;
c54be90b 437
36697dc0 438 switch (v->base) {
871d7de4 439
36697dc0
LP
440 case TIMER_ACTIVE:
441 if (state_translation_table[t->state] == UNIT_ACTIVE)
442 base = UNIT(t)->inactive_exit_timestamp.monotonic;
443 else
c54be90b 444 base = ts.monotonic;
36697dc0 445 break;
871d7de4 446
36697dc0 447 case TIMER_BOOT:
c1d9ba99
MS
448 if (detect_container() <= 0) {
449 /* CLOCK_MONOTONIC equals the uptime on Linux */
450 base = 0;
451 break;
452 }
453 /* In a container we don't want to include the time the host
454 * was already up when the container started, so count from
ec251fe7 455 * our own startup. */
4831981d 456 _fallthrough_;
36697dc0 457 case TIMER_STARTUP:
9f9f0342 458 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
36697dc0 459 break;
871d7de4 460
36697dc0 461 case TIMER_UNIT_ACTIVE:
3e0c30ac 462 leave_around = true;
525b95f1 463 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 464 if (base <= 0)
36697dc0 465 continue;
36697dc0 466 break;
871d7de4 467
36697dc0 468 case TIMER_UNIT_INACTIVE:
3e0c30ac 469 leave_around = true;
525b95f1 470 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 471 if (base <= 0)
36697dc0 472 continue;
36697dc0 473 break;
871d7de4 474
36697dc0 475 default:
04499a70 476 assert_not_reached();
36697dc0 477 }
871d7de4 478
c54be90b 479 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
36697dc0 480
aa1f95d2
MK
481 if (dual_timestamp_is_set(&t->last_trigger) &&
482 !time_change &&
c54be90b
LP
483 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
484 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
e41e1943 485 /* This is a one time trigger, disable it now */
36697dc0
LP
486 v->disabled = true;
487 continue;
488 }
489
490 if (!found_monotonic)
dedabea4 491 t->next_elapse_monotonic_or_boottime = v->next_elapse;
36697dc0 492 else
dedabea4 493 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
36697dc0
LP
494
495 found_monotonic = true;
496 }
871d7de4
LP
497 }
498
efebb613 499 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
f2341e0a 500 log_unit_debug(UNIT(t), "Timer is elapsed.");
3e0c30ac 501 timer_enter_elapsed(t, leave_around);
871d7de4
LP
502 return;
503 }
504
36697dc0 505 if (found_monotonic) {
3e0c30ac 506 usec_t left;
dedabea4 507
744c7693
LP
508 add_random(t, &t->next_elapse_monotonic_or_boottime);
509
c54be90b 510 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
5291f26d 511 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
871d7de4 512
718db961 513 if (t->monotonic_event_source) {
dedabea4 514 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
718db961
LP
515 if (r < 0)
516 goto fail;
517
518 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
519 if (r < 0)
520 goto fail;
521 } else {
522
6a0f1f6d
LP
523 r = sd_event_add_time(
524 UNIT(t)->manager->event,
525 &t->monotonic_event_source,
dedabea4
LP
526 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
527 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
6a0f1f6d 528 timer_dispatch, t);
cbf60d0a
LP
529 if (r < 0)
530 goto fail;
718db961 531
cbf60d0a
LP
532 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
533 }
7dfbe2e3 534
718db961 535 } else if (t->monotonic_event_source) {
718db961 536
06642d17 537 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
718db961
LP
538 if (r < 0)
539 goto fail;
540 }
36697dc0
LP
541
542 if (found_realtime) {
744c7693
LP
543 add_random(t, &t->next_elapse_realtime);
544
04f5c018 545 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
36697dc0 546
718db961
LP
547 if (t->realtime_event_source) {
548 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
549 if (r < 0)
550 goto fail;
551
552 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
553 if (r < 0)
554 goto fail;
555 } else {
6a0f1f6d
LP
556 r = sd_event_add_time(
557 UNIT(t)->manager->event,
558 &t->realtime_event_source,
dedabea4 559 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
6a0f1f6d
LP
560 t->next_elapse_realtime, t->accuracy_usec,
561 timer_dispatch, t);
cbf60d0a
LP
562 if (r < 0)
563 goto fail;
718db961 564
cbf60d0a
LP
565 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
566 }
7dfbe2e3 567
718db961 568 } else if (t->realtime_event_source) {
718db961 569
06642d17 570 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
718db961
LP
571 if (r < 0)
572 goto fail;
573 }
871d7de4
LP
574
575 timer_set_state(t, TIMER_WAITING);
576 return;
577
578fail:
f2341e0a 579 log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m");
067d72c9 580 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
581}
582
583static void timer_enter_running(Timer *t) {
4afd3348 584 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e903182e 585 Unit *trigger;
871d7de4 586 int r;
398ef8ba 587
871d7de4
LP
588 assert(t);
589
ba3e67a7 590 /* Don't start job if we are supposed to go down */
31afa0a4 591 if (unit_stop_pending(UNIT(t)))
ba3e67a7
LP
592 return;
593
e903182e
LP
594 trigger = UNIT_TRIGGER(UNIT(t));
595 if (!trigger) {
596 log_unit_error(UNIT(t), "Unit to trigger vanished.");
597 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
598 return;
599 }
600
50cbaba4 601 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, NULL);
36697dc0 602 if (r < 0)
871d7de4
LP
603 goto fail;
604
06642d17
LP
605 dual_timestamp_get(&t->last_trigger);
606
472fc28f 607 if (t->stamp_path)
ee735086 608 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
e41e1943 609
871d7de4
LP
610 timer_set_state(t, TIMER_RUNNING);
611 return;
612
613fail:
f2341e0a 614 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
067d72c9 615 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
616}
617
618static int timer_start(Unit *u) {
619 Timer *t = TIMER(u);
779042e7 620 TimerValue *v;
07299350 621 int r;
871d7de4
LP
622
623 assert(t);
3742095b 624 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
01f78473 625
a4191c9f
LP
626 r = unit_test_trigger_loaded(u);
627 if (r < 0)
628 return r;
871d7de4 629
4b58153d
LP
630 r = unit_acquire_invocation_id(u);
631 if (r < 0)
632 return r;
633
06642d17
LP
634 t->last_trigger = DUAL_TIMESTAMP_NULL;
635
779042e7
MC
636 /* Reenable all timers that depend on unit activation time */
637 LIST_FOREACH(value, v, t->values)
638 if (v->base == TIMER_ACTIVE)
639 v->disabled = false;
640
06642d17
LP
641 if (t->stamp_path) {
642 struct stat st;
643
77542a79
LP
644 if (stat(t->stamp_path, &st) >= 0) {
645 usec_t ft;
646
647 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
648 * something is wrong with the system clock. */
649
650 ft = timespec_load(&st.st_mtim);
651 if (ft < now(CLOCK_REALTIME))
652 t->last_trigger.realtime = ft;
04f5c018 653 else
77542a79 654 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
04f5c018 655 FORMAT_TIMESTAMP(ft));
77542a79
LP
656
657 } else if (errno == ENOENT)
2762ce2d 658 /* The timer has never run before, make sure a stamp file exists. */
4b58153d 659 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
06642d17
LP
660 }
661
067d72c9 662 t->result = TIMER_SUCCESS;
aa1f95d2 663 timer_enter_waiting(t, false);
82a2b6bb 664 return 1;
871d7de4
LP
665}
666
667static int timer_stop(Unit *u) {
668 Timer *t = TIMER(u);
669
670 assert(t);
3742095b 671 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
871d7de4 672
067d72c9 673 timer_enter_dead(t, TIMER_SUCCESS);
82a2b6bb 674 return 1;
871d7de4
LP
675}
676
677static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
678 Timer *t = TIMER(u);
679
680 assert(u);
681 assert(f);
682 assert(fds);
683
d68c645b
LP
684 (void) serialize_item(f, "state", timer_state_to_string(t->state));
685 (void) serialize_item(f, "result", timer_result_to_string(t->result));
871d7de4 686
06642d17 687 if (t->last_trigger.realtime > 0)
d68c645b 688 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
06642d17
LP
689
690 if (t->last_trigger.monotonic > 0)
d68c645b 691 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
06642d17 692
871d7de4
LP
693 return 0;
694}
695
696static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
697 Timer *t = TIMER(u);
698
699 assert(u);
700 assert(key);
701 assert(value);
702 assert(fds);
703
704 if (streq(key, "state")) {
705 TimerState state;
706
36697dc0
LP
707 state = timer_state_from_string(value);
708 if (state < 0)
f2341e0a 709 log_unit_debug(u, "Failed to parse state value: %s", value);
871d7de4
LP
710 else
711 t->deserialized_state = state;
d68c645b 712
067d72c9
LP
713 } else if (streq(key, "result")) {
714 TimerResult f;
715
716 f = timer_result_from_string(value);
717 if (f < 0)
f2341e0a 718 log_unit_debug(u, "Failed to parse result value: %s", value);
067d72c9
LP
719 else if (f != TIMER_SUCCESS)
720 t->result = f;
06642d17 721
d68c645b
LP
722 } else if (streq(key, "last-trigger-realtime"))
723 (void) deserialize_usec(value, &t->last_trigger.realtime);
724 else if (streq(key, "last-trigger-monotonic"))
725 (void) deserialize_usec(value, &t->last_trigger.monotonic);
726 else
f2341e0a 727 log_unit_debug(u, "Unknown serialization key: %s", key);
871d7de4
LP
728
729 return 0;
034c6ed7
LP
730}
731
44a6b1b6 732_pure_ static UnitActiveState timer_active_state(Unit *u) {
871d7de4
LP
733 assert(u);
734
735 return state_translation_table[TIMER(u)->state];
736}
737
44a6b1b6 738_pure_ static const char *timer_sub_state_to_string(Unit *u) {
871d7de4
LP
739 assert(u);
740
741 return timer_state_to_string(TIMER(u)->state);
742}
743
718db961
LP
744static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
745 Timer *t = TIMER(userdata);
871d7de4
LP
746
747 assert(t);
5cb5a6ff 748
871d7de4 749 if (t->state != TIMER_WAITING)
718db961 750 return 0;
5cb5a6ff 751
f2341e0a 752 log_unit_debug(UNIT(t), "Timer elapsed.");
871d7de4 753 timer_enter_running(t);
718db961 754 return 0;
5cb5a6ff
LP
755}
756
3ecaa09b
LP
757static void timer_trigger_notify(Unit *u, Unit *other) {
758 Timer *t = TIMER(u);
759 TimerValue *v;
871d7de4 760
3ecaa09b
LP
761 assert(u);
762 assert(other);
871d7de4 763
0377cd29
LP
764 /* Filter out invocations with bogus state */
765 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
871d7de4 766
3ecaa09b
LP
767 /* Reenable all timers that depend on unit state */
768 LIST_FOREACH(value, v, t->values)
3742095b 769 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
3ecaa09b 770 v->disabled = false;
01f78473 771
3ecaa09b 772 switch (t->state) {
871d7de4 773
3ecaa09b
LP
774 case TIMER_WAITING:
775 case TIMER_ELAPSED:
871d7de4 776
3ecaa09b 777 /* Recalculate sleep time */
aa1f95d2 778 timer_enter_waiting(t, false);
3ecaa09b 779 break;
871d7de4 780
3ecaa09b 781 case TIMER_RUNNING:
871d7de4 782
3ecaa09b 783 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
f2341e0a 784 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
aa1f95d2 785 timer_enter_waiting(t, false);
3ecaa09b
LP
786 }
787 break;
871d7de4 788
3ecaa09b
LP
789 case TIMER_DEAD:
790 case TIMER_FAILED:
791 break;
871d7de4 792
3ecaa09b 793 default:
04499a70 794 assert_not_reached();
871d7de4 795 }
871d7de4
LP
796}
797
fdf20a31 798static void timer_reset_failed(Unit *u) {
5632e374
LP
799 Timer *t = TIMER(u);
800
801 assert(t);
802
fdf20a31 803 if (t->state == TIMER_FAILED)
5632e374
LP
804 timer_set_state(t, TIMER_DEAD);
805
067d72c9 806 t->result = TIMER_SUCCESS;
5632e374
LP
807}
808
8742514c
LP
809static void timer_time_change(Unit *u) {
810 Timer *t = TIMER(u);
13f512d3 811 usec_t ts;
8742514c
LP
812
813 assert(u);
814
815 if (t->state != TIMER_WAITING)
816 return;
817
13f512d3
AJ
818 /* If we appear to have triggered in the future, the system clock must
819 * have been set backwards. So let's rewind our own clock and allow
820 * the future trigger(s) to happen again :). Exactly the same as when
821 * you start a timer unit with Persistent=yes. */
822 ts = now(CLOCK_REALTIME);
823 if (t->last_trigger.realtime > ts)
824 t->last_trigger.realtime = ts;
825
efebb613
LP
826 if (t->on_clock_change) {
827 log_unit_debug(u, "Time change, triggering activation.");
828 timer_enter_running(t);
829 } else {
830 log_unit_debug(u, "Time change, recalculating next elapse.");
831 timer_enter_waiting(t, true);
832 }
8742514c
LP
833}
834
bbf5fd8e
LP
835static void timer_timezone_change(Unit *u) {
836 Timer *t = TIMER(u);
837
838 assert(u);
839
840 if (t->state != TIMER_WAITING)
841 return;
842
efebb613
LP
843 if (t->on_timezone_change) {
844 log_unit_debug(u, "Timezone change, triggering activation.");
845 timer_enter_running(t);
846 } else {
847 log_unit_debug(u, "Timezone change, recalculating next elapse.");
848 timer_enter_waiting(t, false);
849 }
bbf5fd8e
LP
850}
851
89f6fe7b
LP
852static int timer_clean(Unit *u, ExecCleanMask mask) {
853 Timer *t = TIMER(u);
854 int r;
855
856 assert(t);
857 assert(mask != 0);
858
859 if (t->state != TIMER_DEAD)
860 return -EBUSY;
861
862 if (!IN_SET(mask, EXEC_CLEAN_STATE))
863 return -EUNATCH;
864
865 r = timer_setup_persistent(t);
866 if (r < 0)
867 return r;
868
869 if (!t->stamp_path)
870 return -EUNATCH;
871
872 if (unlink(t->stamp_path) && errno != ENOENT)
873 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
874
875 return 0;
876}
877
878static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
879 Timer *t = TIMER(u);
880
881 assert(t);
882
883 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
884 return 0;
885}
886
705578c3 887static int timer_can_start(Unit *u) {
9727f242
DDM
888 Timer *t = TIMER(u);
889 int r;
890
891 assert(t);
892
893 r = unit_test_start_limit(u);
894 if (r < 0) {
895 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
896 return r;
897 }
898
705578c3 899 return 1;
9727f242
DDM
900}
901
871d7de4 902static const char* const timer_base_table[_TIMER_BASE_MAX] = {
48d83e33
ZJS
903 [TIMER_ACTIVE] = "OnActiveSec",
904 [TIMER_BOOT] = "OnBootSec",
905 [TIMER_STARTUP] = "OnStartupSec",
906 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
36697dc0 907 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
48d83e33 908 [TIMER_CALENDAR] = "OnCalendar"
871d7de4
LP
909};
910
911DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
912
067d72c9 913static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
40f41f34
DDM
914 [TIMER_SUCCESS] = "success",
915 [TIMER_FAILURE_RESOURCES] = "resources",
916 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
067d72c9
LP
917};
918
919DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
920
87f0e418 921const UnitVTable timer_vtable = {
7d17cfbc 922 .object_size = sizeof(Timer),
718db961 923
f975e971
LP
924 .sections =
925 "Unit\0"
926 "Timer\0"
927 "Install\0",
d8a812d1 928 .private_section = "Timer",
5cb5a6ff 929
c80a9a33
LP
930 .can_transient = true,
931 .can_fail = true,
932 .can_trigger = true,
933
871d7de4 934 .init = timer_init,
034c6ed7 935 .done = timer_done,
871d7de4
LP
936 .load = timer_load,
937
938 .coldplug = timer_coldplug,
939
940 .dump = timer_dump,
941
942 .start = timer_start,
943 .stop = timer_stop,
944
89f6fe7b
LP
945 .clean = timer_clean,
946 .can_clean = timer_can_clean,
947
871d7de4
LP
948 .serialize = timer_serialize,
949 .deserialize_item = timer_deserialize_item,
950
951 .active_state = timer_active_state,
952 .sub_state_to_string = timer_sub_state_to_string,
953
3ecaa09b
LP
954 .trigger_notify = timer_trigger_notify,
955
fdf20a31 956 .reset_failed = timer_reset_failed,
8742514c 957 .time_change = timer_time_change,
bbf5fd8e 958 .timezone_change = timer_timezone_change,
5632e374 959
d8a812d1 960 .bus_set_property = bus_timer_set_property,
9727f242 961
705578c3 962 .can_start = timer_can_start,
5cb5a6ff 963};