1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
10 #include "alloc-util.h"
11 #include "bus-error.h"
13 #include "dbus-timer.h"
15 #include "parse-util.h"
16 #include "random-util.h"
18 #include "string-table.h"
19 #include "string-util.h"
21 #include "unit-name.h"
23 #include "user-util.h"
26 static const UnitActiveState state_translation_table
[_TIMER_STATE_MAX
] = {
27 [TIMER_DEAD
] = UNIT_INACTIVE
,
28 [TIMER_WAITING
] = UNIT_ACTIVE
,
29 [TIMER_RUNNING
] = UNIT_ACTIVE
,
30 [TIMER_ELAPSED
] = UNIT_ACTIVE
,
31 [TIMER_FAILED
] = UNIT_FAILED
34 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
);
36 static void timer_init(Unit
*u
) {
40 assert(u
->load_state
== UNIT_STUB
);
42 t
->next_elapse_monotonic_or_boottime
= USEC_INFINITY
;
43 t
->next_elapse_realtime
= USEC_INFINITY
;
44 t
->accuracy_usec
= u
->manager
->default_timer_accuracy_usec
;
45 t
->remain_after_elapse
= true;
48 void timer_free_values(Timer
*t
) {
53 while ((v
= t
->values
)) {
54 LIST_REMOVE(value
, t
->values
, v
);
55 calendar_spec_free(v
->calendar_spec
);
60 static void timer_done(Unit
*u
) {
67 t
->monotonic_event_source
= sd_event_source_unref(t
->monotonic_event_source
);
68 t
->realtime_event_source
= sd_event_source_unref(t
->realtime_event_source
);
73 static int timer_verify(Timer
*t
) {
76 if (UNIT(t
)->load_state
!= UNIT_LOADED
)
80 log_unit_error(UNIT(t
), "Timer unit lacks value setting. Refusing.");
87 static int timer_add_default_dependencies(Timer
*t
) {
93 if (!UNIT(t
)->default_dependencies
)
96 r
= unit_add_dependency_by_name(UNIT(t
), UNIT_BEFORE
, SPECIAL_TIMERS_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
100 if (MANAGER_IS_SYSTEM(UNIT(t
)->manager
)) {
101 r
= unit_add_two_dependencies_by_name(UNIT(t
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
105 LIST_FOREACH(value
, v
, t
->values
) {
106 if (v
->base
== TIMER_CALENDAR
) {
107 r
= unit_add_dependency_by_name(UNIT(t
), UNIT_AFTER
, SPECIAL_TIME_SYNC_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
115 return unit_add_two_dependencies_by_name(UNIT(t
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true, UNIT_DEPENDENCY_DEFAULT
);
118 static int timer_add_trigger_dependencies(Timer
*t
) {
124 if (!hashmap_isempty(UNIT(t
)->dependencies
[UNIT_TRIGGERS
]))
127 r
= unit_load_related_unit(UNIT(t
), ".service", &x
);
131 return unit_add_two_dependencies(UNIT(t
), UNIT_BEFORE
, UNIT_TRIGGERS
, x
, true, UNIT_DEPENDENCY_IMPLICIT
);
134 static int timer_setup_persistent(Timer
*t
) {
142 if (MANAGER_IS_SYSTEM(UNIT(t
)->manager
)) {
144 r
= unit_require_mounts_for(UNIT(t
), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE
);
148 t
->stamp_path
= strappend("/var/lib/systemd/timers/stamp-", UNIT(t
)->id
);
152 e
= getenv("XDG_DATA_HOME");
154 t
->stamp_path
= strjoin(e
, "/systemd/timers/stamp-", UNIT(t
)->id
);
157 _cleanup_free_
char *h
= NULL
;
159 r
= get_home_dir(&h
);
161 return log_unit_error_errno(UNIT(t
), r
, "Failed to determine home directory: %m");
163 t
->stamp_path
= strjoin(h
, "/.local/share/systemd/timers/stamp-", UNIT(t
)->id
);
173 static int timer_load(Unit
*u
) {
178 assert(u
->load_state
== UNIT_STUB
);
180 r
= unit_load_fragment_and_dropin(u
);
184 if (u
->load_state
== UNIT_LOADED
) {
186 r
= timer_add_trigger_dependencies(t
);
190 r
= timer_setup_persistent(t
);
194 r
= timer_add_default_dependencies(t
);
199 return timer_verify(t
);
202 static void timer_dump(Unit
*u
, FILE *f
, const char *prefix
) {
203 char buf
[FORMAT_TIMESPAN_MAX
];
208 trigger
= UNIT_TRIGGER(u
);
211 "%sTimer State: %s\n"
217 "%sRemainAfterElapse: %s\n",
218 prefix
, timer_state_to_string(t
->state
),
219 prefix
, timer_result_to_string(t
->result
),
220 prefix
, trigger
? trigger
->id
: "n/a",
221 prefix
, yes_no(t
->persistent
),
222 prefix
, yes_no(t
->wake_system
),
223 prefix
, format_timespan(buf
, sizeof(buf
), t
->accuracy_usec
, 1),
224 prefix
, yes_no(t
->remain_after_elapse
));
226 LIST_FOREACH(value
, v
, t
->values
) {
228 if (v
->base
== TIMER_CALENDAR
) {
229 _cleanup_free_
char *p
= NULL
;
231 (void) calendar_spec_to_string(v
->calendar_spec
, &p
);
236 timer_base_to_string(v
->base
),
239 char timespan1
[FORMAT_TIMESPAN_MAX
];
244 timer_base_to_string(v
->base
),
245 format_timespan(timespan1
, sizeof(timespan1
), v
->value
, 0));
250 static void timer_set_state(Timer
*t
, TimerState state
) {
251 TimerState old_state
;
254 old_state
= t
->state
;
257 if (state
!= TIMER_WAITING
) {
258 t
->monotonic_event_source
= sd_event_source_unref(t
->monotonic_event_source
);
259 t
->realtime_event_source
= sd_event_source_unref(t
->realtime_event_source
);
260 t
->next_elapse_monotonic_or_boottime
= USEC_INFINITY
;
261 t
->next_elapse_realtime
= USEC_INFINITY
;
264 if (state
!= old_state
)
265 log_unit_debug(UNIT(t
), "Changed %s -> %s", timer_state_to_string(old_state
), timer_state_to_string(state
));
267 unit_notify(UNIT(t
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
270 static void timer_enter_waiting(Timer
*t
, bool initial
);
272 static int timer_coldplug(Unit
*u
) {
276 assert(t
->state
== TIMER_DEAD
);
278 if (t
->deserialized_state
== t
->state
)
281 if (t
->deserialized_state
== TIMER_WAITING
)
282 timer_enter_waiting(t
, false);
284 timer_set_state(t
, t
->deserialized_state
);
289 static void timer_enter_dead(Timer
*t
, TimerResult f
) {
292 if (t
->result
== TIMER_SUCCESS
)
295 if (t
->result
!= TIMER_SUCCESS
)
296 log_unit_warning(UNIT(t
), "Failed with result '%s'.", timer_result_to_string(t
->result
));
298 timer_set_state(t
, t
->result
!= TIMER_SUCCESS
? TIMER_FAILED
: TIMER_DEAD
);
301 static void timer_enter_elapsed(Timer
*t
, bool leave_around
) {
304 /* If a unit is marked with RemainAfterElapse=yes we leave it
305 * around even after it elapsed once, so that starting it
306 * later again does not necessarily mean immediate
307 * retriggering. We unconditionally leave units with
308 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
309 * since they might be restarted automatically at any time
312 if (t
->remain_after_elapse
|| leave_around
)
313 timer_set_state(t
, TIMER_ELAPSED
);
315 timer_enter_dead(t
, TIMER_SUCCESS
);
318 static void add_random(Timer
*t
, usec_t
*v
) {
319 char s
[FORMAT_TIMESPAN_MAX
];
325 if (t
->random_usec
== 0)
327 if (*v
== USEC_INFINITY
)
330 add
= random_u64() % t
->random_usec
;
332 if (*v
+ add
< *v
) /* overflow */
333 *v
= (usec_t
) -2; /* Highest possible value, that is not USEC_INFINITY */
337 log_unit_debug(UNIT(t
), "Adding %s random time.", format_timespan(s
, sizeof(s
), add
, 0));
340 static void timer_enter_waiting(Timer
*t
, bool initial
) {
341 bool found_monotonic
= false, found_realtime
= false;
342 bool leave_around
= false;
350 trigger
= UNIT_TRIGGER(UNIT(t
));
352 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
353 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
357 triple_timestamp_get(&ts
);
358 t
->next_elapse_monotonic_or_boottime
= t
->next_elapse_realtime
= 0;
360 LIST_FOREACH(value
, v
, t
->values
) {
364 if (v
->base
== TIMER_CALENDAR
) {
367 /* If we know the last time this was
368 * triggered, schedule the job based relative
369 * to that. If we don't, just start from
370 * the activation time. */
372 if (t
->last_trigger
.realtime
> 0)
373 b
= t
->last_trigger
.realtime
;
375 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
376 b
= UNIT(t
)->inactive_exit_timestamp
.realtime
;
381 r
= calendar_spec_next_usec(v
->calendar_spec
, b
, &v
->next_elapse
);
386 t
->next_elapse_realtime
= v
->next_elapse
;
388 t
->next_elapse_realtime
= MIN(t
->next_elapse_realtime
, v
->next_elapse
);
390 found_realtime
= true;
398 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
399 base
= UNIT(t
)->inactive_exit_timestamp
.monotonic
;
405 if (detect_container() <= 0) {
406 /* CLOCK_MONOTONIC equals the uptime on Linux */
410 /* In a container we don't want to include the time the host
411 * was already up when the container started, so count from
412 * our own startup. */
415 base
= UNIT(t
)->manager
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
].monotonic
;
418 case TIMER_UNIT_ACTIVE
:
420 base
= trigger
->inactive_exit_timestamp
.monotonic
;
423 base
= t
->last_trigger
.monotonic
;
427 base
= MAX(base
, t
->last_trigger
.monotonic
);
431 case TIMER_UNIT_INACTIVE
:
433 base
= trigger
->inactive_enter_timestamp
.monotonic
;
436 base
= t
->last_trigger
.monotonic
;
440 base
= MAX(base
, t
->last_trigger
.monotonic
);
445 assert_not_reached("Unknown timer base");
448 v
->next_elapse
= usec_add(usec_shift_clock(base
, CLOCK_MONOTONIC
, TIMER_MONOTONIC_CLOCK(t
)), v
->value
);
451 v
->next_elapse
< triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)) &&
452 IN_SET(v
->base
, TIMER_ACTIVE
, TIMER_BOOT
, TIMER_STARTUP
)) {
453 /* This is a one time trigger, disable it now */
458 if (!found_monotonic
)
459 t
->next_elapse_monotonic_or_boottime
= v
->next_elapse
;
461 t
->next_elapse_monotonic_or_boottime
= MIN(t
->next_elapse_monotonic_or_boottime
, v
->next_elapse
);
463 found_monotonic
= true;
467 if (!found_monotonic
&& !found_realtime
) {
468 log_unit_debug(UNIT(t
), "Timer is elapsed.");
469 timer_enter_elapsed(t
, leave_around
);
473 if (found_monotonic
) {
474 char buf
[FORMAT_TIMESPAN_MAX
];
477 add_random(t
, &t
->next_elapse_monotonic_or_boottime
);
479 left
= usec_sub_unsigned(t
->next_elapse_monotonic_or_boottime
, triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)));
480 log_unit_debug(UNIT(t
), "Monotonic timer elapses in %s.", format_timespan(buf
, sizeof(buf
), left
, 0));
482 if (t
->monotonic_event_source
) {
483 r
= sd_event_source_set_time(t
->monotonic_event_source
, t
->next_elapse_monotonic_or_boottime
);
487 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_ONESHOT
);
492 r
= sd_event_add_time(
493 UNIT(t
)->manager
->event
,
494 &t
->monotonic_event_source
,
495 t
->wake_system
? CLOCK_BOOTTIME_ALARM
: CLOCK_MONOTONIC
,
496 t
->next_elapse_monotonic_or_boottime
, t
->accuracy_usec
,
501 (void) sd_event_source_set_description(t
->monotonic_event_source
, "timer-monotonic");
504 } else if (t
->monotonic_event_source
) {
506 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_OFF
);
511 if (found_realtime
) {
512 char buf
[FORMAT_TIMESTAMP_MAX
];
514 add_random(t
, &t
->next_elapse_realtime
);
516 log_unit_debug(UNIT(t
), "Realtime timer elapses at %s.", format_timestamp(buf
, sizeof(buf
), t
->next_elapse_realtime
));
518 if (t
->realtime_event_source
) {
519 r
= sd_event_source_set_time(t
->realtime_event_source
, t
->next_elapse_realtime
);
523 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_ONESHOT
);
527 r
= sd_event_add_time(
528 UNIT(t
)->manager
->event
,
529 &t
->realtime_event_source
,
530 t
->wake_system
? CLOCK_REALTIME_ALARM
: CLOCK_REALTIME
,
531 t
->next_elapse_realtime
, t
->accuracy_usec
,
536 (void) sd_event_source_set_description(t
->realtime_event_source
, "timer-realtime");
539 } else if (t
->realtime_event_source
) {
541 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_OFF
);
546 timer_set_state(t
, TIMER_WAITING
);
550 log_unit_warning_errno(UNIT(t
), r
, "Failed to enter waiting state: %m");
551 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
554 static void timer_enter_running(Timer
*t
) {
555 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
561 /* Don't start job if we are supposed to go down */
562 if (unit_stop_pending(UNIT(t
)))
565 trigger
= UNIT_TRIGGER(UNIT(t
));
567 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
568 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
572 r
= manager_add_job(UNIT(t
)->manager
, JOB_START
, trigger
, JOB_REPLACE
, &error
, NULL
);
576 dual_timestamp_get(&t
->last_trigger
);
579 touch_file(t
->stamp_path
, true, t
->last_trigger
.realtime
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
581 timer_set_state(t
, TIMER_RUNNING
);
585 log_unit_warning(UNIT(t
), "Failed to queue unit startup job: %s", bus_error_message(&error
, r
));
586 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
589 static int timer_start(Unit
*u
) {
596 assert(IN_SET(t
->state
, TIMER_DEAD
, TIMER_FAILED
));
598 trigger
= UNIT_TRIGGER(u
);
599 if (!trigger
|| trigger
->load_state
!= UNIT_LOADED
) {
600 log_unit_error(u
, "Refusing to start, unit to trigger not loaded.");
604 r
= unit_start_limit_test(u
);
606 timer_enter_dead(t
, TIMER_FAILURE_START_LIMIT_HIT
);
610 r
= unit_acquire_invocation_id(u
);
614 t
->last_trigger
= DUAL_TIMESTAMP_NULL
;
616 /* Reenable all timers that depend on unit activation time */
617 LIST_FOREACH(value
, v
, t
->values
)
618 if (v
->base
== TIMER_ACTIVE
)
624 if (stat(t
->stamp_path
, &st
) >= 0) {
627 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
628 * something is wrong with the system clock. */
630 ft
= timespec_load(&st
.st_mtim
);
631 if (ft
< now(CLOCK_REALTIME
))
632 t
->last_trigger
.realtime
= ft
;
634 char z
[FORMAT_TIMESTAMP_MAX
];
636 log_unit_warning(u
, "Not using persistent file timestamp %s as it is in the future.",
637 format_timestamp(z
, sizeof(z
), ft
));
640 } else if (errno
== ENOENT
)
641 /* The timer has never run before,
642 * make sure a stamp file exists.
644 (void) touch_file(t
->stamp_path
, true, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
647 t
->result
= TIMER_SUCCESS
;
648 timer_enter_waiting(t
, true);
652 static int timer_stop(Unit
*u
) {
656 assert(IN_SET(t
->state
, TIMER_WAITING
, TIMER_RUNNING
, TIMER_ELAPSED
));
658 timer_enter_dead(t
, TIMER_SUCCESS
);
662 static int timer_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
669 unit_serialize_item(u
, f
, "state", timer_state_to_string(t
->state
));
670 unit_serialize_item(u
, f
, "result", timer_result_to_string(t
->result
));
672 if (t
->last_trigger
.realtime
> 0)
673 unit_serialize_item_format(u
, f
, "last-trigger-realtime", "%" PRIu64
, t
->last_trigger
.realtime
);
675 if (t
->last_trigger
.monotonic
> 0)
676 unit_serialize_item_format(u
, f
, "last-trigger-monotonic", "%" PRIu64
, t
->last_trigger
.monotonic
);
681 static int timer_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
690 if (streq(key
, "state")) {
693 state
= timer_state_from_string(value
);
695 log_unit_debug(u
, "Failed to parse state value: %s", value
);
697 t
->deserialized_state
= state
;
698 } else if (streq(key
, "result")) {
701 f
= timer_result_from_string(value
);
703 log_unit_debug(u
, "Failed to parse result value: %s", value
);
704 else if (f
!= TIMER_SUCCESS
)
706 } else if (streq(key
, "last-trigger-realtime")) {
708 r
= safe_atou64(value
, &t
->last_trigger
.realtime
);
710 log_unit_debug(u
, "Failed to parse last-trigger-realtime value: %s", value
);
712 } else if (streq(key
, "last-trigger-monotonic")) {
714 r
= safe_atou64(value
, &t
->last_trigger
.monotonic
);
716 log_unit_debug(u
, "Failed to parse last-trigger-monotonic value: %s", value
);
719 log_unit_debug(u
, "Unknown serialization key: %s", key
);
724 _pure_
static UnitActiveState
timer_active_state(Unit
*u
) {
727 return state_translation_table
[TIMER(u
)->state
];
730 _pure_
static const char *timer_sub_state_to_string(Unit
*u
) {
733 return timer_state_to_string(TIMER(u
)->state
);
736 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
737 Timer
*t
= TIMER(userdata
);
741 if (t
->state
!= TIMER_WAITING
)
744 log_unit_debug(UNIT(t
), "Timer elapsed.");
745 timer_enter_running(t
);
749 static void timer_trigger_notify(Unit
*u
, Unit
*other
) {
756 if (other
->load_state
!= UNIT_LOADED
)
759 /* Reenable all timers that depend on unit state */
760 LIST_FOREACH(value
, v
, t
->values
)
761 if (IN_SET(v
->base
, TIMER_UNIT_ACTIVE
, TIMER_UNIT_INACTIVE
))
769 /* Recalculate sleep time */
770 timer_enter_waiting(t
, false);
775 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
))) {
776 log_unit_debug(UNIT(t
), "Got notified about unit deactivation.");
777 timer_enter_waiting(t
, false);
786 assert_not_reached("Unknown timer state");
790 static void timer_reset_failed(Unit
*u
) {
795 if (t
->state
== TIMER_FAILED
)
796 timer_set_state(t
, TIMER_DEAD
);
798 t
->result
= TIMER_SUCCESS
;
801 static void timer_time_change(Unit
*u
) {
807 if (t
->state
!= TIMER_WAITING
)
810 /* If we appear to have triggered in the future, the system clock must
811 * have been set backwards. So let's rewind our own clock and allow
812 * the future trigger(s) to happen again :). Exactly the same as when
813 * you start a timer unit with Persistent=yes. */
814 ts
= now(CLOCK_REALTIME
);
815 if (t
->last_trigger
.realtime
> ts
)
816 t
->last_trigger
.realtime
= ts
;
818 log_unit_debug(u
, "Time change, recalculating next elapse.");
819 timer_enter_waiting(t
, false);
822 static const char* const timer_base_table
[_TIMER_BASE_MAX
] = {
823 [TIMER_ACTIVE
] = "OnActiveSec",
824 [TIMER_BOOT
] = "OnBootSec",
825 [TIMER_STARTUP
] = "OnStartupSec",
826 [TIMER_UNIT_ACTIVE
] = "OnUnitActiveSec",
827 [TIMER_UNIT_INACTIVE
] = "OnUnitInactiveSec",
828 [TIMER_CALENDAR
] = "OnCalendar"
831 DEFINE_STRING_TABLE_LOOKUP(timer_base
, TimerBase
);
833 static const char* const timer_result_table
[_TIMER_RESULT_MAX
] = {
834 [TIMER_SUCCESS
] = "success",
835 [TIMER_FAILURE_RESOURCES
] = "resources",
836 [TIMER_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
839 DEFINE_STRING_TABLE_LOOKUP(timer_result
, TimerResult
);
841 const UnitVTable timer_vtable
= {
842 .object_size
= sizeof(Timer
),
848 .private_section
= "Timer",
854 .coldplug
= timer_coldplug
,
858 .start
= timer_start
,
861 .serialize
= timer_serialize
,
862 .deserialize_item
= timer_deserialize_item
,
864 .active_state
= timer_active_state
,
865 .sub_state_to_string
= timer_sub_state_to_string
,
867 .trigger_notify
= timer_trigger_notify
,
869 .reset_failed
= timer_reset_failed
,
870 .time_change
= timer_time_change
,
872 .bus_vtable
= bus_timer_vtable
,
873 .bus_set_property
= bus_timer_set_property
,
875 .can_transient
= true,