1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "alloc-util.h"
8 #include "dbus-timer.h"
11 #include "parse-util.h"
12 #include "random-util.h"
13 #include "serialize.h"
15 #include "string-table.h"
16 #include "string-util.h"
18 #include "unit-name.h"
20 #include "user-util.h"
23 static const UnitActiveState state_translation_table
[_TIMER_STATE_MAX
] = {
24 [TIMER_DEAD
] = UNIT_INACTIVE
,
25 [TIMER_WAITING
] = UNIT_ACTIVE
,
26 [TIMER_RUNNING
] = UNIT_ACTIVE
,
27 [TIMER_ELAPSED
] = UNIT_ACTIVE
,
28 [TIMER_FAILED
] = UNIT_FAILED
31 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
);
33 static void timer_init(Unit
*u
) {
37 assert(u
->load_state
== UNIT_STUB
);
39 t
->next_elapse_monotonic_or_boottime
= USEC_INFINITY
;
40 t
->next_elapse_realtime
= USEC_INFINITY
;
41 t
->accuracy_usec
= u
->manager
->default_timer_accuracy_usec
;
42 t
->remain_after_elapse
= true;
45 void timer_free_values(Timer
*t
) {
50 while ((v
= t
->values
)) {
51 LIST_REMOVE(value
, t
->values
, v
);
52 calendar_spec_free(v
->calendar_spec
);
57 static void timer_done(Unit
*u
) {
64 t
->monotonic_event_source
= sd_event_source_unref(t
->monotonic_event_source
);
65 t
->realtime_event_source
= sd_event_source_unref(t
->realtime_event_source
);
70 static int timer_verify(Timer
*t
) {
73 if (UNIT(t
)->load_state
!= UNIT_LOADED
)
77 log_unit_error(UNIT(t
), "Timer unit lacks value setting. Refusing.");
84 static int timer_add_default_dependencies(Timer
*t
) {
90 if (!UNIT(t
)->default_dependencies
)
93 r
= unit_add_dependency_by_name(UNIT(t
), UNIT_BEFORE
, SPECIAL_TIMERS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
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
);
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
);
112 return unit_add_two_dependencies_by_name(UNIT(t
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
115 static int timer_add_trigger_dependencies(Timer
*t
) {
121 if (!hashmap_isempty(UNIT(t
)->dependencies
[UNIT_TRIGGERS
]))
124 r
= unit_load_related_unit(UNIT(t
), ".service", &x
);
128 return unit_add_two_dependencies(UNIT(t
), UNIT_BEFORE
, UNIT_TRIGGERS
, x
, true, UNIT_DEPENDENCY_IMPLICIT
);
131 static int timer_setup_persistent(Timer
*t
) {
139 if (MANAGER_IS_SYSTEM(UNIT(t
)->manager
)) {
141 r
= unit_require_mounts_for(UNIT(t
), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE
);
145 t
->stamp_path
= strappend("/var/lib/systemd/timers/stamp-", UNIT(t
)->id
);
149 e
= getenv("XDG_DATA_HOME");
151 t
->stamp_path
= strjoin(e
, "/systemd/timers/stamp-", UNIT(t
)->id
);
154 _cleanup_free_
char *h
= NULL
;
156 r
= get_home_dir(&h
);
158 return log_unit_error_errno(UNIT(t
), r
, "Failed to determine home directory: %m");
160 t
->stamp_path
= strjoin(h
, "/.local/share/systemd/timers/stamp-", UNIT(t
)->id
);
170 static int timer_load(Unit
*u
) {
175 assert(u
->load_state
== UNIT_STUB
);
177 r
= unit_load_fragment_and_dropin(u
);
181 if (u
->load_state
== UNIT_LOADED
) {
183 r
= timer_add_trigger_dependencies(t
);
187 r
= timer_setup_persistent(t
);
191 r
= timer_add_default_dependencies(t
);
196 return timer_verify(t
);
199 static void timer_dump(Unit
*u
, FILE *f
, const char *prefix
) {
200 char buf
[FORMAT_TIMESPAN_MAX
];
205 trigger
= UNIT_TRIGGER(u
);
208 "%sTimer State: %s\n"
214 "%sRemainAfterElapse: %s\n",
215 prefix
, timer_state_to_string(t
->state
),
216 prefix
, timer_result_to_string(t
->result
),
217 prefix
, trigger
? trigger
->id
: "n/a",
218 prefix
, yes_no(t
->persistent
),
219 prefix
, yes_no(t
->wake_system
),
220 prefix
, format_timespan(buf
, sizeof(buf
), t
->accuracy_usec
, 1),
221 prefix
, yes_no(t
->remain_after_elapse
));
223 LIST_FOREACH(value
, v
, t
->values
) {
225 if (v
->base
== TIMER_CALENDAR
) {
226 _cleanup_free_
char *p
= NULL
;
228 (void) calendar_spec_to_string(v
->calendar_spec
, &p
);
233 timer_base_to_string(v
->base
),
236 char timespan1
[FORMAT_TIMESPAN_MAX
];
241 timer_base_to_string(v
->base
),
242 format_timespan(timespan1
, sizeof(timespan1
), v
->value
, 0));
247 static void timer_set_state(Timer
*t
, TimerState state
) {
248 TimerState old_state
;
251 if (t
->state
!= state
)
252 bus_unit_send_pending_change_signal(UNIT(t
), false);
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 time_change
);
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 unit_log_result(UNIT(t
), t
->result
== TIMER_SUCCESS
, timer_result_to_string(t
->result
));
296 timer_set_state(t
, t
->result
!= TIMER_SUCCESS
? TIMER_FAILED
: TIMER_DEAD
);
299 static void timer_enter_elapsed(Timer
*t
, bool leave_around
) {
302 /* If a unit is marked with RemainAfterElapse=yes we leave it
303 * around even after it elapsed once, so that starting it
304 * later again does not necessarily mean immediate
305 * retriggering. We unconditionally leave units with
306 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
307 * since they might be restarted automatically at any time
310 if (t
->remain_after_elapse
|| leave_around
)
311 timer_set_state(t
, TIMER_ELAPSED
);
313 timer_enter_dead(t
, TIMER_SUCCESS
);
316 static void add_random(Timer
*t
, usec_t
*v
) {
317 char s
[FORMAT_TIMESPAN_MAX
];
323 if (t
->random_usec
== 0)
325 if (*v
== USEC_INFINITY
)
328 add
= random_u64() % t
->random_usec
;
330 if (*v
+ add
< *v
) /* overflow */
331 *v
= (usec_t
) -2; /* Highest possible value, that is not USEC_INFINITY */
335 log_unit_debug(UNIT(t
), "Adding %s random time.", format_timespan(s
, sizeof(s
), add
, 0));
338 static void timer_enter_waiting(Timer
*t
, bool time_change
) {
339 bool found_monotonic
= false, found_realtime
= false;
340 bool leave_around
= false;
348 trigger
= UNIT_TRIGGER(UNIT(t
));
350 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
351 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
355 triple_timestamp_get(&ts
);
356 t
->next_elapse_monotonic_or_boottime
= t
->next_elapse_realtime
= 0;
358 LIST_FOREACH(value
, v
, t
->values
) {
362 if (v
->base
== TIMER_CALENDAR
) {
365 /* If we know the last time this was
366 * triggered, schedule the job based relative
367 * to that. If we don't, just start from
368 * the activation time. */
370 if (t
->last_trigger
.realtime
> 0)
371 b
= t
->last_trigger
.realtime
;
373 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
374 b
= UNIT(t
)->inactive_exit_timestamp
.realtime
;
379 r
= calendar_spec_next_usec(v
->calendar_spec
, b
, &v
->next_elapse
);
383 /* To make the delay due to RandomizedDelaySec= work even at boot,
384 * if the scheduled time has already passed, set the time when systemd
385 * first started as the scheduled time.
386 * Also, we don't have to check t->persistent since the logic implicitly express true. */
387 if (v
->next_elapse
< UNIT(t
)->manager
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
].realtime
)
388 v
->next_elapse
= UNIT(t
)->manager
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
].realtime
;
391 t
->next_elapse_realtime
= v
->next_elapse
;
393 t
->next_elapse_realtime
= MIN(t
->next_elapse_realtime
, v
->next_elapse
);
395 found_realtime
= true;
403 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
404 base
= UNIT(t
)->inactive_exit_timestamp
.monotonic
;
410 if (detect_container() <= 0) {
411 /* CLOCK_MONOTONIC equals the uptime on Linux */
415 /* In a container we don't want to include the time the host
416 * was already up when the container started, so count from
417 * our own startup. */
420 base
= UNIT(t
)->manager
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
].monotonic
;
423 case TIMER_UNIT_ACTIVE
:
425 base
= trigger
->inactive_exit_timestamp
.monotonic
;
428 base
= t
->last_trigger
.monotonic
;
432 base
= MAX(base
, t
->last_trigger
.monotonic
);
436 case TIMER_UNIT_INACTIVE
:
438 base
= trigger
->inactive_enter_timestamp
.monotonic
;
441 base
= t
->last_trigger
.monotonic
;
445 base
= MAX(base
, t
->last_trigger
.monotonic
);
450 assert_not_reached("Unknown timer base");
453 v
->next_elapse
= usec_add(usec_shift_clock(base
, CLOCK_MONOTONIC
, TIMER_MONOTONIC_CLOCK(t
)), v
->value
);
455 if (dual_timestamp_is_set(&t
->last_trigger
) &&
457 v
->next_elapse
< triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)) &&
458 IN_SET(v
->base
, TIMER_ACTIVE
, TIMER_BOOT
, TIMER_STARTUP
)) {
459 /* This is a one time trigger, disable it now */
464 if (!found_monotonic
)
465 t
->next_elapse_monotonic_or_boottime
= v
->next_elapse
;
467 t
->next_elapse_monotonic_or_boottime
= MIN(t
->next_elapse_monotonic_or_boottime
, v
->next_elapse
);
469 found_monotonic
= true;
473 if (!found_monotonic
&& !found_realtime
) {
474 log_unit_debug(UNIT(t
), "Timer is elapsed.");
475 timer_enter_elapsed(t
, leave_around
);
479 if (found_monotonic
) {
480 char buf
[FORMAT_TIMESPAN_MAX
];
483 add_random(t
, &t
->next_elapse_monotonic_or_boottime
);
485 left
= usec_sub_unsigned(t
->next_elapse_monotonic_or_boottime
, triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)));
486 log_unit_debug(UNIT(t
), "Monotonic timer elapses in %s.", format_timespan(buf
, sizeof(buf
), left
, 0));
488 if (t
->monotonic_event_source
) {
489 r
= sd_event_source_set_time(t
->monotonic_event_source
, t
->next_elapse_monotonic_or_boottime
);
493 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_ONESHOT
);
498 r
= sd_event_add_time(
499 UNIT(t
)->manager
->event
,
500 &t
->monotonic_event_source
,
501 t
->wake_system
? CLOCK_BOOTTIME_ALARM
: CLOCK_MONOTONIC
,
502 t
->next_elapse_monotonic_or_boottime
, t
->accuracy_usec
,
507 (void) sd_event_source_set_description(t
->monotonic_event_source
, "timer-monotonic");
510 } else if (t
->monotonic_event_source
) {
512 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_OFF
);
517 if (found_realtime
) {
518 char buf
[FORMAT_TIMESTAMP_MAX
];
520 add_random(t
, &t
->next_elapse_realtime
);
522 log_unit_debug(UNIT(t
), "Realtime timer elapses at %s.", format_timestamp(buf
, sizeof(buf
), t
->next_elapse_realtime
));
524 if (t
->realtime_event_source
) {
525 r
= sd_event_source_set_time(t
->realtime_event_source
, t
->next_elapse_realtime
);
529 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_ONESHOT
);
533 r
= sd_event_add_time(
534 UNIT(t
)->manager
->event
,
535 &t
->realtime_event_source
,
536 t
->wake_system
? CLOCK_REALTIME_ALARM
: CLOCK_REALTIME
,
537 t
->next_elapse_realtime
, t
->accuracy_usec
,
542 (void) sd_event_source_set_description(t
->realtime_event_source
, "timer-realtime");
545 } else if (t
->realtime_event_source
) {
547 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_OFF
);
552 timer_set_state(t
, TIMER_WAITING
);
556 log_unit_warning_errno(UNIT(t
), r
, "Failed to enter waiting state: %m");
557 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
560 static void timer_enter_running(Timer
*t
) {
561 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
567 /* Don't start job if we are supposed to go down */
568 if (unit_stop_pending(UNIT(t
)))
571 trigger
= UNIT_TRIGGER(UNIT(t
));
573 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
574 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
578 r
= manager_add_job(UNIT(t
)->manager
, JOB_START
, trigger
, JOB_REPLACE
, &error
, NULL
);
582 dual_timestamp_get(&t
->last_trigger
);
585 touch_file(t
->stamp_path
, true, t
->last_trigger
.realtime
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
587 timer_set_state(t
, TIMER_RUNNING
);
591 log_unit_warning(UNIT(t
), "Failed to queue unit startup job: %s", bus_error_message(&error
, r
));
592 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
595 static int timer_start(Unit
*u
) {
602 assert(IN_SET(t
->state
, TIMER_DEAD
, TIMER_FAILED
));
604 trigger
= UNIT_TRIGGER(u
);
605 if (!trigger
|| trigger
->load_state
!= UNIT_LOADED
) {
606 log_unit_error(u
, "Refusing to start, unit to trigger not loaded.");
610 r
= unit_start_limit_test(u
);
612 timer_enter_dead(t
, TIMER_FAILURE_START_LIMIT_HIT
);
616 r
= unit_acquire_invocation_id(u
);
620 t
->last_trigger
= DUAL_TIMESTAMP_NULL
;
622 /* Reenable all timers that depend on unit activation time */
623 LIST_FOREACH(value
, v
, t
->values
)
624 if (v
->base
== TIMER_ACTIVE
)
630 if (stat(t
->stamp_path
, &st
) >= 0) {
633 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
634 * something is wrong with the system clock. */
636 ft
= timespec_load(&st
.st_mtim
);
637 if (ft
< now(CLOCK_REALTIME
))
638 t
->last_trigger
.realtime
= ft
;
640 char z
[FORMAT_TIMESTAMP_MAX
];
642 log_unit_warning(u
, "Not using persistent file timestamp %s as it is in the future.",
643 format_timestamp(z
, sizeof(z
), ft
));
646 } else if (errno
== ENOENT
)
647 /* The timer has never run before,
648 * make sure a stamp file exists.
650 (void) touch_file(t
->stamp_path
, true, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
653 t
->result
= TIMER_SUCCESS
;
654 timer_enter_waiting(t
, false);
658 static int timer_stop(Unit
*u
) {
662 assert(IN_SET(t
->state
, TIMER_WAITING
, TIMER_RUNNING
, TIMER_ELAPSED
));
664 timer_enter_dead(t
, TIMER_SUCCESS
);
668 static int timer_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
675 (void) serialize_item(f
, "state", timer_state_to_string(t
->state
));
676 (void) serialize_item(f
, "result", timer_result_to_string(t
->result
));
678 if (t
->last_trigger
.realtime
> 0)
679 (void) serialize_usec(f
, "last-trigger-realtime", t
->last_trigger
.realtime
);
681 if (t
->last_trigger
.monotonic
> 0)
682 (void) serialize_usec(f
, "last-trigger-monotonic", t
->last_trigger
.monotonic
);
687 static int timer_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
695 if (streq(key
, "state")) {
698 state
= timer_state_from_string(value
);
700 log_unit_debug(u
, "Failed to parse state value: %s", value
);
702 t
->deserialized_state
= state
;
704 } else if (streq(key
, "result")) {
707 f
= timer_result_from_string(value
);
709 log_unit_debug(u
, "Failed to parse result value: %s", value
);
710 else if (f
!= TIMER_SUCCESS
)
713 } else if (streq(key
, "last-trigger-realtime"))
714 (void) deserialize_usec(value
, &t
->last_trigger
.realtime
);
715 else if (streq(key
, "last-trigger-monotonic"))
716 (void) deserialize_usec(value
, &t
->last_trigger
.monotonic
);
718 log_unit_debug(u
, "Unknown serialization key: %s", key
);
723 _pure_
static UnitActiveState
timer_active_state(Unit
*u
) {
726 return state_translation_table
[TIMER(u
)->state
];
729 _pure_
static const char *timer_sub_state_to_string(Unit
*u
) {
732 return timer_state_to_string(TIMER(u
)->state
);
735 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
736 Timer
*t
= TIMER(userdata
);
740 if (t
->state
!= TIMER_WAITING
)
743 log_unit_debug(UNIT(t
), "Timer elapsed.");
744 timer_enter_running(t
);
748 static void timer_trigger_notify(Unit
*u
, Unit
*other
) {
755 if (other
->load_state
!= UNIT_LOADED
)
758 /* Reenable all timers that depend on unit state */
759 LIST_FOREACH(value
, v
, t
->values
)
760 if (IN_SET(v
->base
, TIMER_UNIT_ACTIVE
, TIMER_UNIT_INACTIVE
))
768 /* Recalculate sleep time */
769 timer_enter_waiting(t
, false);
774 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
))) {
775 log_unit_debug(UNIT(t
), "Got notified about unit deactivation.");
776 timer_enter_waiting(t
, false);
785 assert_not_reached("Unknown timer state");
789 static void timer_reset_failed(Unit
*u
) {
794 if (t
->state
== TIMER_FAILED
)
795 timer_set_state(t
, TIMER_DEAD
);
797 t
->result
= TIMER_SUCCESS
;
800 static void timer_time_change(Unit
*u
) {
806 if (t
->state
!= TIMER_WAITING
)
809 /* If we appear to have triggered in the future, the system clock must
810 * have been set backwards. So let's rewind our own clock and allow
811 * the future trigger(s) to happen again :). Exactly the same as when
812 * you start a timer unit with Persistent=yes. */
813 ts
= now(CLOCK_REALTIME
);
814 if (t
->last_trigger
.realtime
> ts
)
815 t
->last_trigger
.realtime
= ts
;
817 log_unit_debug(u
, "Time change, recalculating next elapse.");
818 timer_enter_waiting(t
, true);
821 static void timer_timezone_change(Unit
*u
) {
826 if (t
->state
!= TIMER_WAITING
)
829 log_unit_debug(u
, "Timezone change, recalculating next elapse.");
830 timer_enter_waiting(t
, false);
833 static const char* const timer_base_table
[_TIMER_BASE_MAX
] = {
834 [TIMER_ACTIVE
] = "OnActiveSec",
835 [TIMER_BOOT
] = "OnBootSec",
836 [TIMER_STARTUP
] = "OnStartupSec",
837 [TIMER_UNIT_ACTIVE
] = "OnUnitActiveSec",
838 [TIMER_UNIT_INACTIVE
] = "OnUnitInactiveSec",
839 [TIMER_CALENDAR
] = "OnCalendar"
842 DEFINE_STRING_TABLE_LOOKUP(timer_base
, TimerBase
);
844 static const char* const timer_result_table
[_TIMER_RESULT_MAX
] = {
845 [TIMER_SUCCESS
] = "success",
846 [TIMER_FAILURE_RESOURCES
] = "resources",
847 [TIMER_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
850 DEFINE_STRING_TABLE_LOOKUP(timer_result
, TimerResult
);
852 const UnitVTable timer_vtable
= {
853 .object_size
= sizeof(Timer
),
859 .private_section
= "Timer",
865 .coldplug
= timer_coldplug
,
869 .start
= timer_start
,
872 .serialize
= timer_serialize
,
873 .deserialize_item
= timer_deserialize_item
,
875 .active_state
= timer_active_state
,
876 .sub_state_to_string
= timer_sub_state_to_string
,
878 .trigger_notify
= timer_trigger_notify
,
880 .reset_failed
= timer_reset_failed
,
881 .time_change
= timer_time_change
,
882 .timezone_change
= timer_timezone_change
,
884 .bus_vtable
= bus_timer_vtable
,
885 .bus_set_property
= bus_timer_set_property
,
887 .can_transient
= true,