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