]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/timer.c
core/timer: Always use inactive_exit_timestamp if it is set
[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;
6546045f
DDM
404 else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
405 b = UNIT(t)->inactive_exit_timestamp.realtime;
406 else
407 b = ts.realtime;
06642d17
LP
408
409 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
36697dc0
LP
410 if (r < 0)
411 continue;
412
58afc4f8
LP
413 /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
414 * time has already passed, set the time when systemd first started as the scheduled
415 * time. Note that we base this on the monotonic timestamp of the boot, not the
416 * realtime one, since the wallclock might have been off during boot. */
417 rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
418 CLOCK_MONOTONIC, CLOCK_REALTIME);
419 if (v->next_elapse < rebased)
420 v->next_elapse = rebased;
a87c1d3a 421
36697dc0
LP
422 if (!found_realtime)
423 t->next_elapse_realtime = v->next_elapse;
10717a1a 424 else
36697dc0 425 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
871d7de4 426
36697dc0 427 found_realtime = true;
871d7de4 428
60933bb8
AJ
429 } else {
430 usec_t base;
c54be90b 431
36697dc0 432 switch (v->base) {
871d7de4 433
36697dc0
LP
434 case TIMER_ACTIVE:
435 if (state_translation_table[t->state] == UNIT_ACTIVE)
436 base = UNIT(t)->inactive_exit_timestamp.monotonic;
437 else
c54be90b 438 base = ts.monotonic;
36697dc0 439 break;
871d7de4 440
36697dc0 441 case TIMER_BOOT:
c1d9ba99
MS
442 if (detect_container() <= 0) {
443 /* CLOCK_MONOTONIC equals the uptime on Linux */
444 base = 0;
445 break;
446 }
447 /* In a container we don't want to include the time the host
448 * was already up when the container started, so count from
ec251fe7 449 * our own startup. */
4831981d 450 _fallthrough_;
36697dc0 451 case TIMER_STARTUP:
9f9f0342 452 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
36697dc0 453 break;
871d7de4 454
36697dc0 455 case TIMER_UNIT_ACTIVE:
3e0c30ac 456 leave_around = true;
525b95f1 457 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 458 if (base <= 0)
36697dc0 459 continue;
36697dc0 460 break;
871d7de4 461
36697dc0 462 case TIMER_UNIT_INACTIVE:
3e0c30ac 463 leave_around = true;
525b95f1 464 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 465 if (base <= 0)
36697dc0 466 continue;
36697dc0 467 break;
871d7de4 468
36697dc0 469 default:
04499a70 470 assert_not_reached();
36697dc0 471 }
871d7de4 472
c54be90b 473 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
36697dc0 474
aa1f95d2
MK
475 if (dual_timestamp_is_set(&t->last_trigger) &&
476 !time_change &&
c54be90b
LP
477 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
478 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
e41e1943 479 /* This is a one time trigger, disable it now */
36697dc0
LP
480 v->disabled = true;
481 continue;
482 }
483
484 if (!found_monotonic)
dedabea4 485 t->next_elapse_monotonic_or_boottime = v->next_elapse;
36697dc0 486 else
dedabea4 487 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
36697dc0
LP
488
489 found_monotonic = true;
490 }
871d7de4
LP
491 }
492
efebb613 493 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
f2341e0a 494 log_unit_debug(UNIT(t), "Timer is elapsed.");
3e0c30ac 495 timer_enter_elapsed(t, leave_around);
871d7de4
LP
496 return;
497 }
498
36697dc0 499 if (found_monotonic) {
3e0c30ac 500 usec_t left;
dedabea4 501
744c7693
LP
502 add_random(t, &t->next_elapse_monotonic_or_boottime);
503
c54be90b 504 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
5291f26d 505 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
871d7de4 506
718db961 507 if (t->monotonic_event_source) {
dedabea4 508 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
718db961
LP
509 if (r < 0)
510 goto fail;
511
512 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
513 if (r < 0)
514 goto fail;
515 } else {
516
6a0f1f6d
LP
517 r = sd_event_add_time(
518 UNIT(t)->manager->event,
519 &t->monotonic_event_source,
dedabea4
LP
520 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
521 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
6a0f1f6d 522 timer_dispatch, t);
cbf60d0a
LP
523 if (r < 0)
524 goto fail;
718db961 525
cbf60d0a
LP
526 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
527 }
7dfbe2e3 528
718db961 529 } else if (t->monotonic_event_source) {
718db961 530
06642d17 531 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
718db961
LP
532 if (r < 0)
533 goto fail;
534 }
36697dc0
LP
535
536 if (found_realtime) {
744c7693
LP
537 add_random(t, &t->next_elapse_realtime);
538
04f5c018 539 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
36697dc0 540
718db961
LP
541 if (t->realtime_event_source) {
542 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
543 if (r < 0)
544 goto fail;
545
546 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
547 if (r < 0)
548 goto fail;
549 } else {
6a0f1f6d
LP
550 r = sd_event_add_time(
551 UNIT(t)->manager->event,
552 &t->realtime_event_source,
dedabea4 553 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
6a0f1f6d
LP
554 t->next_elapse_realtime, t->accuracy_usec,
555 timer_dispatch, t);
cbf60d0a
LP
556 if (r < 0)
557 goto fail;
718db961 558
cbf60d0a
LP
559 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
560 }
7dfbe2e3 561
718db961 562 } else if (t->realtime_event_source) {
718db961 563
06642d17 564 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
718db961
LP
565 if (r < 0)
566 goto fail;
567 }
871d7de4
LP
568
569 timer_set_state(t, TIMER_WAITING);
570 return;
571
572fail:
f2341e0a 573 log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m");
067d72c9 574 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
575}
576
577static void timer_enter_running(Timer *t) {
c8bc7519 578 _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
4afd3348 579 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e903182e 580 Unit *trigger;
c8bc7519 581 Job *job;
871d7de4 582 int r;
398ef8ba 583
871d7de4
LP
584 assert(t);
585
ba3e67a7 586 /* Don't start job if we are supposed to go down */
31afa0a4 587 if (unit_stop_pending(UNIT(t)))
ba3e67a7
LP
588 return;
589
e903182e
LP
590 trigger = UNIT_TRIGGER(UNIT(t));
591 if (!trigger) {
592 log_unit_error(UNIT(t), "Unit to trigger vanished.");
593 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
594 return;
595 }
596
c8bc7519
LB
597 details = activation_details_new(UNIT(t));
598 if (!details) {
599 r = -ENOMEM;
600 goto fail;
601 }
602
603 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, &job);
36697dc0 604 if (r < 0)
871d7de4
LP
605 goto fail;
606
06642d17 607 dual_timestamp_get(&t->last_trigger);
c8bc7519
LB
608 ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
609
610 job_set_activation_details(job, details);
06642d17 611
472fc28f 612 if (t->stamp_path)
ee735086 613 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
e41e1943 614
871d7de4
LP
615 timer_set_state(t, TIMER_RUNNING);
616 return;
617
618fail:
f2341e0a 619 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
067d72c9 620 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
621}
622
623static int timer_start(Unit *u) {
624 Timer *t = TIMER(u);
07299350 625 int r;
871d7de4
LP
626
627 assert(t);
3742095b 628 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
01f78473 629
a4191c9f
LP
630 r = unit_test_trigger_loaded(u);
631 if (r < 0)
632 return r;
871d7de4 633
4b58153d
LP
634 r = unit_acquire_invocation_id(u);
635 if (r < 0)
636 return r;
637
06642d17
LP
638 t->last_trigger = DUAL_TIMESTAMP_NULL;
639
779042e7
MC
640 /* Reenable all timers that depend on unit activation time */
641 LIST_FOREACH(value, v, t->values)
642 if (v->base == TIMER_ACTIVE)
643 v->disabled = false;
644
06642d17
LP
645 if (t->stamp_path) {
646 struct stat st;
647
77542a79
LP
648 if (stat(t->stamp_path, &st) >= 0) {
649 usec_t ft;
650
651 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
652 * something is wrong with the system clock. */
653
654 ft = timespec_load(&st.st_mtim);
655 if (ft < now(CLOCK_REALTIME))
656 t->last_trigger.realtime = ft;
04f5c018 657 else
77542a79 658 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
04f5c018 659 FORMAT_TIMESTAMP(ft));
77542a79
LP
660
661 } else if (errno == ENOENT)
2762ce2d 662 /* The timer has never run before, make sure a stamp file exists. */
4b58153d 663 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
06642d17
LP
664 }
665
067d72c9 666 t->result = TIMER_SUCCESS;
aa1f95d2 667 timer_enter_waiting(t, false);
82a2b6bb 668 return 1;
871d7de4
LP
669}
670
671static int timer_stop(Unit *u) {
672 Timer *t = TIMER(u);
673
674 assert(t);
3742095b 675 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
871d7de4 676
067d72c9 677 timer_enter_dead(t, TIMER_SUCCESS);
82a2b6bb 678 return 1;
871d7de4
LP
679}
680
681static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
682 Timer *t = TIMER(u);
683
684 assert(u);
685 assert(f);
686 assert(fds);
687
d68c645b
LP
688 (void) serialize_item(f, "state", timer_state_to_string(t->state));
689 (void) serialize_item(f, "result", timer_result_to_string(t->result));
871d7de4 690
06642d17 691 if (t->last_trigger.realtime > 0)
d68c645b 692 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
06642d17
LP
693
694 if (t->last_trigger.monotonic > 0)
d68c645b 695 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
06642d17 696
871d7de4
LP
697 return 0;
698}
699
700static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
701 Timer *t = TIMER(u);
702
703 assert(u);
704 assert(key);
705 assert(value);
706 assert(fds);
707
708 if (streq(key, "state")) {
709 TimerState state;
710
36697dc0
LP
711 state = timer_state_from_string(value);
712 if (state < 0)
f2341e0a 713 log_unit_debug(u, "Failed to parse state value: %s", value);
871d7de4
LP
714 else
715 t->deserialized_state = state;
d68c645b 716
067d72c9
LP
717 } else if (streq(key, "result")) {
718 TimerResult f;
719
720 f = timer_result_from_string(value);
721 if (f < 0)
f2341e0a 722 log_unit_debug(u, "Failed to parse result value: %s", value);
067d72c9
LP
723 else if (f != TIMER_SUCCESS)
724 t->result = f;
06642d17 725
d68c645b
LP
726 } else if (streq(key, "last-trigger-realtime"))
727 (void) deserialize_usec(value, &t->last_trigger.realtime);
728 else if (streq(key, "last-trigger-monotonic"))
729 (void) deserialize_usec(value, &t->last_trigger.monotonic);
730 else
f2341e0a 731 log_unit_debug(u, "Unknown serialization key: %s", key);
871d7de4
LP
732
733 return 0;
034c6ed7
LP
734}
735
44a6b1b6 736_pure_ static UnitActiveState timer_active_state(Unit *u) {
871d7de4
LP
737 assert(u);
738
739 return state_translation_table[TIMER(u)->state];
740}
741
44a6b1b6 742_pure_ static const char *timer_sub_state_to_string(Unit *u) {
871d7de4
LP
743 assert(u);
744
745 return timer_state_to_string(TIMER(u)->state);
746}
747
718db961
LP
748static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
749 Timer *t = TIMER(userdata);
871d7de4
LP
750
751 assert(t);
5cb5a6ff 752
871d7de4 753 if (t->state != TIMER_WAITING)
718db961 754 return 0;
5cb5a6ff 755
f2341e0a 756 log_unit_debug(UNIT(t), "Timer elapsed.");
871d7de4 757 timer_enter_running(t);
718db961 758 return 0;
5cb5a6ff
LP
759}
760
3ecaa09b
LP
761static void timer_trigger_notify(Unit *u, Unit *other) {
762 Timer *t = TIMER(u);
871d7de4 763
3ecaa09b
LP
764 assert(u);
765 assert(other);
871d7de4 766
0377cd29
LP
767 /* Filter out invocations with bogus state */
768 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
871d7de4 769
3ecaa09b
LP
770 /* Reenable all timers that depend on unit state */
771 LIST_FOREACH(value, v, t->values)
3742095b 772 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
3ecaa09b 773 v->disabled = false;
01f78473 774
3ecaa09b 775 switch (t->state) {
871d7de4 776
3ecaa09b
LP
777 case TIMER_WAITING:
778 case TIMER_ELAPSED:
871d7de4 779
3ecaa09b 780 /* Recalculate sleep time */
aa1f95d2 781 timer_enter_waiting(t, false);
3ecaa09b 782 break;
871d7de4 783
3ecaa09b 784 case TIMER_RUNNING:
871d7de4 785
3ecaa09b 786 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
f2341e0a 787 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
aa1f95d2 788 timer_enter_waiting(t, false);
3ecaa09b
LP
789 }
790 break;
871d7de4 791
3ecaa09b
LP
792 case TIMER_DEAD:
793 case TIMER_FAILED:
794 break;
871d7de4 795
3ecaa09b 796 default:
04499a70 797 assert_not_reached();
871d7de4 798 }
871d7de4
LP
799}
800
fdf20a31 801static void timer_reset_failed(Unit *u) {
5632e374
LP
802 Timer *t = TIMER(u);
803
804 assert(t);
805
fdf20a31 806 if (t->state == TIMER_FAILED)
5632e374
LP
807 timer_set_state(t, TIMER_DEAD);
808
067d72c9 809 t->result = TIMER_SUCCESS;
5632e374
LP
810}
811
8742514c
LP
812static void timer_time_change(Unit *u) {
813 Timer *t = TIMER(u);
13f512d3 814 usec_t ts;
8742514c
LP
815
816 assert(u);
817
818 if (t->state != TIMER_WAITING)
819 return;
820
13f512d3
AJ
821 /* If we appear to have triggered in the future, the system clock must
822 * have been set backwards. So let's rewind our own clock and allow
0923b425 823 * the future triggers to happen again :). Exactly the same as when
13f512d3
AJ
824 * you start a timer unit with Persistent=yes. */
825 ts = now(CLOCK_REALTIME);
826 if (t->last_trigger.realtime > ts)
827 t->last_trigger.realtime = ts;
828
efebb613
LP
829 if (t->on_clock_change) {
830 log_unit_debug(u, "Time change, triggering activation.");
831 timer_enter_running(t);
832 } else {
833 log_unit_debug(u, "Time change, recalculating next elapse.");
834 timer_enter_waiting(t, true);
835 }
8742514c
LP
836}
837
bbf5fd8e
LP
838static void timer_timezone_change(Unit *u) {
839 Timer *t = TIMER(u);
840
841 assert(u);
842
843 if (t->state != TIMER_WAITING)
844 return;
845
efebb613
LP
846 if (t->on_timezone_change) {
847 log_unit_debug(u, "Timezone change, triggering activation.");
848 timer_enter_running(t);
849 } else {
850 log_unit_debug(u, "Timezone change, recalculating next elapse.");
851 timer_enter_waiting(t, false);
852 }
bbf5fd8e
LP
853}
854
89f6fe7b
LP
855static int timer_clean(Unit *u, ExecCleanMask mask) {
856 Timer *t = TIMER(u);
857 int r;
858
859 assert(t);
860 assert(mask != 0);
861
862 if (t->state != TIMER_DEAD)
863 return -EBUSY;
864
4f06325c 865 if (mask != EXEC_CLEAN_STATE)
89f6fe7b
LP
866 return -EUNATCH;
867
868 r = timer_setup_persistent(t);
869 if (r < 0)
870 return r;
871
872 if (!t->stamp_path)
873 return -EUNATCH;
874
875 if (unlink(t->stamp_path) && errno != ENOENT)
876 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
877
878 return 0;
879}
880
881static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
882 Timer *t = TIMER(u);
883
884 assert(t);
4fb8f1e8 885 assert(ret);
89f6fe7b
LP
886
887 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
888 return 0;
889}
890
705578c3 891static int timer_can_start(Unit *u) {
9727f242
DDM
892 Timer *t = TIMER(u);
893 int r;
894
895 assert(t);
896
897 r = unit_test_start_limit(u);
898 if (r < 0) {
899 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
900 return r;
901 }
902
705578c3 903 return 1;
9727f242
DDM
904}
905
c8bc7519
LB
906static void activation_details_timer_serialize(ActivationDetails *details, FILE *f) {
907 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(details);
908
909 assert(details);
910 assert(f);
911 assert(t);
912
913 (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
914}
915
916static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
917 int r;
918
919 assert(key);
920 assert(value);
921
922 if (!details || !*details)
923 return -EINVAL;
924
925 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
926 if (!t)
927 return -EINVAL;
928
929 if (!streq(key, "activation-details-timer-last-trigger"))
930 return -EINVAL;
931
932 r = deserialize_dual_timestamp(value, &t->last_trigger);
933 if (r < 0)
934 return r;
935
936 return 0;
937}
938
939static int activation_details_timer_append_env(ActivationDetails *details, char ***strv) {
940 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(details);
941 int r;
942
943 assert(details);
944 assert(strv);
945 assert(t);
946
947 if (!dual_timestamp_is_set(&t->last_trigger))
948 return 0;
949
6457ce15 950 r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
951 if (r < 0)
952 return r;
953
6457ce15 954 r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
955 if (r < 0)
956 return r;
957
958 return 2; /* Return the number of variables added to the env block */
959}
960
961static int activation_details_timer_append_pair(ActivationDetails *details, char ***strv) {
962 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(details);
963 int r;
964
965 assert(details);
966 assert(strv);
967 assert(t);
968
969 if (!dual_timestamp_is_set(&t->last_trigger))
970 return 0;
971
972 r = strv_extend(strv, "trigger_timer_realtime_usec");
973 if (r < 0)
974 return r;
975
6457ce15 976 r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
977 if (r < 0)
978 return r;
979
980 r = strv_extend(strv, "trigger_timer_monotonic_usec");
981 if (r < 0)
982 return r;
983
6457ce15 984 r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
985 if (r < 0)
986 return r;
987
988 return 2; /* Return the number of pairs added to the env block */
989}
990
871d7de4 991static const char* const timer_base_table[_TIMER_BASE_MAX] = {
48d83e33
ZJS
992 [TIMER_ACTIVE] = "OnActiveSec",
993 [TIMER_BOOT] = "OnBootSec",
994 [TIMER_STARTUP] = "OnStartupSec",
995 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
36697dc0 996 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
48d83e33 997 [TIMER_CALENDAR] = "OnCalendar"
871d7de4
LP
998};
999
1000DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
1001
067d72c9 1002static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
40f41f34
DDM
1003 [TIMER_SUCCESS] = "success",
1004 [TIMER_FAILURE_RESOURCES] = "resources",
1005 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
067d72c9
LP
1006};
1007
1008DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1009
87f0e418 1010const UnitVTable timer_vtable = {
7d17cfbc 1011 .object_size = sizeof(Timer),
718db961 1012
f975e971
LP
1013 .sections =
1014 "Unit\0"
1015 "Timer\0"
1016 "Install\0",
d8a812d1 1017 .private_section = "Timer",
5cb5a6ff 1018
c80a9a33
LP
1019 .can_transient = true,
1020 .can_fail = true,
1021 .can_trigger = true,
1022
871d7de4 1023 .init = timer_init,
034c6ed7 1024 .done = timer_done,
871d7de4
LP
1025 .load = timer_load,
1026
1027 .coldplug = timer_coldplug,
1028
1029 .dump = timer_dump,
1030
1031 .start = timer_start,
1032 .stop = timer_stop,
1033
89f6fe7b
LP
1034 .clean = timer_clean,
1035 .can_clean = timer_can_clean,
1036
871d7de4
LP
1037 .serialize = timer_serialize,
1038 .deserialize_item = timer_deserialize_item,
1039
1040 .active_state = timer_active_state,
1041 .sub_state_to_string = timer_sub_state_to_string,
1042
3ecaa09b
LP
1043 .trigger_notify = timer_trigger_notify,
1044
fdf20a31 1045 .reset_failed = timer_reset_failed,
8742514c 1046 .time_change = timer_time_change,
bbf5fd8e 1047 .timezone_change = timer_timezone_change,
5632e374 1048
d8a812d1 1049 .bus_set_property = bus_timer_set_property,
9727f242 1050
705578c3 1051 .can_start = timer_can_start,
5cb5a6ff 1052};
c8bc7519
LB
1053
1054const ActivationDetailsVTable activation_details_timer_vtable = {
1055 .object_size = sizeof(ActivationDetailsTimer),
1056
1057 .serialize = activation_details_timer_serialize,
1058 .deserialize = activation_details_timer_deserialize,
1059 .append_env = activation_details_timer_append_env,
1060 .append_pair = activation_details_timer_append_pair,
1061};