]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/timer.c
Merge pull request #28728 from yuwata/fstab-no
[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_disable_unref(t->monotonic_event_source);
69 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
70
71 t->stamp_path = mfree(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
87 assert(t);
88
89 if (!UNIT(t)->default_dependencies)
90 return 0;
91
92 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
93 if (r < 0)
94 return r;
95
96 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
97 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
98 if (r < 0)
99 return r;
100
101 LIST_FOREACH(value, v, t->values) {
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);
107 if (r < 0)
108 return r;
109 }
110
111 break;
112 }
113 }
114
115 return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
116 }
117
118 static int timer_add_trigger_dependencies(Timer *t) {
119 Unit *x;
120 int r;
121
122 assert(t);
123
124 if (UNIT_TRIGGER(UNIT(t)))
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);
132 }
133
134 static int timer_setup_persistent(Timer *t) {
135 _cleanup_free_ char *stamp_path = NULL;
136 int r;
137
138 assert(t);
139
140 if (!t->persistent)
141 return 0;
142
143 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
144
145 r = unit_require_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE);
146 if (r < 0)
147 return r;
148
149 stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
150 } else {
151 const char *e;
152
153 e = getenv("XDG_DATA_HOME");
154 if (e)
155 stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
156 else {
157
158 _cleanup_free_ char *h = NULL;
159
160 r = get_home_dir(&h);
161 if (r < 0)
162 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
163
164 stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
165 }
166 }
167
168 if (!stamp_path)
169 return log_oom();
170
171 return free_and_replace(t->stamp_path, stamp_path);
172 }
173
174 static 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
204 static int timer_load(Unit *u) {
205 Timer *t = TIMER(u);
206 int r;
207
208 assert(u);
209 assert(u->load_state == UNIT_STUB);
210
211 r = unit_load_fragment_and_dropin(u, true);
212 if (r < 0)
213 return r;
214
215 if (u->load_state != UNIT_LOADED)
216 return 0;
217
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;
222
223 r = timer_setup_persistent(t);
224 if (r < 0)
225 return r;
226
227 r = timer_add_default_dependencies(t);
228 if (r < 0)
229 return r;
230
231 return timer_verify(t);
232 }
233
234 static void timer_dump(Unit *u, FILE *f, const char *prefix) {
235 Timer *t = TIMER(u);
236 Unit *trigger;
237
238 trigger = UNIT_TRIGGER(u);
239
240 fprintf(f,
241 "%sTimer State: %s\n"
242 "%sResult: %s\n"
243 "%sUnit: %s\n"
244 "%sPersistent: %s\n"
245 "%sWakeSystem: %s\n"
246 "%sAccuracy: %s\n"
247 "%sRemainAfterElapse: %s\n"
248 "%sFixedRandomDelay: %s\n"
249 "%sOnClockChange: %s\n"
250 "%sOnTimeZoneChange: %s\n",
251 prefix, timer_state_to_string(t->state),
252 prefix, timer_result_to_string(t->result),
253 prefix, trigger ? trigger->id : "n/a",
254 prefix, yes_no(t->persistent),
255 prefix, yes_no(t->wake_system),
256 prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
257 prefix, yes_no(t->remain_after_elapse),
258 prefix, yes_no(t->fixed_random_delay),
259 prefix, yes_no(t->on_clock_change),
260 prefix, yes_no(t->on_timezone_change));
261
262 LIST_FOREACH(value, v, t->values)
263 if (v->base == TIMER_CALENDAR) {
264 _cleanup_free_ char *p = NULL;
265
266 (void) calendar_spec_to_string(v->calendar_spec, &p);
267
268 fprintf(f,
269 "%s%s: %s\n",
270 prefix,
271 timer_base_to_string(v->base),
272 strna(p));
273 } else
274 fprintf(f,
275 "%s%s: %s\n",
276 prefix,
277 timer_base_to_string(v->base),
278 FORMAT_TIMESPAN(v->value, 0));
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_disable_unref(t->monotonic_event_source);
293 t->realtime_event_source = sd_event_source_disable_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], /* reload_success = */ true);
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 usec_t add;
352
353 assert(t);
354 assert(v);
355
356 if (t->random_usec == 0)
357 return;
358 if (*v == USEC_INFINITY)
359 return;
360
361 add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_usec;
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
368 log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
369 }
370
371 static void timer_enter_waiting(Timer *t, bool time_change) {
372 bool found_monotonic = false, found_realtime = false;
373 bool leave_around = false;
374 triple_timestamp ts;
375 Unit *trigger;
376 int r;
377
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
387 triple_timestamp_get(&ts);
388 t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
389
390 LIST_FOREACH(value, v, t->values) {
391 if (v->disabled)
392 continue;
393
394 if (v->base == TIMER_CALENDAR) {
395 usec_t b, rebased;
396
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 (dual_timestamp_is_set(&t->last_trigger))
403 b = t->last_trigger.realtime;
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;
408
409 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
410 if (r < 0)
411 continue;
412
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;
421
422 if (!found_realtime)
423 t->next_elapse_realtime = v->next_elapse;
424 else
425 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
426
427 found_realtime = true;
428
429 } else {
430 usec_t base;
431
432 switch (v->base) {
433
434 case TIMER_ACTIVE:
435 if (state_translation_table[t->state] == UNIT_ACTIVE)
436 base = UNIT(t)->inactive_exit_timestamp.monotonic;
437 else
438 base = ts.monotonic;
439 break;
440
441 case TIMER_BOOT:
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
449 * our own startup. */
450 _fallthrough_;
451 case TIMER_STARTUP:
452 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
453 break;
454
455 case TIMER_UNIT_ACTIVE:
456 leave_around = true;
457 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
458 if (base <= 0)
459 continue;
460 break;
461
462 case TIMER_UNIT_INACTIVE:
463 leave_around = true;
464 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
465 if (base <= 0)
466 continue;
467 break;
468
469 default:
470 assert_not_reached();
471 }
472
473 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
474
475 if (dual_timestamp_is_set(&t->last_trigger) &&
476 !time_change &&
477 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
478 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
479 /* This is a one time trigger, disable it now */
480 v->disabled = true;
481 continue;
482 }
483
484 if (!found_monotonic)
485 t->next_elapse_monotonic_or_boottime = v->next_elapse;
486 else
487 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
488
489 found_monotonic = true;
490 }
491 }
492
493 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
494 log_unit_debug(UNIT(t), "Timer is elapsed.");
495 timer_enter_elapsed(t, leave_around);
496 return;
497 }
498
499 if (found_monotonic) {
500 usec_t left;
501
502 add_random(t, &t->next_elapse_monotonic_or_boottime);
503
504 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
505 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
506
507 if (t->monotonic_event_source) {
508 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
509 if (r < 0)
510 goto fail;
511
512 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
513 if (r < 0)
514 goto fail;
515 } else {
516
517 r = sd_event_add_time(
518 UNIT(t)->manager->event,
519 &t->monotonic_event_source,
520 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
521 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
522 timer_dispatch, t);
523 if (r < 0)
524 goto fail;
525
526 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
527 }
528
529 } else if (t->monotonic_event_source) {
530
531 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
532 if (r < 0)
533 goto fail;
534 }
535
536 if (found_realtime) {
537 add_random(t, &t->next_elapse_realtime);
538
539 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
540
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);
547 if (r < 0)
548 goto fail;
549 } else {
550 r = sd_event_add_time(
551 UNIT(t)->manager->event,
552 &t->realtime_event_source,
553 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
554 t->next_elapse_realtime, t->accuracy_usec,
555 timer_dispatch, t);
556 if (r < 0)
557 goto fail;
558
559 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
560 }
561
562 } else if (t->realtime_event_source) {
563
564 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
565 if (r < 0)
566 goto fail;
567 }
568
569 timer_set_state(t, TIMER_WAITING);
570 return;
571
572 fail:
573 log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m");
574 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
575 }
576
577 static void timer_enter_running(Timer *t) {
578 _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
579 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
580 Unit *trigger;
581 Job *job;
582 int r;
583
584 assert(t);
585
586 /* Don't start job if we are supposed to go down */
587 if (unit_stop_pending(UNIT(t)))
588 return;
589
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
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);
604 if (r < 0)
605 goto fail;
606
607 dual_timestamp_get(&t->last_trigger);
608 ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
609
610 job_set_activation_details(job, details);
611
612 if (t->stamp_path)
613 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
614
615 timer_set_state(t, TIMER_RUNNING);
616 return;
617
618 fail:
619 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
620 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
621 }
622
623 static int timer_start(Unit *u) {
624 Timer *t = TIMER(u);
625 int r;
626
627 assert(t);
628 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
629
630 r = unit_test_trigger_loaded(u);
631 if (r < 0)
632 return r;
633
634 r = unit_acquire_invocation_id(u);
635 if (r < 0)
636 return r;
637
638 t->last_trigger = DUAL_TIMESTAMP_NULL;
639
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
645 if (t->stamp_path) {
646 struct stat st;
647
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;
657 else
658 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
659 FORMAT_TIMESTAMP(ft));
660
661 } else if (errno == ENOENT)
662 /* The timer has never run before, make sure a stamp file exists. */
663 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
664 }
665
666 t->result = TIMER_SUCCESS;
667 timer_enter_waiting(t, false);
668 return 1;
669 }
670
671 static int timer_stop(Unit *u) {
672 Timer *t = TIMER(u);
673
674 assert(t);
675 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
676
677 timer_enter_dead(t, TIMER_SUCCESS);
678 return 1;
679 }
680
681 static 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
688 (void) serialize_item(f, "state", timer_state_to_string(t->state));
689 (void) serialize_item(f, "result", timer_result_to_string(t->result));
690
691 if (dual_timestamp_is_set(&t->last_trigger))
692 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
693
694 if (t->last_trigger.monotonic > 0)
695 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
696
697 return 0;
698 }
699
700 static 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
711 state = timer_state_from_string(value);
712 if (state < 0)
713 log_unit_debug(u, "Failed to parse state value: %s", value);
714 else
715 t->deserialized_state = state;
716
717 } else if (streq(key, "result")) {
718 TimerResult f;
719
720 f = timer_result_from_string(value);
721 if (f < 0)
722 log_unit_debug(u, "Failed to parse result value: %s", value);
723 else if (f != TIMER_SUCCESS)
724 t->result = f;
725
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
731 log_unit_debug(u, "Unknown serialization key: %s", key);
732
733 return 0;
734 }
735
736 _pure_ static UnitActiveState timer_active_state(Unit *u) {
737 assert(u);
738
739 return state_translation_table[TIMER(u)->state];
740 }
741
742 _pure_ static const char *timer_sub_state_to_string(Unit *u) {
743 assert(u);
744
745 return timer_state_to_string(TIMER(u)->state);
746 }
747
748 static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
749 Timer *t = TIMER(userdata);
750
751 assert(t);
752
753 if (t->state != TIMER_WAITING)
754 return 0;
755
756 log_unit_debug(UNIT(t), "Timer elapsed.");
757 timer_enter_running(t);
758 return 0;
759 }
760
761 static void timer_trigger_notify(Unit *u, Unit *other) {
762 Timer *t = TIMER(u);
763
764 assert(u);
765 assert(other);
766
767 /* Filter out invocations with bogus state */
768 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
769
770 /* Reenable all timers that depend on unit state */
771 LIST_FOREACH(value, v, t->values)
772 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
773 v->disabled = false;
774
775 switch (t->state) {
776
777 case TIMER_WAITING:
778 case TIMER_ELAPSED:
779
780 /* Recalculate sleep time */
781 timer_enter_waiting(t, false);
782 break;
783
784 case TIMER_RUNNING:
785
786 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
787 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
788 timer_enter_waiting(t, false);
789 }
790 break;
791
792 case TIMER_DEAD:
793 case TIMER_FAILED:
794 break;
795
796 default:
797 assert_not_reached();
798 }
799 }
800
801 static void timer_reset_failed(Unit *u) {
802 Timer *t = TIMER(u);
803
804 assert(t);
805
806 if (t->state == TIMER_FAILED)
807 timer_set_state(t, TIMER_DEAD);
808
809 t->result = TIMER_SUCCESS;
810 }
811
812 static void timer_time_change(Unit *u) {
813 Timer *t = TIMER(u);
814 usec_t ts;
815
816 assert(u);
817
818 if (t->state != TIMER_WAITING)
819 return;
820
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
823 * the future triggers to happen again :). Exactly the same as when
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
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 }
836 }
837
838 static 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
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 }
853 }
854
855 static 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
865 if (mask != EXEC_CLEAN_STATE)
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
881 static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
882 Timer *t = TIMER(u);
883
884 assert(t);
885 assert(ret);
886
887 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
888 return 0;
889 }
890
891 static int timer_can_start(Unit *u) {
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
903 return 1;
904 }
905
906 static 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
916 static 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
939 static 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
950 r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
951 if (r < 0)
952 return r;
953
954 r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
955 if (r < 0)
956 return r;
957
958 return 2; /* Return the number of variables added to the env block */
959 }
960
961 static 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
976 r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
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
984 r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
985 if (r < 0)
986 return r;
987
988 return 2; /* Return the number of pairs added to the env block */
989 }
990
991 static const char* const timer_base_table[_TIMER_BASE_MAX] = {
992 [TIMER_ACTIVE] = "OnActiveSec",
993 [TIMER_BOOT] = "OnBootSec",
994 [TIMER_STARTUP] = "OnStartupSec",
995 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
996 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
997 [TIMER_CALENDAR] = "OnCalendar"
998 };
999
1000 DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
1001
1002 static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
1003 [TIMER_SUCCESS] = "success",
1004 [TIMER_FAILURE_RESOURCES] = "resources",
1005 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1006 };
1007
1008 DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1009
1010 const UnitVTable timer_vtable = {
1011 .object_size = sizeof(Timer),
1012
1013 .sections =
1014 "Unit\0"
1015 "Timer\0"
1016 "Install\0",
1017 .private_section = "Timer",
1018
1019 .can_transient = true,
1020 .can_fail = true,
1021 .can_trigger = true,
1022
1023 .init = timer_init,
1024 .done = timer_done,
1025 .load = timer_load,
1026
1027 .coldplug = timer_coldplug,
1028
1029 .dump = timer_dump,
1030
1031 .start = timer_start,
1032 .stop = timer_stop,
1033
1034 .clean = timer_clean,
1035 .can_clean = timer_can_clean,
1036
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
1043 .trigger_notify = timer_trigger_notify,
1044
1045 .reset_failed = timer_reset_failed,
1046 .time_change = timer_time_change,
1047 .timezone_change = timer_timezone_change,
1048
1049 .bus_set_property = bus_timer_set_property,
1050
1051 .can_start = timer_can_start,
1052 };
1053
1054 const 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 };