1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "alloc-util.h"
8 #include "dbus-timer.h"
10 #include "parse-util.h"
11 #include "random-util.h"
12 #include "serialize.h"
14 #include "string-table.h"
15 #include "string-util.h"
17 #include "unit-name.h"
19 #include "user-util.h"
22 static const UnitActiveState state_translation_table
[_TIMER_STATE_MAX
] = {
23 [TIMER_DEAD
] = UNIT_INACTIVE
,
24 [TIMER_WAITING
] = UNIT_ACTIVE
,
25 [TIMER_RUNNING
] = UNIT_ACTIVE
,
26 [TIMER_ELAPSED
] = UNIT_ACTIVE
,
27 [TIMER_FAILED
] = UNIT_FAILED
30 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
);
32 static void timer_init(Unit
*u
) {
36 assert(u
->load_state
== UNIT_STUB
);
38 t
->next_elapse_monotonic_or_boottime
= USEC_INFINITY
;
39 t
->next_elapse_realtime
= USEC_INFINITY
;
40 t
->accuracy_usec
= u
->manager
->default_timer_accuracy_usec
;
41 t
->remain_after_elapse
= true;
44 void timer_free_values(Timer
*t
) {
49 while ((v
= t
->values
)) {
50 LIST_REMOVE(value
, t
->values
, v
);
51 calendar_spec_free(v
->calendar_spec
);
56 static void timer_done(Unit
*u
) {
63 t
->monotonic_event_source
= sd_event_source_unref(t
->monotonic_event_source
);
64 t
->realtime_event_source
= sd_event_source_unref(t
->realtime_event_source
);
69 static int timer_verify(Timer
*t
) {
72 if (UNIT(t
)->load_state
!= UNIT_LOADED
)
76 log_unit_error(UNIT(t
), "Timer unit lacks value setting. Refusing.");
83 static int timer_add_default_dependencies(Timer
*t
) {
89 if (!UNIT(t
)->default_dependencies
)
92 r
= unit_add_dependency_by_name(UNIT(t
), UNIT_BEFORE
, SPECIAL_TIMERS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
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
);
101 LIST_FOREACH(value
, v
, t
->values
) {
102 if (v
->base
== TIMER_CALENDAR
) {
103 r
= unit_add_dependency_by_name(UNIT(t
), UNIT_AFTER
, SPECIAL_TIME_SYNC_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
111 return unit_add_two_dependencies_by_name(UNIT(t
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
114 static int timer_add_trigger_dependencies(Timer
*t
) {
120 if (!hashmap_isempty(UNIT(t
)->dependencies
[UNIT_TRIGGERS
]))
123 r
= unit_load_related_unit(UNIT(t
), ".service", &x
);
127 return unit_add_two_dependencies(UNIT(t
), UNIT_BEFORE
, UNIT_TRIGGERS
, x
, true, UNIT_DEPENDENCY_IMPLICIT
);
130 static int timer_setup_persistent(Timer
*t
) {
138 if (MANAGER_IS_SYSTEM(UNIT(t
)->manager
)) {
140 r
= unit_require_mounts_for(UNIT(t
), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE
);
144 t
->stamp_path
= strappend("/var/lib/systemd/timers/stamp-", UNIT(t
)->id
);
148 e
= getenv("XDG_DATA_HOME");
150 t
->stamp_path
= strjoin(e
, "/systemd/timers/stamp-", UNIT(t
)->id
);
153 _cleanup_free_
char *h
= NULL
;
155 r
= get_home_dir(&h
);
157 return log_unit_error_errno(UNIT(t
), r
, "Failed to determine home directory: %m");
159 t
->stamp_path
= strjoin(h
, "/.local/share/systemd/timers/stamp-", UNIT(t
)->id
);
169 static int timer_load(Unit
*u
) {
174 assert(u
->load_state
== UNIT_STUB
);
176 r
= unit_load_fragment_and_dropin(u
);
180 if (u
->load_state
== UNIT_LOADED
) {
182 r
= timer_add_trigger_dependencies(t
);
186 r
= timer_setup_persistent(t
);
190 r
= timer_add_default_dependencies(t
);
195 return timer_verify(t
);
198 static void timer_dump(Unit
*u
, FILE *f
, const char *prefix
) {
199 char buf
[FORMAT_TIMESPAN_MAX
];
204 trigger
= UNIT_TRIGGER(u
);
207 "%sTimer State: %s\n"
213 "%sRemainAfterElapse: %s\n",
214 prefix
, timer_state_to_string(t
->state
),
215 prefix
, timer_result_to_string(t
->result
),
216 prefix
, trigger
? trigger
->id
: "n/a",
217 prefix
, yes_no(t
->persistent
),
218 prefix
, yes_no(t
->wake_system
),
219 prefix
, format_timespan(buf
, sizeof(buf
), t
->accuracy_usec
, 1),
220 prefix
, yes_no(t
->remain_after_elapse
));
222 LIST_FOREACH(value
, v
, t
->values
) {
224 if (v
->base
== TIMER_CALENDAR
) {
225 _cleanup_free_
char *p
= NULL
;
227 (void) calendar_spec_to_string(v
->calendar_spec
, &p
);
232 timer_base_to_string(v
->base
),
235 char timespan1
[FORMAT_TIMESPAN_MAX
];
240 timer_base_to_string(v
->base
),
241 format_timespan(timespan1
, sizeof(timespan1
), v
->value
, 0));
246 static void timer_set_state(Timer
*t
, TimerState state
) {
247 TimerState old_state
;
250 old_state
= t
->state
;
253 if (state
!= TIMER_WAITING
) {
254 t
->monotonic_event_source
= sd_event_source_unref(t
->monotonic_event_source
);
255 t
->realtime_event_source
= sd_event_source_unref(t
->realtime_event_source
);
256 t
->next_elapse_monotonic_or_boottime
= USEC_INFINITY
;
257 t
->next_elapse_realtime
= USEC_INFINITY
;
260 if (state
!= old_state
)
261 log_unit_debug(UNIT(t
), "Changed %s -> %s", timer_state_to_string(old_state
), timer_state_to_string(state
));
263 unit_notify(UNIT(t
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
266 static void timer_enter_waiting(Timer
*t
, bool initial
, bool time_change
);
268 static int timer_coldplug(Unit
*u
) {
272 assert(t
->state
== TIMER_DEAD
);
274 if (t
->deserialized_state
== t
->state
)
277 if (t
->deserialized_state
== TIMER_WAITING
)
278 timer_enter_waiting(t
, false, false);
280 timer_set_state(t
, t
->deserialized_state
);
285 static void timer_enter_dead(Timer
*t
, TimerResult f
) {
288 if (t
->result
== TIMER_SUCCESS
)
291 unit_log_result(UNIT(t
), t
->result
== TIMER_SUCCESS
, timer_result_to_string(t
->result
));
292 timer_set_state(t
, t
->result
!= TIMER_SUCCESS
? TIMER_FAILED
: TIMER_DEAD
);
295 static void timer_enter_elapsed(Timer
*t
, bool leave_around
) {
298 /* If a unit is marked with RemainAfterElapse=yes we leave it
299 * around even after it elapsed once, so that starting it
300 * later again does not necessarily mean immediate
301 * retriggering. We unconditionally leave units with
302 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
303 * since they might be restarted automatically at any time
306 if (t
->remain_after_elapse
|| leave_around
)
307 timer_set_state(t
, TIMER_ELAPSED
);
309 timer_enter_dead(t
, TIMER_SUCCESS
);
312 static void add_random(Timer
*t
, usec_t
*v
) {
313 char s
[FORMAT_TIMESPAN_MAX
];
319 if (t
->random_usec
== 0)
321 if (*v
== USEC_INFINITY
)
324 add
= random_u64() % t
->random_usec
;
326 if (*v
+ add
< *v
) /* overflow */
327 *v
= (usec_t
) -2; /* Highest possible value, that is not USEC_INFINITY */
331 log_unit_debug(UNIT(t
), "Adding %s random time.", format_timespan(s
, sizeof(s
), add
, 0));
334 static void timer_enter_waiting(Timer
*t
, bool initial
, bool time_change
) {
335 bool found_monotonic
= false, found_realtime
= false;
336 bool leave_around
= false;
344 trigger
= UNIT_TRIGGER(UNIT(t
));
346 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
347 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
351 triple_timestamp_get(&ts
);
352 t
->next_elapse_monotonic_or_boottime
= t
->next_elapse_realtime
= 0;
354 LIST_FOREACH(value
, v
, t
->values
) {
358 if (v
->base
== TIMER_CALENDAR
) {
361 /* If we know the last time this was
362 * triggered, schedule the job based relative
363 * to that. If we don't, just start from
364 * the activation time. */
366 if (t
->last_trigger
.realtime
> 0)
367 b
= t
->last_trigger
.realtime
;
369 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
370 b
= UNIT(t
)->inactive_exit_timestamp
.realtime
;
375 r
= calendar_spec_next_usec(v
->calendar_spec
, b
, &v
->next_elapse
);
380 t
->next_elapse_realtime
= v
->next_elapse
;
382 t
->next_elapse_realtime
= MIN(t
->next_elapse_realtime
, v
->next_elapse
);
384 found_realtime
= true;
392 if (state_translation_table
[t
->state
] == UNIT_ACTIVE
)
393 base
= UNIT(t
)->inactive_exit_timestamp
.monotonic
;
399 if (detect_container() <= 0) {
400 /* CLOCK_MONOTONIC equals the uptime on Linux */
404 /* In a container we don't want to include the time the host
405 * was already up when the container started, so count from
406 * our own startup. */
409 base
= UNIT(t
)->manager
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
].monotonic
;
412 case TIMER_UNIT_ACTIVE
:
414 base
= trigger
->inactive_exit_timestamp
.monotonic
;
417 base
= t
->last_trigger
.monotonic
;
421 base
= MAX(base
, t
->last_trigger
.monotonic
);
425 case TIMER_UNIT_INACTIVE
:
427 base
= trigger
->inactive_enter_timestamp
.monotonic
;
430 base
= t
->last_trigger
.monotonic
;
434 base
= MAX(base
, t
->last_trigger
.monotonic
);
439 assert_not_reached("Unknown timer base");
442 v
->next_elapse
= usec_add(usec_shift_clock(base
, CLOCK_MONOTONIC
, TIMER_MONOTONIC_CLOCK(t
)), v
->value
);
444 if (!initial
&& !time_change
&&
445 v
->next_elapse
< triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)) &&
446 IN_SET(v
->base
, TIMER_ACTIVE
, TIMER_BOOT
, TIMER_STARTUP
)) {
447 /* This is a one time trigger, disable it now */
452 if (!found_monotonic
)
453 t
->next_elapse_monotonic_or_boottime
= v
->next_elapse
;
455 t
->next_elapse_monotonic_or_boottime
= MIN(t
->next_elapse_monotonic_or_boottime
, v
->next_elapse
);
457 found_monotonic
= true;
461 if (!found_monotonic
&& !found_realtime
) {
462 log_unit_debug(UNIT(t
), "Timer is elapsed.");
463 timer_enter_elapsed(t
, leave_around
);
467 if (found_monotonic
) {
468 char buf
[FORMAT_TIMESPAN_MAX
];
471 add_random(t
, &t
->next_elapse_monotonic_or_boottime
);
473 left
= usec_sub_unsigned(t
->next_elapse_monotonic_or_boottime
, triple_timestamp_by_clock(&ts
, TIMER_MONOTONIC_CLOCK(t
)));
474 log_unit_debug(UNIT(t
), "Monotonic timer elapses in %s.", format_timespan(buf
, sizeof(buf
), left
, 0));
476 if (t
->monotonic_event_source
) {
477 r
= sd_event_source_set_time(t
->monotonic_event_source
, t
->next_elapse_monotonic_or_boottime
);
481 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_ONESHOT
);
486 r
= sd_event_add_time(
487 UNIT(t
)->manager
->event
,
488 &t
->monotonic_event_source
,
489 t
->wake_system
? CLOCK_BOOTTIME_ALARM
: CLOCK_MONOTONIC
,
490 t
->next_elapse_monotonic_or_boottime
, t
->accuracy_usec
,
495 (void) sd_event_source_set_description(t
->monotonic_event_source
, "timer-monotonic");
498 } else if (t
->monotonic_event_source
) {
500 r
= sd_event_source_set_enabled(t
->monotonic_event_source
, SD_EVENT_OFF
);
505 if (found_realtime
) {
506 char buf
[FORMAT_TIMESTAMP_MAX
];
508 add_random(t
, &t
->next_elapse_realtime
);
510 log_unit_debug(UNIT(t
), "Realtime timer elapses at %s.", format_timestamp(buf
, sizeof(buf
), t
->next_elapse_realtime
));
512 if (t
->realtime_event_source
) {
513 r
= sd_event_source_set_time(t
->realtime_event_source
, t
->next_elapse_realtime
);
517 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_ONESHOT
);
521 r
= sd_event_add_time(
522 UNIT(t
)->manager
->event
,
523 &t
->realtime_event_source
,
524 t
->wake_system
? CLOCK_REALTIME_ALARM
: CLOCK_REALTIME
,
525 t
->next_elapse_realtime
, t
->accuracy_usec
,
530 (void) sd_event_source_set_description(t
->realtime_event_source
, "timer-realtime");
533 } else if (t
->realtime_event_source
) {
535 r
= sd_event_source_set_enabled(t
->realtime_event_source
, SD_EVENT_OFF
);
540 timer_set_state(t
, TIMER_WAITING
);
544 log_unit_warning_errno(UNIT(t
), r
, "Failed to enter waiting state: %m");
545 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
548 static void timer_enter_running(Timer
*t
) {
549 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
555 /* Don't start job if we are supposed to go down */
556 if (unit_stop_pending(UNIT(t
)))
559 trigger
= UNIT_TRIGGER(UNIT(t
));
561 log_unit_error(UNIT(t
), "Unit to trigger vanished.");
562 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
566 r
= manager_add_job(UNIT(t
)->manager
, JOB_START
, trigger
, JOB_REPLACE
, &error
, NULL
);
570 dual_timestamp_get(&t
->last_trigger
);
573 touch_file(t
->stamp_path
, true, t
->last_trigger
.realtime
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
575 timer_set_state(t
, TIMER_RUNNING
);
579 log_unit_warning(UNIT(t
), "Failed to queue unit startup job: %s", bus_error_message(&error
, r
));
580 timer_enter_dead(t
, TIMER_FAILURE_RESOURCES
);
583 static int timer_start(Unit
*u
) {
590 assert(IN_SET(t
->state
, TIMER_DEAD
, TIMER_FAILED
));
592 trigger
= UNIT_TRIGGER(u
);
593 if (!trigger
|| trigger
->load_state
!= UNIT_LOADED
) {
594 log_unit_error(u
, "Refusing to start, unit to trigger not loaded.");
598 r
= unit_start_limit_test(u
);
600 timer_enter_dead(t
, TIMER_FAILURE_START_LIMIT_HIT
);
604 r
= unit_acquire_invocation_id(u
);
608 t
->last_trigger
= DUAL_TIMESTAMP_NULL
;
610 /* Reenable all timers that depend on unit activation time */
611 LIST_FOREACH(value
, v
, t
->values
)
612 if (v
->base
== TIMER_ACTIVE
)
618 if (stat(t
->stamp_path
, &st
) >= 0) {
621 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
622 * something is wrong with the system clock. */
624 ft
= timespec_load(&st
.st_mtim
);
625 if (ft
< now(CLOCK_REALTIME
))
626 t
->last_trigger
.realtime
= ft
;
628 char z
[FORMAT_TIMESTAMP_MAX
];
630 log_unit_warning(u
, "Not using persistent file timestamp %s as it is in the future.",
631 format_timestamp(z
, sizeof(z
), ft
));
634 } else if (errno
== ENOENT
)
635 /* The timer has never run before,
636 * make sure a stamp file exists.
638 (void) touch_file(t
->stamp_path
, true, USEC_INFINITY
, UID_INVALID
, GID_INVALID
, MODE_INVALID
);
641 t
->result
= TIMER_SUCCESS
;
642 timer_enter_waiting(t
, true, false);
646 static int timer_stop(Unit
*u
) {
650 assert(IN_SET(t
->state
, TIMER_WAITING
, TIMER_RUNNING
, TIMER_ELAPSED
));
652 timer_enter_dead(t
, TIMER_SUCCESS
);
656 static int timer_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
663 (void) serialize_item(f
, "state", timer_state_to_string(t
->state
));
664 (void) serialize_item(f
, "result", timer_result_to_string(t
->result
));
666 if (t
->last_trigger
.realtime
> 0)
667 (void) serialize_usec(f
, "last-trigger-realtime", t
->last_trigger
.realtime
);
669 if (t
->last_trigger
.monotonic
> 0)
670 (void) serialize_usec(f
, "last-trigger-monotonic", t
->last_trigger
.monotonic
);
675 static int timer_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
683 if (streq(key
, "state")) {
686 state
= timer_state_from_string(value
);
688 log_unit_debug(u
, "Failed to parse state value: %s", value
);
690 t
->deserialized_state
= state
;
692 } else if (streq(key
, "result")) {
695 f
= timer_result_from_string(value
);
697 log_unit_debug(u
, "Failed to parse result value: %s", value
);
698 else if (f
!= TIMER_SUCCESS
)
701 } else if (streq(key
, "last-trigger-realtime"))
702 (void) deserialize_usec(value
, &t
->last_trigger
.realtime
);
703 else if (streq(key
, "last-trigger-monotonic"))
704 (void) deserialize_usec(value
, &t
->last_trigger
.monotonic
);
706 log_unit_debug(u
, "Unknown serialization key: %s", key
);
711 _pure_
static UnitActiveState
timer_active_state(Unit
*u
) {
714 return state_translation_table
[TIMER(u
)->state
];
717 _pure_
static const char *timer_sub_state_to_string(Unit
*u
) {
720 return timer_state_to_string(TIMER(u
)->state
);
723 static int timer_dispatch(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
724 Timer
*t
= TIMER(userdata
);
728 if (t
->state
!= TIMER_WAITING
)
731 log_unit_debug(UNIT(t
), "Timer elapsed.");
732 timer_enter_running(t
);
736 static void timer_trigger_notify(Unit
*u
, Unit
*other
) {
743 if (other
->load_state
!= UNIT_LOADED
)
746 /* Reenable all timers that depend on unit state */
747 LIST_FOREACH(value
, v
, t
->values
)
748 if (IN_SET(v
->base
, TIMER_UNIT_ACTIVE
, TIMER_UNIT_INACTIVE
))
756 /* Recalculate sleep time */
757 timer_enter_waiting(t
, false, false);
762 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other
))) {
763 log_unit_debug(UNIT(t
), "Got notified about unit deactivation.");
764 timer_enter_waiting(t
, false, false);
773 assert_not_reached("Unknown timer state");
777 static void timer_reset_failed(Unit
*u
) {
782 if (t
->state
== TIMER_FAILED
)
783 timer_set_state(t
, TIMER_DEAD
);
785 t
->result
= TIMER_SUCCESS
;
788 static void timer_time_change(Unit
*u
) {
794 if (t
->state
!= TIMER_WAITING
)
797 /* If we appear to have triggered in the future, the system clock must
798 * have been set backwards. So let's rewind our own clock and allow
799 * the future trigger(s) to happen again :). Exactly the same as when
800 * you start a timer unit with Persistent=yes. */
801 ts
= now(CLOCK_REALTIME
);
802 if (t
->last_trigger
.realtime
> ts
)
803 t
->last_trigger
.realtime
= ts
;
805 log_unit_debug(u
, "Time change, recalculating next elapse.");
806 timer_enter_waiting(t
, false, true);
809 static void timer_timezone_change(Unit
*u
) {
814 if (t
->state
!= TIMER_WAITING
)
817 log_unit_debug(u
, "Timezone change, recalculating next elapse.");
818 timer_enter_waiting(t
, false, false);
821 static const char* const timer_base_table
[_TIMER_BASE_MAX
] = {
822 [TIMER_ACTIVE
] = "OnActiveSec",
823 [TIMER_BOOT
] = "OnBootSec",
824 [TIMER_STARTUP
] = "OnStartupSec",
825 [TIMER_UNIT_ACTIVE
] = "OnUnitActiveSec",
826 [TIMER_UNIT_INACTIVE
] = "OnUnitInactiveSec",
827 [TIMER_CALENDAR
] = "OnCalendar"
830 DEFINE_STRING_TABLE_LOOKUP(timer_base
, TimerBase
);
832 static const char* const timer_result_table
[_TIMER_RESULT_MAX
] = {
833 [TIMER_SUCCESS
] = "success",
834 [TIMER_FAILURE_RESOURCES
] = "resources",
835 [TIMER_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
838 DEFINE_STRING_TABLE_LOOKUP(timer_result
, TimerResult
);
840 const UnitVTable timer_vtable
= {
841 .object_size
= sizeof(Timer
),
847 .private_section
= "Timer",
853 .coldplug
= timer_coldplug
,
857 .start
= timer_start
,
860 .serialize
= timer_serialize
,
861 .deserialize_item
= timer_deserialize_item
,
863 .active_state
= timer_active_state
,
864 .sub_state_to_string
= timer_sub_state_to_string
,
866 .trigger_notify
= timer_trigger_notify
,
868 .reset_failed
= timer_reset_failed
,
869 .time_change
= timer_time_change
,
870 .timezone_change
= timer_timezone_change
,
872 .bus_vtable
= bus_timer_vtable
,
873 .bus_set_property
= bus_timer_set_property
,
875 .can_transient
= true,