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