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