]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/timer.c
network: DHCP version logging typos
[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 = ASSERT_PTR(TIMER(u));
39
40 assert(u->load_state == UNIT_STUB);
41
42 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
43 t->next_elapse_realtime = USEC_INFINITY;
44 t->accuracy_usec = u->manager->defaults.timer_accuracy_usec;
45 t->remain_after_elapse = true;
46 }
47
48 void timer_free_values(Timer *t) {
49 TimerValue *v;
50
51 assert(t);
52
53 while ((v = LIST_POP(value, t->values))) {
54 calendar_spec_free(v->calendar_spec);
55 free(v);
56 }
57 }
58
59 static void timer_done(Unit *u) {
60 Timer *t = ASSERT_PTR(TIMER(u));
61
62 timer_free_values(t);
63
64 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
65 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
66
67 t->stamp_path = mfree(t->stamp_path);
68 }
69
70 static int timer_verify(Timer *t) {
71 assert(t);
72 assert(UNIT(t)->load_state == UNIT_LOADED);
73
74 if (!t->values && !t->on_clock_change && !t->on_timezone_change)
75 return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
76
77 return 0;
78 }
79
80 static int timer_add_default_dependencies(Timer *t) {
81 int r;
82
83 assert(t);
84
85 if (!UNIT(t)->default_dependencies)
86 return 0;
87
88 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
89 if (r < 0)
90 return r;
91
92 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
93 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
94 if (r < 0)
95 return r;
96
97 LIST_FOREACH(value, v, t->values) {
98 if (v->base != TIMER_CALENDAR)
99 continue;
100
101 FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
102 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
103 if (r < 0)
104 return r;
105 }
106
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 (UNIT_TRIGGER(UNIT(t)))
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 _cleanup_free_ char *stamp_path = NULL;
132 int r;
133
134 assert(t);
135
136 if (!t->persistent)
137 return 0;
138
139 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
140
141 r = unit_add_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
142 if (r < 0)
143 return r;
144
145 stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
146 } else {
147 const char *e;
148
149 e = getenv("XDG_DATA_HOME");
150 if (e)
151 stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
152 else {
153
154 _cleanup_free_ char *h = NULL;
155
156 r = get_home_dir(&h);
157 if (r < 0)
158 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
159
160 stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
161 }
162 }
163
164 if (!stamp_path)
165 return log_oom();
166
167 return free_and_replace(t->stamp_path, stamp_path);
168 }
169
170 static uint64_t timer_get_fixed_delay_hash(Timer *t) {
171 static const uint8_t hash_key[] = {
172 0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
173 0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
174 };
175
176 struct siphash state;
177 sd_id128_t machine_id;
178 uid_t uid;
179 int r;
180
181 assert(t);
182
183 uid = getuid();
184 r = sd_id128_get_machine(&machine_id);
185 if (r < 0) {
186 log_unit_debug_errno(UNIT(t), r,
187 "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
188 machine_id = SD_ID128_NULL;
189 }
190
191 siphash24_init(&state, hash_key);
192 siphash24_compress_typesafe(machine_id, &state);
193 siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
194 siphash24_compress_typesafe(uid, &state);
195 siphash24_compress_string(UNIT(t)->id, &state);
196
197 return siphash24_finalize(&state);
198 }
199
200 static int timer_load(Unit *u) {
201 Timer *t = ASSERT_PTR(TIMER(u));
202 int r;
203
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 Timer *t = ASSERT_PTR(TIMER(u));
231 Unit *trigger;
232
233 assert(f);
234 assert(prefix);
235
236 trigger = UNIT_TRIGGER(u);
237
238 fprintf(f,
239 "%sTimer State: %s\n"
240 "%sResult: %s\n"
241 "%sUnit: %s\n"
242 "%sPersistent: %s\n"
243 "%sWakeSystem: %s\n"
244 "%sAccuracy: %s\n"
245 "%sRemainAfterElapse: %s\n"
246 "%sFixedRandomDelay: %s\n"
247 "%sOnClockChange: %s\n"
248 "%sOnTimeZoneChange: %s\n",
249 prefix, timer_state_to_string(t->state),
250 prefix, timer_result_to_string(t->result),
251 prefix, trigger ? trigger->id : "n/a",
252 prefix, yes_no(t->persistent),
253 prefix, yes_no(t->wake_system),
254 prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
255 prefix, yes_no(t->remain_after_elapse),
256 prefix, yes_no(t->fixed_random_delay),
257 prefix, yes_no(t->on_clock_change),
258 prefix, yes_no(t->on_timezone_change));
259
260 LIST_FOREACH(value, v, t->values)
261 if (v->base == TIMER_CALENDAR) {
262 _cleanup_free_ char *p = NULL;
263
264 (void) calendar_spec_to_string(v->calendar_spec, &p);
265
266 fprintf(f,
267 "%s%s: %s\n",
268 prefix,
269 timer_base_to_string(v->base),
270 strna(p));
271 } else
272 fprintf(f,
273 "%s%s: %s\n",
274 prefix,
275 timer_base_to_string(v->base),
276 FORMAT_TIMESPAN(v->value, 0));
277 }
278
279 static void timer_set_state(Timer *t, TimerState state) {
280 TimerState old_state;
281
282 assert(t);
283
284 if (t->state != state)
285 bus_unit_send_pending_change_signal(UNIT(t), false);
286
287 old_state = t->state;
288 t->state = state;
289
290 if (state != TIMER_WAITING) {
291 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
292 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
293 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
294 t->next_elapse_realtime = USEC_INFINITY;
295 }
296
297 if (state != old_state)
298 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
299
300 unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
301 }
302
303 static void timer_enter_waiting(Timer *t, bool time_change);
304
305 static int timer_coldplug(Unit *u) {
306 Timer *t = ASSERT_PTR(TIMER(u));
307
308 assert(t->state == TIMER_DEAD);
309
310 if (t->deserialized_state == t->state)
311 return 0;
312
313 if (t->deserialized_state == TIMER_WAITING)
314 timer_enter_waiting(t, false);
315 else
316 timer_set_state(t, t->deserialized_state);
317
318 return 0;
319 }
320
321 static void timer_enter_dead(Timer *t, TimerResult f) {
322 assert(t);
323
324 if (t->result == TIMER_SUCCESS)
325 t->result = f;
326
327 unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
328 timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
329 }
330
331 static void timer_enter_elapsed(Timer *t, bool leave_around) {
332 assert(t);
333
334 /* If a unit is marked with RemainAfterElapse=yes we leave it
335 * around even after it elapsed once, so that starting it
336 * later again does not necessarily mean immediate
337 * retriggering. We unconditionally leave units with
338 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
339 * since they might be restarted automatically at any time
340 * later on. */
341
342 if (t->remain_after_elapse || leave_around)
343 timer_set_state(t, TIMER_ELAPSED);
344 else
345 timer_enter_dead(t, TIMER_SUCCESS);
346 }
347
348 static void add_random(Timer *t, usec_t *v) {
349 usec_t add;
350
351 assert(t);
352 assert(v);
353
354 if (t->random_usec == 0)
355 return;
356 if (*v == USEC_INFINITY)
357 return;
358
359 add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_usec;
360
361 if (*v + add < *v) /* overflow */
362 *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
363 else
364 *v += add;
365
366 log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
367 }
368
369 static void timer_enter_waiting(Timer *t, bool time_change) {
370 bool found_monotonic = false, found_realtime = false;
371 bool leave_around = false;
372 triple_timestamp ts;
373 Unit *trigger;
374 int r;
375
376 assert(t);
377
378 trigger = UNIT_TRIGGER(UNIT(t));
379 if (!trigger) {
380 log_unit_error(UNIT(t), "Unit to trigger vanished.");
381 goto fail;
382 }
383
384 triple_timestamp_now(&ts);
385 t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
386
387 LIST_FOREACH(value, v, t->values) {
388 if (v->disabled)
389 continue;
390
391 if (v->base == TIMER_CALENDAR) {
392 usec_t b, rebased;
393
394 /* If we know the last time this was
395 * triggered, schedule the job based relative
396 * to that. If we don't, just start from
397 * the activation time. */
398
399 if (dual_timestamp_is_set(&t->last_trigger))
400 b = t->last_trigger.realtime;
401 else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
402 b = UNIT(t)->inactive_exit_timestamp.realtime;
403 else
404 b = ts.realtime;
405
406 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
407 if (r < 0)
408 continue;
409
410 /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
411 * time has already passed, set the time when systemd first started as the scheduled
412 * time. Note that we base this on the monotonic timestamp of the boot, not the
413 * realtime one, since the wallclock might have been off during boot. */
414 rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
415 CLOCK_MONOTONIC, CLOCK_REALTIME);
416 if (v->next_elapse < rebased)
417 v->next_elapse = rebased;
418
419 if (!found_realtime)
420 t->next_elapse_realtime = v->next_elapse;
421 else
422 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
423
424 found_realtime = true;
425
426 } else {
427 usec_t base;
428
429 switch (v->base) {
430
431 case TIMER_ACTIVE:
432 if (state_translation_table[t->state] == UNIT_ACTIVE)
433 base = UNIT(t)->inactive_exit_timestamp.monotonic;
434 else
435 base = ts.monotonic;
436 break;
437
438 case TIMER_BOOT:
439 if (detect_container() <= 0) {
440 /* CLOCK_MONOTONIC equals the uptime on Linux */
441 base = 0;
442 break;
443 }
444 /* In a container we don't want to include the time the host
445 * was already up when the container started, so count from
446 * our own startup. */
447 _fallthrough_;
448 case TIMER_STARTUP:
449 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
450 break;
451
452 case TIMER_UNIT_ACTIVE:
453 leave_around = true;
454 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
455 if (base <= 0)
456 continue;
457 break;
458
459 case TIMER_UNIT_INACTIVE:
460 leave_around = true;
461 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
462 if (base <= 0)
463 continue;
464 break;
465
466 default:
467 assert_not_reached();
468 }
469
470 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
471
472 if (dual_timestamp_is_set(&t->last_trigger) &&
473 !time_change &&
474 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
475 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
476 /* This is a one time trigger, disable it now */
477 v->disabled = true;
478 continue;
479 }
480
481 if (!found_monotonic)
482 t->next_elapse_monotonic_or_boottime = v->next_elapse;
483 else
484 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
485
486 found_monotonic = true;
487 }
488 }
489
490 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
491 log_unit_debug(UNIT(t), "Timer is elapsed.");
492 timer_enter_elapsed(t, leave_around);
493 return;
494 }
495
496 if (found_monotonic) {
497 usec_t left;
498
499 add_random(t, &t->next_elapse_monotonic_or_boottime);
500
501 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
502 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
503
504 if (t->monotonic_event_source) {
505 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
506 if (r < 0) {
507 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule monotonic event source: %m");
508 goto fail;
509 }
510
511 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
512 if (r < 0) {
513 log_unit_warning_errno(UNIT(t), r, "Failed to enable monotonic event source: %m");
514 goto fail;
515 }
516 } else {
517
518 r = sd_event_add_time(
519 UNIT(t)->manager->event,
520 &t->monotonic_event_source,
521 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
522 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
523 timer_dispatch, t);
524 if (r < 0) {
525 log_unit_warning_errno(UNIT(t), r, "Failed to add monotonic event source: %m");
526 goto fail;
527 }
528
529 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
530 }
531
532 } else if (t->monotonic_event_source) {
533
534 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
535 if (r < 0) {
536 log_unit_warning_errno(UNIT(t), r, "Failed to disable monotonic event source: %m");
537 goto fail;
538 }
539 }
540
541 if (found_realtime) {
542 add_random(t, &t->next_elapse_realtime);
543
544 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
545
546 if (t->realtime_event_source) {
547 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
548 if (r < 0) {
549 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule realtime event source: %m");
550 goto fail;
551 }
552
553 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
554 if (r < 0) {
555 log_unit_warning_errno(UNIT(t), r, "Failed to enable realtime event source: %m");
556 goto fail;
557 }
558 } else {
559 r = sd_event_add_time(
560 UNIT(t)->manager->event,
561 &t->realtime_event_source,
562 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
563 t->next_elapse_realtime, t->accuracy_usec,
564 timer_dispatch, t);
565 if (r < 0) {
566 log_unit_warning_errno(UNIT(t), r, "Failed to add realtime event source: %m");
567 goto fail;
568 }
569
570 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
571 }
572
573 } else if (t->realtime_event_source) {
574
575 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
576 if (r < 0) {
577 log_unit_warning_errno(UNIT(t), r, "Failed to disable realtime event source: %m");
578 goto fail;
579 }
580 }
581
582 timer_set_state(t, TIMER_WAITING);
583 return;
584
585 fail:
586 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
587 }
588
589 static void timer_enter_running(Timer *t) {
590 _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
591 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
592 Unit *trigger;
593 Job *job;
594 int r;
595
596 assert(t);
597
598 /* Don't start job if we are supposed to go down */
599 if (unit_stop_pending(UNIT(t)))
600 return;
601
602 trigger = UNIT_TRIGGER(UNIT(t));
603 if (!trigger) {
604 log_unit_error(UNIT(t), "Unit to trigger vanished.");
605 goto fail;
606 }
607
608 details = activation_details_new(UNIT(t));
609 if (!details) {
610 log_oom();
611 goto fail;
612 }
613
614 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, &job);
615 if (r < 0) {
616 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
617 goto fail;
618 }
619
620 dual_timestamp_now(&t->last_trigger);
621 ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
622
623 job_set_activation_details(job, details);
624
625 if (t->stamp_path)
626 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
627
628 timer_set_state(t, TIMER_RUNNING);
629 return;
630
631 fail:
632 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
633 }
634
635 static int timer_start(Unit *u) {
636 Timer *t = ASSERT_PTR(TIMER(u));
637 int r;
638
639 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
640
641 r = unit_test_trigger_loaded(u);
642 if (r < 0)
643 return r;
644
645 r = unit_acquire_invocation_id(u);
646 if (r < 0)
647 return r;
648
649 t->last_trigger = DUAL_TIMESTAMP_NULL;
650
651 /* Reenable all timers that depend on unit activation time */
652 LIST_FOREACH(value, v, t->values)
653 if (v->base == TIMER_ACTIVE)
654 v->disabled = false;
655
656 if (t->stamp_path) {
657 struct stat st;
658
659 if (stat(t->stamp_path, &st) >= 0) {
660 usec_t ft;
661
662 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
663 * something is wrong with the system clock. */
664
665 ft = timespec_load(&st.st_mtim);
666 if (ft < now(CLOCK_REALTIME))
667 t->last_trigger.realtime = ft;
668 else
669 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
670 FORMAT_TIMESTAMP(ft));
671
672 } else if (errno == ENOENT)
673 /* The timer has never run before, make sure a stamp file exists. */
674 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
675 }
676
677 t->result = TIMER_SUCCESS;
678 timer_enter_waiting(t, false);
679 return 1;
680 }
681
682 static int timer_stop(Unit *u) {
683 Timer *t = ASSERT_PTR(TIMER(u));
684
685 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
686
687 timer_enter_dead(t, TIMER_SUCCESS);
688 return 1;
689 }
690
691 static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
692 Timer *t = ASSERT_PTR(TIMER(u));
693
694 assert(f);
695 assert(fds);
696
697 (void) serialize_item(f, "state", timer_state_to_string(t->state));
698 (void) serialize_item(f, "result", timer_result_to_string(t->result));
699
700 if (dual_timestamp_is_set(&t->last_trigger))
701 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
702
703 if (t->last_trigger.monotonic > 0)
704 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
705
706 return 0;
707 }
708
709 static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
710 Timer *t = ASSERT_PTR(TIMER(u));
711
712 assert(key);
713 assert(value);
714 assert(fds);
715
716 if (streq(key, "state")) {
717 TimerState state;
718
719 state = timer_state_from_string(value);
720 if (state < 0)
721 log_unit_debug(u, "Failed to parse state value: %s", value);
722 else
723 t->deserialized_state = state;
724
725 } else if (streq(key, "result")) {
726 TimerResult f;
727
728 f = timer_result_from_string(value);
729 if (f < 0)
730 log_unit_debug(u, "Failed to parse result value: %s", value);
731 else if (f != TIMER_SUCCESS)
732 t->result = f;
733
734 } else if (streq(key, "last-trigger-realtime"))
735 (void) deserialize_usec(value, &t->last_trigger.realtime);
736 else if (streq(key, "last-trigger-monotonic"))
737 (void) deserialize_usec(value, &t->last_trigger.monotonic);
738 else
739 log_unit_debug(u, "Unknown serialization key: %s", key);
740
741 return 0;
742 }
743
744 static UnitActiveState timer_active_state(Unit *u) {
745 Timer *t = ASSERT_PTR(TIMER(u));
746
747 return state_translation_table[t->state];
748 }
749
750 static const char *timer_sub_state_to_string(Unit *u) {
751 Timer *t = ASSERT_PTR(TIMER(u));
752
753 return timer_state_to_string(t->state);
754 }
755
756 static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
757 Timer *t = ASSERT_PTR(TIMER(userdata));
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 = ASSERT_PTR(TIMER(u));
769
770 assert(other);
771
772 /* Filter out invocations with bogus state */
773 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
774
775 /* Reenable all timers that depend on unit state */
776 LIST_FOREACH(value, v, t->values)
777 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
778 v->disabled = false;
779
780 switch (t->state) {
781
782 case TIMER_WAITING:
783 case TIMER_ELAPSED:
784
785 /* Recalculate sleep time */
786 timer_enter_waiting(t, false);
787 break;
788
789 case TIMER_RUNNING:
790
791 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
792 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
793 timer_enter_waiting(t, false);
794 }
795 break;
796
797 case TIMER_DEAD:
798 case TIMER_FAILED:
799 break;
800
801 default:
802 assert_not_reached();
803 }
804 }
805
806 static void timer_reset_failed(Unit *u) {
807 Timer *t = ASSERT_PTR(TIMER(u));
808
809 if (t->state == TIMER_FAILED)
810 timer_set_state(t, TIMER_DEAD);
811
812 t->result = TIMER_SUCCESS;
813 }
814
815 static void timer_time_change(Unit *u) {
816 Timer *t = ASSERT_PTR(TIMER(u));
817 usec_t ts;
818
819 if (t->state != TIMER_WAITING)
820 return;
821
822 /* If we appear to have triggered in the future, the system clock must
823 * have been set backwards. So let's rewind our own clock and allow
824 * the future triggers to happen again :). Exactly the same as when
825 * you start a timer unit with Persistent=yes. */
826 ts = now(CLOCK_REALTIME);
827 if (t->last_trigger.realtime > ts)
828 t->last_trigger.realtime = ts;
829
830 if (t->on_clock_change) {
831 log_unit_debug(u, "Time change, triggering activation.");
832 timer_enter_running(t);
833 } else {
834 log_unit_debug(u, "Time change, recalculating next elapse.");
835 timer_enter_waiting(t, true);
836 }
837 }
838
839 static void timer_timezone_change(Unit *u) {
840 Timer *t = ASSERT_PTR(TIMER(u));
841
842 if (t->state != TIMER_WAITING)
843 return;
844
845 if (t->on_timezone_change) {
846 log_unit_debug(u, "Timezone change, triggering activation.");
847 timer_enter_running(t);
848 } else {
849 log_unit_debug(u, "Timezone change, recalculating next elapse.");
850 timer_enter_waiting(t, false);
851 }
852 }
853
854 static int timer_clean(Unit *u, ExecCleanMask mask) {
855 Timer *t = ASSERT_PTR(TIMER(u));
856 int r;
857
858 assert(mask != 0);
859
860 if (t->state != TIMER_DEAD)
861 return -EBUSY;
862
863 if (mask != EXEC_CLEAN_STATE)
864 return -EUNATCH;
865
866 r = timer_setup_persistent(t);
867 if (r < 0)
868 return r;
869
870 if (!t->stamp_path)
871 return -EUNATCH;
872
873 if (unlink(t->stamp_path) && errno != ENOENT)
874 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
875
876 return 0;
877 }
878
879 static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
880 Timer *t = ASSERT_PTR(TIMER(u));
881
882 assert(ret);
883
884 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
885 return 0;
886 }
887
888 static int timer_can_start(Unit *u) {
889 Timer *t = ASSERT_PTR(TIMER(u));
890 int r;
891
892 r = unit_test_start_limit(u);
893 if (r < 0) {
894 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
895 return r;
896 }
897
898 return 1;
899 }
900
901 static void activation_details_timer_serialize(ActivationDetails *details, FILE *f) {
902 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
903
904 assert(f);
905 assert(t);
906
907 (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
908 }
909
910 static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
911 int r;
912
913 assert(key);
914 assert(value);
915
916 if (!details || !*details)
917 return -EINVAL;
918
919 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
920 if (!t)
921 return -EINVAL;
922
923 if (!streq(key, "activation-details-timer-last-trigger"))
924 return -EINVAL;
925
926 r = deserialize_dual_timestamp(value, &t->last_trigger);
927 if (r < 0)
928 return r;
929
930 return 0;
931 }
932
933 static int activation_details_timer_append_env(ActivationDetails *details, char ***strv) {
934 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
935 int r;
936
937 assert(strv);
938 assert(t);
939
940 if (!dual_timestamp_is_set(&t->last_trigger))
941 return 0;
942
943 r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
944 if (r < 0)
945 return r;
946
947 r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
948 if (r < 0)
949 return r;
950
951 return 2; /* Return the number of variables added to the env block */
952 }
953
954 static int activation_details_timer_append_pair(ActivationDetails *details, char ***strv) {
955 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
956 int r;
957
958 assert(strv);
959 assert(t);
960
961 if (!dual_timestamp_is_set(&t->last_trigger))
962 return 0;
963
964 r = strv_extend(strv, "trigger_timer_realtime_usec");
965 if (r < 0)
966 return r;
967
968 r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
969 if (r < 0)
970 return r;
971
972 r = strv_extend(strv, "trigger_timer_monotonic_usec");
973 if (r < 0)
974 return r;
975
976 r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
977 if (r < 0)
978 return r;
979
980 return 2; /* Return the number of pairs added to the env block */
981 }
982
983 uint64_t timer_next_elapse_monotonic(const Timer *t) {
984 assert(t);
985
986 return (uint64_t) usec_shift_clock(t->next_elapse_monotonic_or_boottime,
987 TIMER_MONOTONIC_CLOCK(t), CLOCK_MONOTONIC);
988 }
989
990 static const char* const timer_base_table[_TIMER_BASE_MAX] = {
991 [TIMER_ACTIVE] = "OnActiveSec",
992 [TIMER_BOOT] = "OnBootSec",
993 [TIMER_STARTUP] = "OnStartupSec",
994 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
995 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
996 [TIMER_CALENDAR] = "OnCalendar",
997 };
998
999 DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
1000
1001 char* timer_base_to_usec_string(TimerBase i) {
1002 _cleanup_free_ char *buf = NULL;
1003 const char *s;
1004 size_t l;
1005
1006 s = timer_base_to_string(i);
1007
1008 if (endswith(s, "Sec")) {
1009 /* s/Sec/USec/ */
1010 l = strlen(s);
1011 buf = new(char, l+2);
1012 if (!buf)
1013 return NULL;
1014
1015 memcpy(buf, s, l-3);
1016 memcpy(buf+l-3, "USec", 5);
1017 } else {
1018 buf = strdup(s);
1019 if (!buf)
1020 return NULL;
1021 }
1022
1023 return TAKE_PTR(buf);
1024 }
1025
1026 static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
1027 [TIMER_SUCCESS] = "success",
1028 [TIMER_FAILURE_RESOURCES] = "resources",
1029 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1030 };
1031
1032 DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1033
1034 const UnitVTable timer_vtable = {
1035 .object_size = sizeof(Timer),
1036
1037 .sections =
1038 "Unit\0"
1039 "Timer\0"
1040 "Install\0",
1041 .private_section = "Timer",
1042
1043 .can_transient = true,
1044 .can_fail = true,
1045 .can_trigger = true,
1046
1047 .init = timer_init,
1048 .done = timer_done,
1049 .load = timer_load,
1050
1051 .coldplug = timer_coldplug,
1052
1053 .dump = timer_dump,
1054
1055 .start = timer_start,
1056 .stop = timer_stop,
1057
1058 .clean = timer_clean,
1059 .can_clean = timer_can_clean,
1060
1061 .serialize = timer_serialize,
1062 .deserialize_item = timer_deserialize_item,
1063
1064 .active_state = timer_active_state,
1065 .sub_state_to_string = timer_sub_state_to_string,
1066
1067 .trigger_notify = timer_trigger_notify,
1068
1069 .reset_failed = timer_reset_failed,
1070 .time_change = timer_time_change,
1071 .timezone_change = timer_timezone_change,
1072
1073 .bus_set_property = bus_timer_set_property,
1074
1075 .can_start = timer_can_start,
1076 };
1077
1078 const ActivationDetailsVTable activation_details_timer_vtable = {
1079 .object_size = sizeof(ActivationDetailsTimer),
1080
1081 .serialize = activation_details_timer_serialize,
1082 .deserialize = activation_details_timer_deserialize,
1083 .append_env = activation_details_timer_append_env,
1084 .append_pair = activation_details_timer_append_pair,
1085 };