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