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