]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/timer.c
man/systemd-sysext: list ephemeral/ephemeral-import in the list of options
[thirdparty/systemd.git] / src / core / timer.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
836e4e7e 3#include <stdlib.h>
ca78ad1d 4#include <sys/stat.h>
ca78ad1d
ZJS
5#include <unistd.h>
6
836e4e7e
DDM
7#include "sd-bus.h"
8
b5efdb8a 9#include "alloc-util.h"
07630cea 10#include "bus-error.h"
836e4e7e 11#include "calendarspec.h"
871d7de4 12#include "dbus-timer.h"
6fcbec6f 13#include "dbus-unit.h"
f4f15635 14#include "fs-util.h"
4ea4abb6 15#include "manager.h"
744c7693 16#include "random-util.h"
d68c645b 17#include "serialize.h"
836e4e7e 18#include "siphash24.h"
a40eb732 19#include "special.h"
8b43440b 20#include "string-table.h"
07630cea 21#include "string-util.h"
836e4e7e 22#include "strv.h"
b1d4f8e1 23#include "timer.h"
07630cea 24#include "unit.h"
b1d4f8e1 25#include "user-util.h"
c1d9ba99 26#include "virt.h"
871d7de4
LP
27
28static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
17f6b640 29 [TIMER_DEAD] = UNIT_INACTIVE,
871d7de4
LP
30 [TIMER_WAITING] = UNIT_ACTIVE,
31 [TIMER_RUNNING] = UNIT_ACTIVE,
32 [TIMER_ELAPSED] = UNIT_ACTIVE,
17f6b640 33 [TIMER_FAILED] = UNIT_FAILED,
871d7de4
LP
34};
35
718db961
LP
36static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
37
871d7de4 38static void timer_init(Unit *u) {
e9fa1bf7 39 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 40
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;
c9e120e0 45 t->accuracy_usec = u->manager->defaults.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
52e3671b 54 while ((v = LIST_POP(value, t->values))) {
3e044c49 55 calendar_spec_free(v->calendar_spec);
871d7de4
LP
56 free(v);
57 }
74051b9b
LP
58}
59
60static void timer_done(Unit *u) {
e9fa1bf7 61 Timer *t = ASSERT_PTR(TIMER(u));
74051b9b
LP
62
63 timer_free_values(t);
871d7de4 64
5dcadb4c
ZJS
65 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
66 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
06642d17 67
756491af 68 t->stamp_path = mfree(t->stamp_path);
871d7de4
LP
69}
70
71static int timer_verify(Timer *t) {
72 assert(t);
75193d41 73 assert(UNIT(t)->load_state == UNIT_LOADED);
871d7de4 74
d85ff944
YW
75 if (!t->values && !t->on_clock_change && !t->on_timezone_change)
76 return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
871d7de4
LP
77
78 return 0;
79}
80
6c155fe3
LP
81static int timer_add_default_dependencies(Timer *t) {
82 int r;
83
84 assert(t);
85
4c9ea260
LP
86 if (!UNIT(t)->default_dependencies)
87 return 0;
88
35d8c19a 89 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721
LP
90 if (r < 0)
91 return r;
2a77d31d 92
463d0d15 93 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
3835b9aa 94 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
36697dc0 95 if (r < 0)
6c155fe3 96 return r;
19f8d037 97
fe934b42 98 LIST_FOREACH(value, v, t->values) {
fe934b42
LP
99 if (v->base != TIMER_CALENDAR)
100 continue;
101
102 FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
103 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
19f8d037
TGR
104 if (r < 0)
105 return r;
19f8d037 106 }
fe934b42
LP
107
108 break;
109 }
2a77d31d 110 }
6c155fe3 111
3835b9aa 112 return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
eef85c4a
LP
113}
114
115static int timer_add_trigger_dependencies(Timer *t) {
116 Unit *x;
117 int r;
118
119 assert(t);
120
bc32241e 121 if (UNIT_TRIGGER(UNIT(t)))
eef85c4a
LP
122 return 0;
123
124 r = unit_load_related_unit(UNIT(t), ".service", &x);
125 if (r < 0)
126 return r;
127
128 return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
6c155fe3
LP
129}
130
06642d17 131static int timer_setup_persistent(Timer *t) {
d3ab7b80 132 _cleanup_free_ char *stamp_path = NULL;
06642d17
LP
133 int r;
134
135 assert(t);
136
137 if (!t->persistent)
138 return 0;
139
463d0d15 140 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
06642d17 141
9e615fa3 142 r = unit_add_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
06642d17
LP
143 if (r < 0)
144 return r;
145
d3ab7b80 146 stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
147 } else {
148 const char *e;
149
150 e = getenv("XDG_DATA_HOME");
151 if (e)
d3ab7b80 152 stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
153 else {
154
155 _cleanup_free_ char *h = NULL;
156
157 r = get_home_dir(&h);
23bbb0de 158 if (r < 0)
f2341e0a 159 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
06642d17 160
d3ab7b80 161 stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
162 }
163 }
164
d3ab7b80 165 if (!stamp_path)
06642d17
LP
166 return log_oom();
167
d3ab7b80 168 return free_and_replace(t->stamp_path, stamp_path);
06642d17
LP
169}
170
acf24a1a
KG
171static uint64_t timer_get_fixed_delay_hash(Timer *t) {
172 static const uint8_t hash_key[] = {
173 0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
174 0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
175 };
176
177 struct siphash state;
178 sd_id128_t machine_id;
179 uid_t uid;
180 int r;
181
182 assert(t);
183
184 uid = getuid();
185 r = sd_id128_get_machine(&machine_id);
186 if (r < 0) {
187 log_unit_debug_errno(UNIT(t), r,
188 "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
189 machine_id = SD_ID128_NULL;
190 }
191
192 siphash24_init(&state, hash_key);
c01a5c05 193 siphash24_compress_typesafe(machine_id, &state);
acf24a1a 194 siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
c01a5c05 195 siphash24_compress_typesafe(uid, &state);
acf24a1a
KG
196 siphash24_compress_string(UNIT(t)->id, &state);
197
198 return siphash24_finalize(&state);
199}
200
871d7de4 201static int timer_load(Unit *u) {
e9fa1bf7 202 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4
LP
203 int r;
204
ac155bb8 205 assert(u->load_state == UNIT_STUB);
871d7de4 206
c3620770 207 r = unit_load_fragment_and_dropin(u, true);
36697dc0 208 if (r < 0)
871d7de4
LP
209 return r;
210
75193d41
ZJS
211 if (u->load_state != UNIT_LOADED)
212 return 0;
871d7de4 213
75193d41
ZJS
214 /* This is a new unit? Then let's add in some extras */
215 r = timer_add_trigger_dependencies(t);
216 if (r < 0)
217 return r;
57020a3a 218
75193d41
ZJS
219 r = timer_setup_persistent(t);
220 if (r < 0)
221 return r;
06642d17 222
75193d41
ZJS
223 r = timer_add_default_dependencies(t);
224 if (r < 0)
225 return r;
871d7de4
LP
226
227 return timer_verify(t);
228}
229
230static void timer_dump(Unit *u, FILE *f, const char *prefix) {
e9fa1bf7 231 Timer *t = ASSERT_PTR(TIMER(u));
3ecaa09b 232 Unit *trigger;
034c6ed7 233
e9fa1bf7
MY
234 assert(f);
235 assert(prefix);
236
3ecaa09b
LP
237 trigger = UNIT_TRIGGER(u);
238
871d7de4
LP
239 fprintf(f,
240 "%sTimer State: %s\n"
067d72c9 241 "%sResult: %s\n"
9f5eb56a 242 "%sUnit: %s\n"
dedabea4
LP
243 "%sPersistent: %s\n"
244 "%sWakeSystem: %s\n"
3e0c30ac 245 "%sAccuracy: %s\n"
efebb613 246 "%sRemainAfterElapse: %s\n"
acf24a1a 247 "%sFixedRandomDelay: %s\n"
efebb613 248 "%sOnClockChange: %s\n"
cc0ab8c8
AS
249 "%sOnTimeZoneChange: %s\n"
250 "%sDeferReactivation: %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 259 prefix, yes_no(t->on_clock_change),
cc0ab8c8
AS
260 prefix, yes_no(t->on_timezone_change),
261 prefix, yes_no(t->defer_reactivation));
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;
e9fa1bf7 284
034c6ed7 285 assert(t);
871d7de4 286
6fcbec6f
LP
287 if (t->state != state)
288 bus_unit_send_pending_change_signal(UNIT(t), false);
289
871d7de4
LP
290 old_state = t->state;
291 t->state = state;
292
36697dc0 293 if (state != TIMER_WAITING) {
5dcadb4c
ZJS
294 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
295 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
6e2c9ce1
ZJS
296 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
297 t->next_elapse_realtime = USEC_INFINITY;
36697dc0 298 }
871d7de4
LP
299
300 if (state != old_state)
f2341e0a 301 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
871d7de4 302
96b09de5 303 unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
871d7de4
LP
304}
305
aa1f95d2 306static void timer_enter_waiting(Timer *t, bool time_change);
871d7de4 307
be847e82 308static int timer_coldplug(Unit *u) {
e9fa1bf7 309 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 310
871d7de4
LP
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
9a0749c8 351static void add_random_delay(Timer *t, usec_t *v) {
744c7693
LP
352 usec_t add;
353
354 assert(t);
3f51aec8 355 assert(v);
744c7693 356
9a0749c8 357 if (t->random_delay_usec == 0)
744c7693
LP
358 return;
359 if (*v == USEC_INFINITY)
360 return;
361
9a0749c8 362 add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_delay_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.");
e7912a08 384 goto fail;
e903182e
LP
385 }
386
fa5a0251 387 triple_timestamp_now(&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) {
9a0749c8
AV
395 usec_t b, rebased, random_offset = 0;
396
397 if (t->random_offset_usec != 0)
398 random_offset = timer_get_fixed_delay_hash(t) % t->random_offset_usec;
06642d17 399
cc0ab8c8
AS
400 /* If DeferReactivation= is enabled, schedule the job based on the last time
401 * the trigger unit entered inactivity. Otherwise, if we know the last time
402 * this was triggered, schedule the job based relative to that. If we don't,
9a0749c8
AV
403 * just start from the activation time or realtime.
404 *
405 * Unless we have a real last-trigger time, we subtract the random_offset because
406 * any event that elapsed within the last random_offset has actually been delayed
407 * and thus hasn't truly elapsed yet. */
cc0ab8c8
AS
408
409 if (t->defer_reactivation &&
410 dual_timestamp_is_set(&trigger->inactive_enter_timestamp)) {
411 if (dual_timestamp_is_set(&t->last_trigger))
412 b = MAX(trigger->inactive_enter_timestamp.realtime,
413 t->last_trigger.realtime);
414 else
415 b = trigger->inactive_enter_timestamp.realtime;
416 } else if (dual_timestamp_is_set(&t->last_trigger))
9ea9faff 417 b = t->last_trigger.realtime;
6546045f 418 else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
9a0749c8 419 b = UNIT(t)->inactive_exit_timestamp.realtime - random_offset;
6546045f 420 else
9a0749c8 421 b = ts.realtime - random_offset;
06642d17
LP
422
423 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
36697dc0
LP
424 if (r < 0)
425 continue;
426
9a0749c8
AV
427 v->next_elapse += random_offset;
428
58afc4f8
LP
429 /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
430 * time has already passed, set the time when systemd first started as the scheduled
431 * time. Note that we base this on the monotonic timestamp of the boot, not the
432 * realtime one, since the wallclock might have been off during boot. */
433 rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
434 CLOCK_MONOTONIC, CLOCK_REALTIME);
435 if (v->next_elapse < rebased)
436 v->next_elapse = rebased;
a87c1d3a 437
36697dc0
LP
438 if (!found_realtime)
439 t->next_elapse_realtime = v->next_elapse;
10717a1a 440 else
36697dc0 441 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
871d7de4 442
36697dc0 443 found_realtime = true;
871d7de4 444
60933bb8
AJ
445 } else {
446 usec_t base;
c54be90b 447
36697dc0 448 switch (v->base) {
871d7de4 449
36697dc0
LP
450 case TIMER_ACTIVE:
451 if (state_translation_table[t->state] == UNIT_ACTIVE)
452 base = UNIT(t)->inactive_exit_timestamp.monotonic;
453 else
c54be90b 454 base = ts.monotonic;
36697dc0 455 break;
871d7de4 456
36697dc0 457 case TIMER_BOOT:
c1d9ba99
MS
458 if (detect_container() <= 0) {
459 /* CLOCK_MONOTONIC equals the uptime on Linux */
460 base = 0;
461 break;
462 }
463 /* In a container we don't want to include the time the host
464 * was already up when the container started, so count from
ec251fe7 465 * our own startup. */
4831981d 466 _fallthrough_;
36697dc0 467 case TIMER_STARTUP:
9f9f0342 468 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
36697dc0 469 break;
871d7de4 470
36697dc0 471 case TIMER_UNIT_ACTIVE:
3e0c30ac 472 leave_around = true;
525b95f1 473 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 474 if (base <= 0)
36697dc0 475 continue;
36697dc0 476 break;
871d7de4 477
36697dc0 478 case TIMER_UNIT_INACTIVE:
3e0c30ac 479 leave_around = true;
525b95f1 480 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 481 if (base <= 0)
36697dc0 482 continue;
36697dc0 483 break;
871d7de4 484
36697dc0 485 default:
04499a70 486 assert_not_reached();
36697dc0 487 }
871d7de4 488
bed9d258
F
489 if (!time_change)
490 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
36697dc0 491
aa1f95d2
MK
492 if (dual_timestamp_is_set(&t->last_trigger) &&
493 !time_change &&
c54be90b
LP
494 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
495 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
e41e1943 496 /* This is a one time trigger, disable it now */
36697dc0
LP
497 v->disabled = true;
498 continue;
499 }
500
501 if (!found_monotonic)
dedabea4 502 t->next_elapse_monotonic_or_boottime = v->next_elapse;
36697dc0 503 else
dedabea4 504 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
36697dc0
LP
505
506 found_monotonic = true;
507 }
871d7de4
LP
508 }
509
efebb613 510 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
f2341e0a 511 log_unit_debug(UNIT(t), "Timer is elapsed.");
3e0c30ac 512 timer_enter_elapsed(t, leave_around);
871d7de4
LP
513 return;
514 }
515
36697dc0 516 if (found_monotonic) {
3e0c30ac 517 usec_t left;
dedabea4 518
9a0749c8 519 add_random_delay(t, &t->next_elapse_monotonic_or_boottime);
744c7693 520
c54be90b 521 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
5291f26d 522 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
871d7de4 523
718db961 524 if (t->monotonic_event_source) {
dedabea4 525 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
e7912a08
LP
526 if (r < 0) {
527 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule monotonic event source: %m");
718db961 528 goto fail;
e7912a08 529 }
718db961
LP
530
531 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
e7912a08
LP
532 if (r < 0) {
533 log_unit_warning_errno(UNIT(t), r, "Failed to enable monotonic event source: %m");
cbf60d0a 534 goto fail;
e7912a08 535 }
cbf60d0a 536 } else {
6a0f1f6d
LP
537 r = sd_event_add_time(
538 UNIT(t)->manager->event,
539 &t->monotonic_event_source,
dedabea4
LP
540 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
541 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
6a0f1f6d 542 timer_dispatch, t);
e7912a08
LP
543 if (r < 0) {
544 log_unit_warning_errno(UNIT(t), r, "Failed to add monotonic event source: %m");
cbf60d0a 545 goto fail;
e7912a08 546 }
718db961 547
cbf60d0a
LP
548 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
549 }
7dfbe2e3 550
a3ada90a 551 } else {
06642d17 552 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
e7912a08
LP
553 if (r < 0) {
554 log_unit_warning_errno(UNIT(t), r, "Failed to disable monotonic event source: %m");
718db961 555 goto fail;
e7912a08 556 }
718db961 557 }
36697dc0
LP
558
559 if (found_realtime) {
9a0749c8 560 add_random_delay(t, &t->next_elapse_realtime);
744c7693 561
04f5c018 562 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
36697dc0 563
718db961
LP
564 if (t->realtime_event_source) {
565 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
e7912a08
LP
566 if (r < 0) {
567 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule realtime event source: %m");
718db961 568 goto fail;
e7912a08 569 }
718db961
LP
570
571 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
e7912a08
LP
572 if (r < 0) {
573 log_unit_warning_errno(UNIT(t), r, "Failed to enable realtime event source: %m");
cbf60d0a 574 goto fail;
e7912a08 575 }
cbf60d0a 576 } else {
6a0f1f6d
LP
577 r = sd_event_add_time(
578 UNIT(t)->manager->event,
579 &t->realtime_event_source,
dedabea4 580 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
6a0f1f6d
LP
581 t->next_elapse_realtime, t->accuracy_usec,
582 timer_dispatch, t);
e7912a08
LP
583 if (r < 0) {
584 log_unit_warning_errno(UNIT(t), r, "Failed to add realtime event source: %m");
cbf60d0a 585 goto fail;
e7912a08 586 }
718db961 587
cbf60d0a
LP
588 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
589 }
7dfbe2e3 590
718db961 591 } else if (t->realtime_event_source) {
718db961 592
06642d17 593 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
e7912a08
LP
594 if (r < 0) {
595 log_unit_warning_errno(UNIT(t), r, "Failed to disable realtime event source: %m");
718db961 596 goto fail;
e7912a08 597 }
718db961 598 }
871d7de4
LP
599
600 timer_set_state(t, TIMER_WAITING);
601 return;
602
603fail:
067d72c9 604 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
605}
606
607static void timer_enter_running(Timer *t) {
c8bc7519 608 _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
4afd3348 609 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e903182e 610 Unit *trigger;
c8bc7519 611 Job *job;
871d7de4 612 int r;
398ef8ba 613
871d7de4
LP
614 assert(t);
615
ba3e67a7 616 /* Don't start job if we are supposed to go down */
31afa0a4 617 if (unit_stop_pending(UNIT(t)))
ba3e67a7
LP
618 return;
619
e903182e
LP
620 trigger = UNIT_TRIGGER(UNIT(t));
621 if (!trigger) {
622 log_unit_error(UNIT(t), "Unit to trigger vanished.");
e7912a08 623 goto fail;
e903182e
LP
624 }
625
c8bc7519
LB
626 details = activation_details_new(UNIT(t));
627 if (!details) {
e7912a08 628 log_oom();
c8bc7519
LB
629 goto fail;
630 }
631
d993ad6c 632 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, &error, &job);
e7912a08
LP
633 if (r < 0) {
634 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
871d7de4 635 goto fail;
e7912a08 636 }
871d7de4 637
fa5a0251 638 dual_timestamp_now(&t->last_trigger);
c8bc7519
LB
639 ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
640
641 job_set_activation_details(job, details);
06642d17 642
472fc28f 643 if (t->stamp_path)
ee735086 644 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
e41e1943 645
871d7de4
LP
646 timer_set_state(t, TIMER_RUNNING);
647 return;
648
649fail:
067d72c9 650 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
651}
652
653static int timer_start(Unit *u) {
e9fa1bf7 654 Timer *t = ASSERT_PTR(TIMER(u));
07299350 655 int r;
871d7de4 656
3742095b 657 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
01f78473 658
a4191c9f
LP
659 r = unit_test_trigger_loaded(u);
660 if (r < 0)
661 return r;
871d7de4 662
4b58153d
LP
663 r = unit_acquire_invocation_id(u);
664 if (r < 0)
665 return r;
666
06642d17
LP
667 t->last_trigger = DUAL_TIMESTAMP_NULL;
668
779042e7
MC
669 /* Reenable all timers that depend on unit activation time */
670 LIST_FOREACH(value, v, t->values)
671 if (v->base == TIMER_ACTIVE)
672 v->disabled = false;
673
06642d17
LP
674 if (t->stamp_path) {
675 struct stat st;
676
77542a79
LP
677 if (stat(t->stamp_path, &st) >= 0) {
678 usec_t ft;
679
680 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
681 * something is wrong with the system clock. */
682
683 ft = timespec_load(&st.st_mtim);
684 if (ft < now(CLOCK_REALTIME))
685 t->last_trigger.realtime = ft;
04f5c018 686 else
77542a79 687 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
04f5c018 688 FORMAT_TIMESTAMP(ft));
77542a79
LP
689
690 } else if (errno == ENOENT)
2762ce2d 691 /* The timer has never run before, make sure a stamp file exists. */
4b58153d 692 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
06642d17
LP
693 }
694
067d72c9 695 t->result = TIMER_SUCCESS;
aa1f95d2 696 timer_enter_waiting(t, false);
82a2b6bb 697 return 1;
871d7de4
LP
698}
699
700static int timer_stop(Unit *u) {
e9fa1bf7 701 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 702
3742095b 703 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
871d7de4 704
067d72c9 705 timer_enter_dead(t, TIMER_SUCCESS);
82a2b6bb 706 return 1;
871d7de4
LP
707}
708
709static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
e9fa1bf7 710 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 711
871d7de4
LP
712 assert(f);
713 assert(fds);
714
d68c645b
LP
715 (void) serialize_item(f, "state", timer_state_to_string(t->state));
716 (void) serialize_item(f, "result", timer_result_to_string(t->result));
871d7de4 717
eba1cf56 718 if (dual_timestamp_is_set(&t->last_trigger))
d68c645b 719 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
06642d17
LP
720
721 if (t->last_trigger.monotonic > 0)
d68c645b 722 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
06642d17 723
871d7de4
LP
724 return 0;
725}
726
727static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
e9fa1bf7 728 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 729
871d7de4
LP
730 assert(key);
731 assert(value);
732 assert(fds);
733
734 if (streq(key, "state")) {
735 TimerState state;
736
36697dc0
LP
737 state = timer_state_from_string(value);
738 if (state < 0)
f2341e0a 739 log_unit_debug(u, "Failed to parse state value: %s", value);
871d7de4
LP
740 else
741 t->deserialized_state = state;
d68c645b 742
067d72c9
LP
743 } else if (streq(key, "result")) {
744 TimerResult f;
745
746 f = timer_result_from_string(value);
747 if (f < 0)
f2341e0a 748 log_unit_debug(u, "Failed to parse result value: %s", value);
067d72c9
LP
749 else if (f != TIMER_SUCCESS)
750 t->result = f;
06642d17 751
d68c645b
LP
752 } else if (streq(key, "last-trigger-realtime"))
753 (void) deserialize_usec(value, &t->last_trigger.realtime);
754 else if (streq(key, "last-trigger-monotonic"))
755 (void) deserialize_usec(value, &t->last_trigger.monotonic);
756 else
f2341e0a 757 log_unit_debug(u, "Unknown serialization key: %s", key);
871d7de4
LP
758
759 return 0;
034c6ed7
LP
760}
761
d1e8e8b5 762static UnitActiveState timer_active_state(Unit *u) {
e9fa1bf7 763 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 764
e9fa1bf7 765 return state_translation_table[t->state];
871d7de4
LP
766}
767
d1e8e8b5 768static const char *timer_sub_state_to_string(Unit *u) {
e9fa1bf7 769 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 770
e9fa1bf7 771 return timer_state_to_string(t->state);
871d7de4
LP
772}
773
718db961 774static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
e9fa1bf7 775 Timer *t = ASSERT_PTR(TIMER(userdata));
5cb5a6ff 776
871d7de4 777 if (t->state != TIMER_WAITING)
718db961 778 return 0;
5cb5a6ff 779
f2341e0a 780 log_unit_debug(UNIT(t), "Timer elapsed.");
871d7de4 781 timer_enter_running(t);
718db961 782 return 0;
5cb5a6ff
LP
783}
784
3ecaa09b 785static void timer_trigger_notify(Unit *u, Unit *other) {
e9fa1bf7 786 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 787
3ecaa09b 788 assert(other);
871d7de4 789
0377cd29
LP
790 /* Filter out invocations with bogus state */
791 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
871d7de4 792
3ecaa09b
LP
793 /* Reenable all timers that depend on unit state */
794 LIST_FOREACH(value, v, t->values)
3742095b 795 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
3ecaa09b 796 v->disabled = false;
01f78473 797
3ecaa09b 798 switch (t->state) {
871d7de4 799
3ecaa09b
LP
800 case TIMER_WAITING:
801 case TIMER_ELAPSED:
871d7de4 802
3ecaa09b 803 /* Recalculate sleep time */
aa1f95d2 804 timer_enter_waiting(t, false);
3ecaa09b 805 break;
871d7de4 806
3ecaa09b 807 case TIMER_RUNNING:
871d7de4 808
3ecaa09b 809 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
f2341e0a 810 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
aa1f95d2 811 timer_enter_waiting(t, false);
3ecaa09b
LP
812 }
813 break;
871d7de4 814
3ecaa09b
LP
815 case TIMER_DEAD:
816 case TIMER_FAILED:
817 break;
871d7de4 818
3ecaa09b 819 default:
04499a70 820 assert_not_reached();
871d7de4 821 }
871d7de4
LP
822}
823
fdf20a31 824static void timer_reset_failed(Unit *u) {
e9fa1bf7 825 Timer *t = ASSERT_PTR(TIMER(u));
5632e374 826
fdf20a31 827 if (t->state == TIMER_FAILED)
5632e374
LP
828 timer_set_state(t, TIMER_DEAD);
829
067d72c9 830 t->result = TIMER_SUCCESS;
5632e374
LP
831}
832
8742514c 833static void timer_time_change(Unit *u) {
e9fa1bf7 834 Timer *t = ASSERT_PTR(TIMER(u));
13f512d3 835 usec_t ts;
8742514c 836
8742514c
LP
837 if (t->state != TIMER_WAITING)
838 return;
839
13f512d3
AJ
840 /* If we appear to have triggered in the future, the system clock must
841 * have been set backwards. So let's rewind our own clock and allow
0923b425 842 * the future triggers to happen again :). Exactly the same as when
13f512d3
AJ
843 * you start a timer unit with Persistent=yes. */
844 ts = now(CLOCK_REALTIME);
845 if (t->last_trigger.realtime > ts)
846 t->last_trigger.realtime = ts;
847
efebb613
LP
848 if (t->on_clock_change) {
849 log_unit_debug(u, "Time change, triggering activation.");
850 timer_enter_running(t);
851 } else {
852 log_unit_debug(u, "Time change, recalculating next elapse.");
853 timer_enter_waiting(t, true);
854 }
8742514c
LP
855}
856
bbf5fd8e 857static void timer_timezone_change(Unit *u) {
e9fa1bf7 858 Timer *t = ASSERT_PTR(TIMER(u));
bbf5fd8e
LP
859
860 if (t->state != TIMER_WAITING)
861 return;
862
efebb613
LP
863 if (t->on_timezone_change) {
864 log_unit_debug(u, "Timezone change, triggering activation.");
865 timer_enter_running(t);
866 } else {
867 log_unit_debug(u, "Timezone change, recalculating next elapse.");
868 timer_enter_waiting(t, false);
869 }
bbf5fd8e
LP
870}
871
89f6fe7b 872static int timer_clean(Unit *u, ExecCleanMask mask) {
e9fa1bf7 873 Timer *t = ASSERT_PTR(TIMER(u));
89f6fe7b
LP
874 int r;
875
89f6fe7b
LP
876 assert(mask != 0);
877
878 if (t->state != TIMER_DEAD)
879 return -EBUSY;
880
4f06325c 881 if (mask != EXEC_CLEAN_STATE)
89f6fe7b
LP
882 return -EUNATCH;
883
884 r = timer_setup_persistent(t);
885 if (r < 0)
886 return r;
887
888 if (!t->stamp_path)
889 return -EUNATCH;
890
891 if (unlink(t->stamp_path) && errno != ENOENT)
892 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
893
894 return 0;
895}
896
897static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
e9fa1bf7 898 Timer *t = ASSERT_PTR(TIMER(u));
89f6fe7b 899
4fb8f1e8 900 assert(ret);
89f6fe7b
LP
901
902 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
903 return 0;
904}
905
705578c3 906static int timer_can_start(Unit *u) {
e9fa1bf7 907 Timer *t = ASSERT_PTR(TIMER(u));
9727f242
DDM
908 int r;
909
9727f242
DDM
910 r = unit_test_start_limit(u);
911 if (r < 0) {
912 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
913 return r;
914 }
915
705578c3 916 return 1;
9727f242
DDM
917}
918
acca52ab
DDM
919static void activation_details_timer_serialize(const ActivationDetails *details, FILE *f) {
920 const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519 921
c8bc7519
LB
922 assert(f);
923 assert(t);
924
925 (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
926}
927
928static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
929 int r;
930
931 assert(key);
932 assert(value);
933
934 if (!details || !*details)
935 return -EINVAL;
936
937 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
938 if (!t)
939 return -EINVAL;
940
941 if (!streq(key, "activation-details-timer-last-trigger"))
942 return -EINVAL;
943
944 r = deserialize_dual_timestamp(value, &t->last_trigger);
945 if (r < 0)
946 return r;
947
948 return 0;
949}
950
acca52ab
DDM
951static int activation_details_timer_append_env(const ActivationDetails *details, char ***strv) {
952 const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519
LB
953 int r;
954
c8bc7519
LB
955 assert(strv);
956 assert(t);
957
958 if (!dual_timestamp_is_set(&t->last_trigger))
959 return 0;
960
6457ce15 961 r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
962 if (r < 0)
963 return r;
964
6457ce15 965 r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
966 if (r < 0)
967 return r;
968
969 return 2; /* Return the number of variables added to the env block */
970}
971
acca52ab
DDM
972static int activation_details_timer_append_pair(const ActivationDetails *details, char ***strv) {
973 const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519
LB
974 int r;
975
c8bc7519
LB
976 assert(strv);
977 assert(t);
978
979 if (!dual_timestamp_is_set(&t->last_trigger))
980 return 0;
981
982 r = strv_extend(strv, "trigger_timer_realtime_usec");
983 if (r < 0)
984 return r;
985
6457ce15 986 r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
987 if (r < 0)
988 return r;
989
990 r = strv_extend(strv, "trigger_timer_monotonic_usec");
991 if (r < 0)
992 return r;
993
6457ce15 994 r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
995 if (r < 0)
996 return r;
997
998 return 2; /* Return the number of pairs added to the env block */
999}
1000
f8a990a0
DDM
1001uint64_t timer_next_elapse_monotonic(const Timer *t) {
1002 assert(t);
1003
1004 return (uint64_t) usec_shift_clock(t->next_elapse_monotonic_or_boottime,
1005 TIMER_MONOTONIC_CLOCK(t), CLOCK_MONOTONIC);
1006}
1007
871d7de4 1008static const char* const timer_base_table[_TIMER_BASE_MAX] = {
48d83e33
ZJS
1009 [TIMER_ACTIVE] = "OnActiveSec",
1010 [TIMER_BOOT] = "OnBootSec",
1011 [TIMER_STARTUP] = "OnStartupSec",
1012 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
36697dc0 1013 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
17f6b640 1014 [TIMER_CALENDAR] = "OnCalendar",
871d7de4
LP
1015};
1016
1017DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
1018
f8a990a0
DDM
1019char* timer_base_to_usec_string(TimerBase i) {
1020 _cleanup_free_ char *buf = NULL;
1021 const char *s;
1022 size_t l;
1023
1024 s = timer_base_to_string(i);
1025
1026 if (endswith(s, "Sec")) {
1027 /* s/Sec/USec/ */
1028 l = strlen(s);
1029 buf = new(char, l+2);
1030 if (!buf)
1031 return NULL;
1032
1033 memcpy(buf, s, l-3);
1034 memcpy(buf+l-3, "USec", 5);
1035 } else {
1036 buf = strdup(s);
1037 if (!buf)
1038 return NULL;
1039 }
1040
1041 return TAKE_PTR(buf);
1042}
1043
067d72c9 1044static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
40f41f34
DDM
1045 [TIMER_SUCCESS] = "success",
1046 [TIMER_FAILURE_RESOURCES] = "resources",
1047 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
067d72c9
LP
1048};
1049
1050DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1051
87f0e418 1052const UnitVTable timer_vtable = {
7d17cfbc 1053 .object_size = sizeof(Timer),
718db961 1054
f975e971
LP
1055 .sections =
1056 "Unit\0"
1057 "Timer\0"
1058 "Install\0",
d8a812d1 1059 .private_section = "Timer",
5cb5a6ff 1060
c80a9a33
LP
1061 .can_transient = true,
1062 .can_fail = true,
1063 .can_trigger = true,
1064
871d7de4 1065 .init = timer_init,
034c6ed7 1066 .done = timer_done,
871d7de4
LP
1067 .load = timer_load,
1068
1069 .coldplug = timer_coldplug,
1070
1071 .dump = timer_dump,
1072
1073 .start = timer_start,
1074 .stop = timer_stop,
1075
89f6fe7b
LP
1076 .clean = timer_clean,
1077 .can_clean = timer_can_clean,
1078
871d7de4
LP
1079 .serialize = timer_serialize,
1080 .deserialize_item = timer_deserialize_item,
1081
1082 .active_state = timer_active_state,
1083 .sub_state_to_string = timer_sub_state_to_string,
1084
3ecaa09b
LP
1085 .trigger_notify = timer_trigger_notify,
1086
fdf20a31 1087 .reset_failed = timer_reset_failed,
8742514c 1088 .time_change = timer_time_change,
bbf5fd8e 1089 .timezone_change = timer_timezone_change,
5632e374 1090
d8a812d1 1091 .bus_set_property = bus_timer_set_property,
9727f242 1092
705578c3 1093 .can_start = timer_can_start,
5cb5a6ff 1094};
c8bc7519
LB
1095
1096const ActivationDetailsVTable activation_details_timer_vtable = {
1097 .object_size = sizeof(ActivationDetailsTimer),
1098
1099 .serialize = activation_details_timer_serialize,
1100 .deserialize = activation_details_timer_deserialize,
1101 .append_env = activation_details_timer_append_env,
1102 .append_pair = activation_details_timer_append_pair,
1103};