]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/timer.c
Merge pull request #14523 from keszybz/refactorings
[thirdparty/systemd.git] / src / core / timer.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09 2
ca78ad1d
ZJS
3#include <sys/stat.h>
4#include <sys/types.h>
5#include <unistd.h>
6
d46de8a1
LP
7#include <errno.h>
8
b5efdb8a 9#include "alloc-util.h"
07630cea
LP
10#include "bus-error.h"
11#include "bus-util.h"
871d7de4 12#include "dbus-timer.h"
6fcbec6f 13#include "dbus-unit.h"
f4f15635 14#include "fs-util.h"
6bedfcbb 15#include "parse-util.h"
744c7693 16#include "random-util.h"
d68c645b 17#include "serialize.h"
a40eb732 18#include "special.h"
8b43440b 19#include "string-table.h"
07630cea 20#include "string-util.h"
b1d4f8e1 21#include "timer.h"
07630cea
LP
22#include "unit-name.h"
23#include "unit.h"
b1d4f8e1 24#include "user-util.h"
c1d9ba99 25#include "virt.h"
871d7de4
LP
26
27static 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,
fdf20a31 32 [TIMER_FAILED] = UNIT_FAILED
871d7de4
LP
33};
34
718db961
LP
35static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
36
871d7de4
LP
37static void timer_init(Unit *u) {
38 Timer *t = TIMER(u);
39
40 assert(u);
ac155bb8 41 assert(u->load_state == UNIT_STUB);
871d7de4 42
3a43da28
KS
43 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
44 t->next_elapse_realtime = USEC_INFINITY;
bd8f585b 45 t->accuracy_usec = u->manager->default_timer_accuracy_usec;
3e0c30ac 46 t->remain_after_elapse = true;
871d7de4 47}
5cb5a6ff 48
74051b9b 49void timer_free_values(Timer *t) {
871d7de4
LP
50 TimerValue *v;
51
52 assert(t);
53
54 while ((v = t->values)) {
71fda00f 55 LIST_REMOVE(value, t->values, v);
3e044c49 56 calendar_spec_free(v->calendar_spec);
871d7de4
LP
57 free(v);
58 }
74051b9b
LP
59}
60
61static void timer_done(Unit *u) {
62 Timer *t = TIMER(u);
63
64 assert(t);
65
66 timer_free_values(t);
871d7de4 67
718db961
LP
68 t->monotonic_event_source = sd_event_source_unref(t->monotonic_event_source);
69 t->realtime_event_source = sd_event_source_unref(t->realtime_event_source);
06642d17
LP
70
71 free(t->stamp_path);
871d7de4
LP
72}
73
74static int timer_verify(Timer *t) {
75 assert(t);
75193d41 76 assert(UNIT(t)->load_state == UNIT_LOADED);
871d7de4 77
efebb613 78 if (!t->values && !t->on_clock_change && !t->on_timezone_change) {
f2341e0a 79 log_unit_error(UNIT(t), "Timer unit lacks value setting. Refusing.");
6f40aa45 80 return -ENOEXEC;
871d7de4
LP
81 }
82
83 return 0;
84}
85
6c155fe3
LP
86static int timer_add_default_dependencies(Timer *t) {
87 int r;
19f8d037 88 TimerValue *v;
6c155fe3
LP
89
90 assert(t);
91
4c9ea260
LP
92 if (!UNIT(t)->default_dependencies)
93 return 0;
94
35d8c19a 95 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721
LP
96 if (r < 0)
97 return r;
2a77d31d 98
463d0d15 99 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
5a724170 100 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
36697dc0 101 if (r < 0)
6c155fe3 102 return r;
19f8d037
TGR
103
104 LIST_FOREACH(value, v, t->values) {
105 if (v->base == TIMER_CALENDAR) {
35d8c19a 106 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, SPECIAL_TIME_SYNC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
19f8d037
TGR
107 if (r < 0)
108 return r;
109 break;
110 }
111 }
2a77d31d 112 }
6c155fe3 113
5a724170 114 return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
eef85c4a
LP
115}
116
117static int timer_add_trigger_dependencies(Timer *t) {
118 Unit *x;
119 int r;
120
121 assert(t);
122
123 if (!hashmap_isempty(UNIT(t)->dependencies[UNIT_TRIGGERS]))
124 return 0;
125
126 r = unit_load_related_unit(UNIT(t), ".service", &x);
127 if (r < 0)
128 return r;
129
130 return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
6c155fe3
LP
131}
132
06642d17
LP
133static int timer_setup_persistent(Timer *t) {
134 int r;
135
136 assert(t);
137
138 if (!t->persistent)
139 return 0;
140
463d0d15 141 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
06642d17 142
eef85c4a 143 r = unit_require_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE);
06642d17
LP
144 if (r < 0)
145 return r;
146
b910cc72 147 t->stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
148 } else {
149 const char *e;
150
151 e = getenv("XDG_DATA_HOME");
152 if (e)
605405c6 153 t->stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
154 else {
155
156 _cleanup_free_ char *h = NULL;
157
158 r = get_home_dir(&h);
23bbb0de 159 if (r < 0)
f2341e0a 160 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
06642d17 161
605405c6 162 t->stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
163 }
164 }
165
166 if (!t->stamp_path)
167 return log_oom();
168
169 return 0;
170}
171
871d7de4
LP
172static int timer_load(Unit *u) {
173 Timer *t = TIMER(u);
174 int r;
175
176 assert(u);
ac155bb8 177 assert(u->load_state == UNIT_STUB);
871d7de4 178
c3620770 179 r = unit_load_fragment_and_dropin(u, true);
36697dc0 180 if (r < 0)
871d7de4
LP
181 return r;
182
75193d41
ZJS
183 if (u->load_state != UNIT_LOADED)
184 return 0;
871d7de4 185
75193d41
ZJS
186 /* This is a new unit? Then let's add in some extras */
187 r = timer_add_trigger_dependencies(t);
188 if (r < 0)
189 return r;
57020a3a 190
75193d41
ZJS
191 r = timer_setup_persistent(t);
192 if (r < 0)
193 return r;
06642d17 194
75193d41
ZJS
195 r = timer_add_default_dependencies(t);
196 if (r < 0)
197 return r;
871d7de4
LP
198
199 return timer_verify(t);
200}
201
202static void timer_dump(Unit *u, FILE *f, const char *prefix) {
9f5eb56a 203 char buf[FORMAT_TIMESPAN_MAX];
871d7de4 204 Timer *t = TIMER(u);
3ecaa09b 205 Unit *trigger;
871d7de4 206 TimerValue *v;
034c6ed7 207
3ecaa09b
LP
208 trigger = UNIT_TRIGGER(u);
209
871d7de4
LP
210 fprintf(f,
211 "%sTimer State: %s\n"
067d72c9 212 "%sResult: %s\n"
9f5eb56a 213 "%sUnit: %s\n"
dedabea4
LP
214 "%sPersistent: %s\n"
215 "%sWakeSystem: %s\n"
3e0c30ac 216 "%sAccuracy: %s\n"
efebb613
LP
217 "%sRemainAfterElapse: %s\n"
218 "%sOnClockChange: %s\n"
0810e396 219 "%sOnTimeZoneChange: %s\n",
871d7de4 220 prefix, timer_state_to_string(t->state),
067d72c9 221 prefix, timer_result_to_string(t->result),
9f5eb56a 222 prefix, trigger ? trigger->id : "n/a",
dedabea4
LP
223 prefix, yes_no(t->persistent),
224 prefix, yes_no(t->wake_system),
3e0c30ac 225 prefix, format_timespan(buf, sizeof(buf), t->accuracy_usec, 1),
efebb613
LP
226 prefix, yes_no(t->remain_after_elapse),
227 prefix, yes_no(t->on_clock_change),
228 prefix, yes_no(t->on_timezone_change));
871d7de4 229
36697dc0
LP
230 LIST_FOREACH(value, v, t->values) {
231
232 if (v->base == TIMER_CALENDAR) {
233 _cleanup_free_ char *p = NULL;
234
25cb94d4 235 (void) calendar_spec_to_string(v->calendar_spec, &p);
36697dc0
LP
236
237 fprintf(f,
238 "%s%s: %s\n",
239 prefix,
240 timer_base_to_string(v->base),
241 strna(p));
242 } else {
243 char timespan1[FORMAT_TIMESPAN_MAX];
244
245 fprintf(f,
246 "%s%s: %s\n",
247 prefix,
248 timer_base_to_string(v->base),
b1d6dcf5 249 format_timespan(timespan1, sizeof(timespan1), v->value, 0));
36697dc0
LP
250 }
251 }
871d7de4
LP
252}
253
254static void timer_set_state(Timer *t, TimerState state) {
255 TimerState old_state;
034c6ed7 256 assert(t);
871d7de4 257
6fcbec6f
LP
258 if (t->state != state)
259 bus_unit_send_pending_change_signal(UNIT(t), false);
260
871d7de4
LP
261 old_state = t->state;
262 t->state = state;
263
36697dc0 264 if (state != TIMER_WAITING) {
718db961
LP
265 t->monotonic_event_source = sd_event_source_unref(t->monotonic_event_source);
266 t->realtime_event_source = sd_event_source_unref(t->realtime_event_source);
6e2c9ce1
ZJS
267 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
268 t->next_elapse_realtime = USEC_INFINITY;
36697dc0 269 }
871d7de4
LP
270
271 if (state != old_state)
f2341e0a 272 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
871d7de4 273
2ad2e41a 274 unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], 0);
871d7de4
LP
275}
276
aa1f95d2 277static void timer_enter_waiting(Timer *t, bool time_change);
871d7de4 278
be847e82 279static int timer_coldplug(Unit *u) {
871d7de4
LP
280 Timer *t = TIMER(u);
281
282 assert(t);
283 assert(t->state == TIMER_DEAD);
284
3e0c30ac
LP
285 if (t->deserialized_state == t->state)
286 return 0;
871d7de4 287
3e0c30ac 288 if (t->deserialized_state == TIMER_WAITING)
aa1f95d2 289 timer_enter_waiting(t, false);
3e0c30ac
LP
290 else
291 timer_set_state(t, t->deserialized_state);
871d7de4
LP
292
293 return 0;
294}
295
067d72c9 296static void timer_enter_dead(Timer *t, TimerResult f) {
871d7de4
LP
297 assert(t);
298
a0fef983 299 if (t->result == TIMER_SUCCESS)
067d72c9 300 t->result = f;
871d7de4 301
aac99f30 302 unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
067d72c9 303 timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
871d7de4
LP
304}
305
3e0c30ac
LP
306static void timer_enter_elapsed(Timer *t, bool leave_around) {
307 assert(t);
308
309 /* If a unit is marked with RemainAfterElapse=yes we leave it
310 * around even after it elapsed once, so that starting it
311 * later again does not necessarily mean immediate
312 * retriggering. We unconditionally leave units with
313 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
314 * since they might be restarted automatically at any time
315 * later on. */
316
317 if (t->remain_after_elapse || leave_around)
318 timer_set_state(t, TIMER_ELAPSED);
319 else
320 timer_enter_dead(t, TIMER_SUCCESS);
321}
322
744c7693
LP
323static void add_random(Timer *t, usec_t *v) {
324 char s[FORMAT_TIMESPAN_MAX];
325 usec_t add;
326
327 assert(t);
3f51aec8 328 assert(v);
744c7693
LP
329
330 if (t->random_usec == 0)
331 return;
332 if (*v == USEC_INFINITY)
333 return;
334
335 add = random_u64() % t->random_usec;
336
337 if (*v + add < *v) /* overflow */
338 *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
339 else
340 *v += add;
341
382852fd 342 log_unit_debug(UNIT(t), "Adding %s random time.", format_timespan(s, sizeof(s), add, 0));
744c7693
LP
343}
344
aa1f95d2 345static void timer_enter_waiting(Timer *t, bool time_change) {
36697dc0 346 bool found_monotonic = false, found_realtime = false;
3e0c30ac 347 bool leave_around = false;
c54be90b 348 triple_timestamp ts;
dedabea4 349 TimerValue *v;
e903182e 350 Unit *trigger;
871d7de4
LP
351 int r;
352
e903182e
LP
353 assert(t);
354
355 trigger = UNIT_TRIGGER(UNIT(t));
356 if (!trigger) {
357 log_unit_error(UNIT(t), "Unit to trigger vanished.");
358 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
359 return;
360 }
361
c54be90b 362 triple_timestamp_get(&ts);
dedabea4 363 t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
871d7de4
LP
364
365 LIST_FOREACH(value, v, t->values) {
871d7de4
LP
366 if (v->disabled)
367 continue;
368
36697dc0 369 if (v->base == TIMER_CALENDAR) {
06642d17
LP
370 usec_t b;
371
372 /* If we know the last time this was
373 * triggered, schedule the job based relative
9ea9faff
AJ
374 * to that. If we don't, just start from
375 * the activation time. */
376
377 if (t->last_trigger.realtime > 0)
378 b = t->last_trigger.realtime;
379 else {
380 if (state_translation_table[t->state] == UNIT_ACTIVE)
381 b = UNIT(t)->inactive_exit_timestamp.realtime;
382 else
383 b = ts.realtime;
384 }
06642d17
LP
385
386 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
36697dc0
LP
387 if (r < 0)
388 continue;
389
a87c1d3a
TY
390 /* To make the delay due to RandomizedDelaySec= work even at boot,
391 * if the scheduled time has already passed, set the time when systemd
392 * first started as the scheduled time.
393 * Also, we don't have to check t->persistent since the logic implicitly express true. */
394 if (v->next_elapse < UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].realtime)
395 v->next_elapse = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].realtime;
396
36697dc0
LP
397 if (!found_realtime)
398 t->next_elapse_realtime = v->next_elapse;
10717a1a 399 else
36697dc0 400 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
871d7de4 401
36697dc0 402 found_realtime = true;
871d7de4 403
60933bb8
AJ
404 } else {
405 usec_t base;
c54be90b 406
36697dc0 407 switch (v->base) {
871d7de4 408
36697dc0
LP
409 case TIMER_ACTIVE:
410 if (state_translation_table[t->state] == UNIT_ACTIVE)
411 base = UNIT(t)->inactive_exit_timestamp.monotonic;
412 else
c54be90b 413 base = ts.monotonic;
36697dc0 414 break;
871d7de4 415
36697dc0 416 case TIMER_BOOT:
c1d9ba99
MS
417 if (detect_container() <= 0) {
418 /* CLOCK_MONOTONIC equals the uptime on Linux */
419 base = 0;
420 break;
421 }
422 /* In a container we don't want to include the time the host
423 * was already up when the container started, so count from
ec251fe7 424 * our own startup. */
4831981d 425 _fallthrough_;
36697dc0 426 case TIMER_STARTUP:
9f9f0342 427 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
36697dc0 428 break;
871d7de4 429
36697dc0 430 case TIMER_UNIT_ACTIVE:
3e0c30ac 431 leave_around = true;
525b95f1 432 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 433 if (base <= 0)
36697dc0 434 continue;
36697dc0 435 break;
871d7de4 436
36697dc0 437 case TIMER_UNIT_INACTIVE:
3e0c30ac 438 leave_around = true;
525b95f1 439 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 440 if (base <= 0)
36697dc0 441 continue;
36697dc0 442 break;
871d7de4 443
36697dc0
LP
444 default:
445 assert_not_reached("Unknown timer base");
446 }
871d7de4 447
c54be90b 448 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
36697dc0 449
aa1f95d2
MK
450 if (dual_timestamp_is_set(&t->last_trigger) &&
451 !time_change &&
c54be90b
LP
452 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
453 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
e41e1943 454 /* This is a one time trigger, disable it now */
36697dc0
LP
455 v->disabled = true;
456 continue;
457 }
458
459 if (!found_monotonic)
dedabea4 460 t->next_elapse_monotonic_or_boottime = v->next_elapse;
36697dc0 461 else
dedabea4 462 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
36697dc0
LP
463
464 found_monotonic = true;
465 }
871d7de4
LP
466 }
467
efebb613 468 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
f2341e0a 469 log_unit_debug(UNIT(t), "Timer is elapsed.");
3e0c30ac 470 timer_enter_elapsed(t, leave_around);
871d7de4
LP
471 return;
472 }
473
36697dc0
LP
474 if (found_monotonic) {
475 char buf[FORMAT_TIMESPAN_MAX];
3e0c30ac 476 usec_t left;
dedabea4 477
744c7693
LP
478 add_random(t, &t->next_elapse_monotonic_or_boottime);
479
c54be90b 480 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
3e0c30ac 481 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", format_timespan(buf, sizeof(buf), left, 0));
871d7de4 482
718db961 483 if (t->monotonic_event_source) {
dedabea4 484 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
718db961
LP
485 if (r < 0)
486 goto fail;
487
488 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
489 if (r < 0)
490 goto fail;
491 } else {
492
6a0f1f6d
LP
493 r = sd_event_add_time(
494 UNIT(t)->manager->event,
495 &t->monotonic_event_source,
dedabea4
LP
496 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
497 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
6a0f1f6d 498 timer_dispatch, t);
cbf60d0a
LP
499 if (r < 0)
500 goto fail;
718db961 501
cbf60d0a
LP
502 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
503 }
7dfbe2e3 504
718db961 505 } else if (t->monotonic_event_source) {
718db961 506
06642d17 507 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
718db961
LP
508 if (r < 0)
509 goto fail;
510 }
36697dc0
LP
511
512 if (found_realtime) {
513 char buf[FORMAT_TIMESTAMP_MAX];
744c7693
LP
514
515 add_random(t, &t->next_elapse_realtime);
516
f2341e0a 517 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", format_timestamp(buf, sizeof(buf), t->next_elapse_realtime));
36697dc0 518
718db961
LP
519 if (t->realtime_event_source) {
520 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
521 if (r < 0)
522 goto fail;
523
524 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
cbf60d0a
LP
525 if (r < 0)
526 goto fail;
527 } else {
6a0f1f6d
LP
528 r = sd_event_add_time(
529 UNIT(t)->manager->event,
530 &t->realtime_event_source,
dedabea4 531 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
6a0f1f6d
LP
532 t->next_elapse_realtime, t->accuracy_usec,
533 timer_dispatch, t);
cbf60d0a
LP
534 if (r < 0)
535 goto fail;
718db961 536
cbf60d0a
LP
537 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
538 }
7dfbe2e3 539
718db961 540 } else if (t->realtime_event_source) {
718db961 541
06642d17 542 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
718db961
LP
543 if (r < 0)
544 goto fail;
545 }
871d7de4
LP
546
547 timer_set_state(t, TIMER_WAITING);
548 return;
549
550fail:
f2341e0a 551 log_unit_warning_errno(UNIT(t), r, "Failed to enter waiting state: %m");
067d72c9 552 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
553}
554
555static void timer_enter_running(Timer *t) {
4afd3348 556 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e903182e 557 Unit *trigger;
871d7de4 558 int r;
398ef8ba 559
871d7de4
LP
560 assert(t);
561
ba3e67a7 562 /* Don't start job if we are supposed to go down */
31afa0a4 563 if (unit_stop_pending(UNIT(t)))
ba3e67a7
LP
564 return;
565
e903182e
LP
566 trigger = UNIT_TRIGGER(UNIT(t));
567 if (!trigger) {
568 log_unit_error(UNIT(t), "Unit to trigger vanished.");
569 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
570 return;
571 }
572
50cbaba4 573 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, NULL);
36697dc0 574 if (r < 0)
871d7de4
LP
575 goto fail;
576
06642d17
LP
577 dual_timestamp_get(&t->last_trigger);
578
472fc28f 579 if (t->stamp_path)
ee735086 580 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
e41e1943 581
871d7de4
LP
582 timer_set_state(t, TIMER_RUNNING);
583 return;
584
585fail:
f2341e0a 586 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
067d72c9 587 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
588}
589
590static int timer_start(Unit *u) {
591 Timer *t = TIMER(u);
779042e7 592 TimerValue *v;
07299350 593 int r;
871d7de4
LP
594
595 assert(t);
3742095b 596 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
01f78473 597
a4191c9f
LP
598 r = unit_test_trigger_loaded(u);
599 if (r < 0)
600 return r;
871d7de4 601
97a3f4ee 602 r = unit_test_start_limit(u);
07299350
LP
603 if (r < 0) {
604 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
605 return r;
606 }
607
4b58153d
LP
608 r = unit_acquire_invocation_id(u);
609 if (r < 0)
610 return r;
611
06642d17
LP
612 t->last_trigger = DUAL_TIMESTAMP_NULL;
613
779042e7
MC
614 /* Reenable all timers that depend on unit activation time */
615 LIST_FOREACH(value, v, t->values)
616 if (v->base == TIMER_ACTIVE)
617 v->disabled = false;
618
06642d17
LP
619 if (t->stamp_path) {
620 struct stat st;
621
77542a79
LP
622 if (stat(t->stamp_path, &st) >= 0) {
623 usec_t ft;
624
625 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
626 * something is wrong with the system clock. */
627
628 ft = timespec_load(&st.st_mtim);
629 if (ft < now(CLOCK_REALTIME))
630 t->last_trigger.realtime = ft;
631 else {
632 char z[FORMAT_TIMESTAMP_MAX];
633
634 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
635 format_timestamp(z, sizeof(z), ft));
636 }
637
638 } else if (errno == ENOENT)
472fc28f
TB
639 /* The timer has never run before,
640 * make sure a stamp file exists.
641 */
4b58153d 642 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
06642d17
LP
643 }
644
067d72c9 645 t->result = TIMER_SUCCESS;
aa1f95d2 646 timer_enter_waiting(t, false);
82a2b6bb 647 return 1;
871d7de4
LP
648}
649
650static int timer_stop(Unit *u) {
651 Timer *t = TIMER(u);
652
653 assert(t);
3742095b 654 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
871d7de4 655
067d72c9 656 timer_enter_dead(t, TIMER_SUCCESS);
82a2b6bb 657 return 1;
871d7de4
LP
658}
659
660static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
661 Timer *t = TIMER(u);
662
663 assert(u);
664 assert(f);
665 assert(fds);
666
d68c645b
LP
667 (void) serialize_item(f, "state", timer_state_to_string(t->state));
668 (void) serialize_item(f, "result", timer_result_to_string(t->result));
871d7de4 669
06642d17 670 if (t->last_trigger.realtime > 0)
d68c645b 671 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
06642d17
LP
672
673 if (t->last_trigger.monotonic > 0)
d68c645b 674 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
06642d17 675
871d7de4
LP
676 return 0;
677}
678
679static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
680 Timer *t = TIMER(u);
681
682 assert(u);
683 assert(key);
684 assert(value);
685 assert(fds);
686
687 if (streq(key, "state")) {
688 TimerState state;
689
36697dc0
LP
690 state = timer_state_from_string(value);
691 if (state < 0)
f2341e0a 692 log_unit_debug(u, "Failed to parse state value: %s", value);
871d7de4
LP
693 else
694 t->deserialized_state = state;
d68c645b 695
067d72c9
LP
696 } else if (streq(key, "result")) {
697 TimerResult f;
698
699 f = timer_result_from_string(value);
700 if (f < 0)
f2341e0a 701 log_unit_debug(u, "Failed to parse result value: %s", value);
067d72c9
LP
702 else if (f != TIMER_SUCCESS)
703 t->result = f;
06642d17 704
d68c645b
LP
705 } else if (streq(key, "last-trigger-realtime"))
706 (void) deserialize_usec(value, &t->last_trigger.realtime);
707 else if (streq(key, "last-trigger-monotonic"))
708 (void) deserialize_usec(value, &t->last_trigger.monotonic);
709 else
f2341e0a 710 log_unit_debug(u, "Unknown serialization key: %s", key);
871d7de4
LP
711
712 return 0;
034c6ed7
LP
713}
714
44a6b1b6 715_pure_ static UnitActiveState timer_active_state(Unit *u) {
871d7de4
LP
716 assert(u);
717
718 return state_translation_table[TIMER(u)->state];
719}
720
44a6b1b6 721_pure_ static const char *timer_sub_state_to_string(Unit *u) {
871d7de4
LP
722 assert(u);
723
724 return timer_state_to_string(TIMER(u)->state);
725}
726
718db961
LP
727static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
728 Timer *t = TIMER(userdata);
871d7de4
LP
729
730 assert(t);
5cb5a6ff 731
871d7de4 732 if (t->state != TIMER_WAITING)
718db961 733 return 0;
5cb5a6ff 734
f2341e0a 735 log_unit_debug(UNIT(t), "Timer elapsed.");
871d7de4 736 timer_enter_running(t);
718db961 737 return 0;
5cb5a6ff
LP
738}
739
3ecaa09b
LP
740static void timer_trigger_notify(Unit *u, Unit *other) {
741 Timer *t = TIMER(u);
742 TimerValue *v;
871d7de4 743
3ecaa09b
LP
744 assert(u);
745 assert(other);
871d7de4 746
3ecaa09b
LP
747 if (other->load_state != UNIT_LOADED)
748 return;
871d7de4 749
3ecaa09b
LP
750 /* Reenable all timers that depend on unit state */
751 LIST_FOREACH(value, v, t->values)
3742095b 752 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
3ecaa09b 753 v->disabled = false;
01f78473 754
3ecaa09b 755 switch (t->state) {
871d7de4 756
3ecaa09b
LP
757 case TIMER_WAITING:
758 case TIMER_ELAPSED:
871d7de4 759
3ecaa09b 760 /* Recalculate sleep time */
aa1f95d2 761 timer_enter_waiting(t, false);
3ecaa09b 762 break;
871d7de4 763
3ecaa09b 764 case TIMER_RUNNING:
871d7de4 765
3ecaa09b 766 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
f2341e0a 767 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
aa1f95d2 768 timer_enter_waiting(t, false);
3ecaa09b
LP
769 }
770 break;
871d7de4 771
3ecaa09b
LP
772 case TIMER_DEAD:
773 case TIMER_FAILED:
774 break;
871d7de4 775
3ecaa09b
LP
776 default:
777 assert_not_reached("Unknown timer state");
871d7de4 778 }
871d7de4
LP
779}
780
fdf20a31 781static void timer_reset_failed(Unit *u) {
5632e374
LP
782 Timer *t = TIMER(u);
783
784 assert(t);
785
fdf20a31 786 if (t->state == TIMER_FAILED)
5632e374
LP
787 timer_set_state(t, TIMER_DEAD);
788
067d72c9 789 t->result = TIMER_SUCCESS;
5632e374
LP
790}
791
8742514c
LP
792static void timer_time_change(Unit *u) {
793 Timer *t = TIMER(u);
13f512d3 794 usec_t ts;
8742514c
LP
795
796 assert(u);
797
798 if (t->state != TIMER_WAITING)
799 return;
800
13f512d3
AJ
801 /* If we appear to have triggered in the future, the system clock must
802 * have been set backwards. So let's rewind our own clock and allow
803 * the future trigger(s) to happen again :). Exactly the same as when
804 * you start a timer unit with Persistent=yes. */
805 ts = now(CLOCK_REALTIME);
806 if (t->last_trigger.realtime > ts)
807 t->last_trigger.realtime = ts;
808
efebb613
LP
809 if (t->on_clock_change) {
810 log_unit_debug(u, "Time change, triggering activation.");
811 timer_enter_running(t);
812 } else {
813 log_unit_debug(u, "Time change, recalculating next elapse.");
814 timer_enter_waiting(t, true);
815 }
8742514c
LP
816}
817
bbf5fd8e
LP
818static void timer_timezone_change(Unit *u) {
819 Timer *t = TIMER(u);
820
821 assert(u);
822
823 if (t->state != TIMER_WAITING)
824 return;
825
efebb613
LP
826 if (t->on_timezone_change) {
827 log_unit_debug(u, "Timezone change, triggering activation.");
828 timer_enter_running(t);
829 } else {
830 log_unit_debug(u, "Timezone change, recalculating next elapse.");
831 timer_enter_waiting(t, false);
832 }
bbf5fd8e
LP
833}
834
89f6fe7b
LP
835static int timer_clean(Unit *u, ExecCleanMask mask) {
836 Timer *t = TIMER(u);
837 int r;
838
839 assert(t);
840 assert(mask != 0);
841
842 if (t->state != TIMER_DEAD)
843 return -EBUSY;
844
845 if (!IN_SET(mask, EXEC_CLEAN_STATE))
846 return -EUNATCH;
847
848 r = timer_setup_persistent(t);
849 if (r < 0)
850 return r;
851
852 if (!t->stamp_path)
853 return -EUNATCH;
854
855 if (unlink(t->stamp_path) && errno != ENOENT)
856 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
857
858 return 0;
859}
860
861static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
862 Timer *t = TIMER(u);
863
864 assert(t);
865
866 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
867 return 0;
868}
869
871d7de4 870static const char* const timer_base_table[_TIMER_BASE_MAX] = {
03fae018
LP
871 [TIMER_ACTIVE] = "OnActiveSec",
872 [TIMER_BOOT] = "OnBootSec",
873 [TIMER_STARTUP] = "OnStartupSec",
874 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
36697dc0
LP
875 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
876 [TIMER_CALENDAR] = "OnCalendar"
871d7de4
LP
877};
878
879DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
880
067d72c9
LP
881static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
882 [TIMER_SUCCESS] = "success",
07299350
LP
883 [TIMER_FAILURE_RESOURCES] = "resources",
884 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
067d72c9
LP
885};
886
887DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
888
87f0e418 889const UnitVTable timer_vtable = {
7d17cfbc 890 .object_size = sizeof(Timer),
718db961 891
f975e971
LP
892 .sections =
893 "Unit\0"
894 "Timer\0"
895 "Install\0",
d8a812d1 896 .private_section = "Timer",
5cb5a6ff 897
871d7de4 898 .init = timer_init,
034c6ed7 899 .done = timer_done,
871d7de4
LP
900 .load = timer_load,
901
902 .coldplug = timer_coldplug,
903
904 .dump = timer_dump,
905
906 .start = timer_start,
907 .stop = timer_stop,
908
89f6fe7b
LP
909 .clean = timer_clean,
910 .can_clean = timer_can_clean,
911
871d7de4
LP
912 .serialize = timer_serialize,
913 .deserialize_item = timer_deserialize_item,
914
915 .active_state = timer_active_state,
916 .sub_state_to_string = timer_sub_state_to_string,
917
3ecaa09b
LP
918 .trigger_notify = timer_trigger_notify,
919
fdf20a31 920 .reset_failed = timer_reset_failed,
8742514c 921 .time_change = timer_time_change,
bbf5fd8e 922 .timezone_change = timer_timezone_change,
5632e374 923
718db961 924 .bus_vtable = bus_timer_vtable,
d8a812d1
WC
925 .bus_set_property = bus_timer_set_property,
926
927 .can_transient = true,
5cb5a6ff 928};