• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 18513518178

14 Oct 2025 04:56PM UTC coverage: 72.072% (-0.2%) from 72.262%
18513518178

push

github

bluca
test: enable TEST-06-SELINUX in openSUSE

openSUSE switched to SELinux by default for quite some time now, so this test is
also successful.

302681 of 419971 relevant lines covered (72.07%)

1141924.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

68.93
/src/core/timer.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <sys/stat.h>
5
#include <unistd.h>
6

7
#include "sd-bus.h"
8

9
#include "alloc-util.h"
10
#include "bus-error.h"
11
#include "calendarspec.h"
12
#include "dbus-timer.h"
13
#include "dbus-unit.h"
14
#include "fs-util.h"
15
#include "manager.h"
16
#include "random-util.h"
17
#include "serialize.h"
18
#include "siphash24.h"
19
#include "special.h"
20
#include "string-table.h"
21
#include "string-util.h"
22
#include "strv.h"
23
#include "timer.h"
24
#include "unit.h"
25
#include "user-util.h"
26
#include "virt.h"
27

28
static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
29
        [TIMER_DEAD]    = UNIT_INACTIVE,
30
        [TIMER_WAITING] = UNIT_ACTIVE,
31
        [TIMER_RUNNING] = UNIT_ACTIVE,
32
        [TIMER_ELAPSED] = UNIT_ACTIVE,
33
        [TIMER_FAILED]  = UNIT_FAILED,
34
};
35

36
static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
37

38
static void timer_init(Unit *u) {
493✔
39
        Timer *t = ASSERT_PTR(TIMER(u));
493✔
40

41
        assert(u->load_state == UNIT_STUB);
493✔
42

43
        t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
493✔
44
        t->next_elapse_realtime = USEC_INFINITY;
493✔
45
        t->accuracy_usec = u->manager->defaults.timer_accuracy_usec;
493✔
46
        t->remain_after_elapse = true;
493✔
47
}
493✔
48

49
void timer_free_values(Timer *t) {
493✔
50
        TimerValue *v;
493✔
51

52
        assert(t);
493✔
53

54
        while ((v = LIST_POP(value, t->values))) {
1,288✔
55
                calendar_spec_free(v->calendar_spec);
795✔
56
                free(v);
795✔
57
        }
58
}
493✔
59

60
static void timer_done(Unit *u) {
493✔
61
        Timer *t = ASSERT_PTR(TIMER(u));
493✔
62

63
        timer_free_values(t);
493✔
64

65
        t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
493✔
66
        t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
493✔
67

68
        t->stamp_path = mfree(t->stamp_path);
493✔
69
}
493✔
70

71
static int timer_verify(Timer *t) {
493✔
72
        assert(t);
493✔
73
        assert(UNIT(t)->load_state == UNIT_LOADED);
493✔
74

75
        if (!t->values && !t->on_clock_change && !t->on_timezone_change)
493✔
76
                return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
×
77

78
        return 0;
79
}
80

81
static int timer_add_default_dependencies(Timer *t) {
493✔
82
        int r;
493✔
83

84
        assert(t);
493✔
85

86
        if (!UNIT(t)->default_dependencies)
493✔
87
                return 0;
88

89
        r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
493✔
90
        if (r < 0)
493✔
91
                return r;
92

93
        if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
493✔
94
                r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
304✔
95
                if (r < 0)
304✔
96
                        return r;
97

98
                LIST_FOREACH(value, v, t->values) {
514✔
99
                        if (v->base != TIMER_CALENDAR)
409✔
100
                                continue;
210✔
101

102
                        FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
597✔
103
                                r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
398✔
104
                                if (r < 0)
398✔
105
                                        return r;
×
106
                        }
107

108
                        break;
199✔
109
                }
110
        }
111

112
        return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
493✔
113
}
114

115
static int timer_add_trigger_dependencies(Timer *t) {
493✔
116
        Unit *x;
493✔
117
        int r;
493✔
118

119
        assert(t);
493✔
120

121
        if (UNIT_TRIGGER(UNIT(t)))
493✔
122
                return 0;
493✔
123

124
        r = unit_load_related_unit(UNIT(t), ".service", &x);
493✔
125
        if (r < 0)
493✔
126
                return r;
127

128
        return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
493✔
129
}
130

131
static int timer_setup_persistent(Timer *t) {
493✔
132
        _cleanup_free_ char *stamp_path = NULL;
493✔
133
        int r;
493✔
134

135
        assert(t);
493✔
136

137
        if (!t->persistent)
493✔
138
                return 0;
139

140
        if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
194✔
141

142
                r = unit_add_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
194✔
143
                if (r < 0)
194✔
144
                        return r;
145

146
                stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
194✔
147
        } else {
148
                const char *e;
×
149

150
                e = getenv("XDG_DATA_HOME");
×
151
                if (e)
×
152
                        stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
×
153
                else {
154

155
                        _cleanup_free_ char *h = NULL;
×
156

157
                        r = get_home_dir(&h);
×
158
                        if (r < 0)
×
159
                                return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
×
160

161
                        stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
×
162
                }
163
        }
164

165
        if (!stamp_path)
194✔
166
                return log_oom();
×
167

168
        return free_and_replace(t->stamp_path, stamp_path);
194✔
169
}
170

171
static uint64_t timer_get_fixed_delay_hash(Timer *t) {
×
172
        static const uint8_t hash_key[] = {
×
173
                0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
174
                0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
175
        };
176

177
        struct siphash state;
×
178
        sd_id128_t machine_id;
×
179
        uid_t uid;
×
180
        int r;
×
181

182
        assert(t);
×
183

184
        uid = getuid();
×
185
        r = sd_id128_get_machine(&machine_id);
×
186
        if (r < 0) {
×
187
                log_unit_debug_errno(UNIT(t), r,
×
188
                                     "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
189
                machine_id = SD_ID128_NULL;
×
190
        }
191

192
        siphash24_init(&state, hash_key);
×
193
        siphash24_compress_typesafe(machine_id, &state);
×
194
        siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
×
195
        siphash24_compress_typesafe(uid, &state);
×
196
        siphash24_compress_string(UNIT(t)->id, &state);
×
197

198
        return siphash24_finalize(&state);
×
199
}
200

201
static int timer_load(Unit *u) {
493✔
202
        Timer *t = ASSERT_PTR(TIMER(u));
493✔
203
        int r;
493✔
204

205
        assert(u->load_state == UNIT_STUB);
493✔
206

207
        r = unit_load_fragment_and_dropin(u, true);
493✔
208
        if (r < 0)
493✔
209
                return r;
210

211
        if (u->load_state != UNIT_LOADED)
493✔
212
                return 0;
213

214
        /* This is a new unit? Then let's add in some extras */
215
        r = timer_add_trigger_dependencies(t);
493✔
216
        if (r < 0)
493✔
217
                return r;
218

219
        r = timer_setup_persistent(t);
493✔
220
        if (r < 0)
493✔
221
                return r;
222

223
        r = timer_add_default_dependencies(t);
493✔
224
        if (r < 0)
493✔
225
                return r;
226

227
        return timer_verify(t);
493✔
228
}
229

230
static void timer_dump(Unit *u, FILE *f, const char *prefix) {
×
231
        Timer *t = ASSERT_PTR(TIMER(u));
×
232
        Unit *trigger;
×
233

234
        assert(f);
×
235
        assert(prefix);
×
236

237
        trigger = UNIT_TRIGGER(u);
×
238

239
        fprintf(f,
×
240
                "%sTimer State: %s\n"
241
                "%sResult: %s\n"
242
                "%sUnit: %s\n"
243
                "%sPersistent: %s\n"
244
                "%sWakeSystem: %s\n"
245
                "%sAccuracy: %s\n"
246
                "%sRemainAfterElapse: %s\n"
247
                "%sFixedRandomDelay: %s\n"
248
                "%sOnClockChange: %s\n"
249
                "%sOnTimeZoneChange: %s\n"
250
                "%sDeferReactivation: %s\n",
251
                prefix, timer_state_to_string(t->state),
252
                prefix, timer_result_to_string(t->result),
253
                prefix, trigger ? trigger->id : "n/a",
254
                prefix, yes_no(t->persistent),
×
255
                prefix, yes_no(t->wake_system),
×
256
                prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
×
257
                prefix, yes_no(t->remain_after_elapse),
×
258
                prefix, yes_no(t->fixed_random_delay),
×
259
                prefix, yes_no(t->on_clock_change),
×
260
                prefix, yes_no(t->on_timezone_change),
×
261
                prefix, yes_no(t->defer_reactivation));
×
262

263
        LIST_FOREACH(value, v, t->values)
×
264
                if (v->base == TIMER_CALENDAR) {
×
265
                        _cleanup_free_ char *p = NULL;
×
266

267
                        (void) calendar_spec_to_string(v->calendar_spec, &p);
×
268

269
                        fprintf(f,
×
270
                                "%s%s: %s\n",
271
                                prefix,
272
                                timer_base_to_string(v->base),
273
                                strna(p));
274
                } else
275
                        fprintf(f,
×
276
                                "%s%s: %s\n",
277
                                prefix,
278
                                timer_base_to_string(v->base),
279
                                FORMAT_TIMESPAN(v->value, 0));
×
280
}
×
281

282
static void timer_set_state(Timer *t, TimerState state) {
675✔
283
        TimerState old_state;
675✔
284

285
        assert(t);
675✔
286

287
        if (t->state != state)
675✔
288
                bus_unit_send_pending_change_signal(UNIT(t), false);
649✔
289

290
        old_state = t->state;
675✔
291
        t->state = state;
675✔
292

293
        if (state != TIMER_WAITING) {
675✔
294
                t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
250✔
295
                t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
250✔
296
                t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
250✔
297
                t->next_elapse_realtime = USEC_INFINITY;
250✔
298
        }
299

300
        if (state != old_state)
675✔
301
                log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
649✔
302

303
        unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
675✔
304
}
675✔
305

306
static void timer_enter_waiting(Timer *t, bool time_change);
307

308
static int timer_coldplug(Unit *u) {
217✔
309
        Timer *t = ASSERT_PTR(TIMER(u));
217✔
310

311
        assert(t->state == TIMER_DEAD);
217✔
312

313
        if (t->deserialized_state == t->state)
217✔
314
                return 0;
315

316
        if (t->deserialized_state == TIMER_WAITING)
120✔
317
                timer_enter_waiting(t, false);
120✔
318
        else
319
                timer_set_state(t, t->deserialized_state);
×
320

321
        return 0;
322
}
323

324
static void timer_enter_dead(Timer *t, TimerResult f) {
243✔
325
        assert(t);
243✔
326

327
        if (t->result == TIMER_SUCCESS)
243✔
328
                t->result = f;
243✔
329

330
        unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
243✔
331
        timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
486✔
332
}
243✔
333

334
static void timer_enter_elapsed(Timer *t, bool leave_around) {
×
335
        assert(t);
×
336

337
        /* If a unit is marked with RemainAfterElapse=yes we leave it
338
         * around even after it elapsed once, so that starting it
339
         * later again does not necessarily mean immediate
340
         * retriggering. We unconditionally leave units with
341
         * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
342
         * since they might be restarted automatically at any time
343
         * later on. */
344

345
        if (t->remain_after_elapse || leave_around)
×
346
                timer_set_state(t, TIMER_ELAPSED);
×
347
        else
348
                timer_enter_dead(t, TIMER_SUCCESS);
×
349
}
×
350

351
static void add_random_delay(Timer *t, usec_t *v) {
425✔
352
        usec_t add;
425✔
353

354
        assert(t);
425✔
355
        assert(v);
425✔
356

357
        if (t->random_delay_usec == 0)
425✔
358
                return;
359
        if (*v == USEC_INFINITY)
64✔
360
                return;
361

362
        add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_delay_usec;
128✔
363

364
        if (*v + add < *v) /* overflow */
64✔
365
                *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
×
366
        else
367
                *v += add;
64✔
368

369
        log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
64✔
370
}
371

372
static void timer_enter_waiting(Timer *t, bool time_change) {
425✔
373
        bool found_monotonic = false, found_realtime = false;
425✔
374
        bool leave_around = false;
425✔
375
        triple_timestamp ts;
425✔
376
        Unit *trigger;
425✔
377
        int r;
425✔
378

379
        assert(t);
425✔
380

381
        trigger = UNIT_TRIGGER(UNIT(t));
425✔
382
        if (!trigger) {
425✔
383
                log_unit_error(UNIT(t), "Unit to trigger vanished.");
×
384
                goto fail;
×
385
        }
386

387
        triple_timestamp_now(&ts);
425✔
388
        t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
425✔
389

390
        LIST_FOREACH(value, v, t->values) {
1,133✔
391
                if (v->disabled)
708✔
392
                        continue;
4✔
393

394
                if (v->base == TIMER_CALENDAR) {
704✔
395
                        bool rebase_after_boot_time = false;
142✔
396
                        usec_t b, random_offset = 0;
142✔
397

398
                        if (t->random_offset_usec != 0)
142✔
399
                                random_offset = timer_get_fixed_delay_hash(t) % t->random_offset_usec;
×
400

401
                        /* If DeferReactivation= is enabled, schedule the job based on the last time
402
                         * the trigger unit entered inactivity. Otherwise, if we know the last time
403
                         * this was triggered, schedule the job based relative to that. If we don't,
404
                         * just start from the activation time or realtime.
405
                         *
406
                         * Unless we have a real last-trigger time, we subtract the random_offset because
407
                         * any event that elapsed within the last random_offset has actually been delayed
408
                         * and thus hasn't truly elapsed yet. */
409

410
                        if (t->defer_reactivation &&
142✔
411
                            dual_timestamp_is_set(&trigger->inactive_enter_timestamp)) {
3✔
412
                                if (dual_timestamp_is_set(&t->last_trigger))
2✔
413
                                        b = MAX(trigger->inactive_enter_timestamp.realtime,
2✔
414
                                                t->last_trigger.realtime);
415
                                else
416
                                        b = trigger->inactive_enter_timestamp.realtime;
417
                        } else if (dual_timestamp_is_set(&t->last_trigger))
140✔
418
                                b = t->last_trigger.realtime;
419
                        else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
126✔
420
                                b = UNIT(t)->inactive_exit_timestamp.realtime - random_offset;
80✔
421
                        else {
422
                                b = ts.realtime - random_offset;
46✔
423
                                rebase_after_boot_time = true;
46✔
424
                        }
425

426
                        r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
142✔
427
                        if (r < 0)
142✔
428
                                continue;
×
429

430
                        v->next_elapse += random_offset;
142✔
431

432
                        if (rebase_after_boot_time) {
142✔
433
                                /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
434
                                 * time has already passed, set the time when systemd first started as the scheduled
435
                                 * time. Note that we base this on the monotonic timestamp of the boot, not the
436
                                 * realtime one, since the wallclock might have been off during boot. */
437
                                usec_t rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
46✔
438
                                                         CLOCK_MONOTONIC, CLOCK_REALTIME);
439
                                if (v->next_elapse < rebased)
46✔
440
                                        v->next_elapse = rebased;
×
441
                        }
442

443
                        if (!found_realtime)
142✔
444
                                t->next_elapse_realtime = v->next_elapse;
142✔
445
                        else
446
                                t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
×
447

448
                        found_realtime = true;
449

450
                } else {
451
                        usec_t base;
562✔
452

453
                        switch (v->base) {
562✔
454

455
                        case TIMER_ACTIVE:
×
456
                                if (state_translation_table[t->state] == UNIT_ACTIVE)
×
457
                                        base = UNIT(t)->inactive_exit_timestamp.monotonic;
×
458
                                else
459
                                        base = ts.monotonic;
×
460
                                break;
461

462
                        case TIMER_BOOT:
64✔
463
                                if (detect_container() <= 0) {
64✔
464
                                        /* CLOCK_MONOTONIC equals the uptime on Linux */
465
                                        base = 0;
466
                                        break;
467
                                }
468
                                /* In a container we don't want to include the time the host
469
                                 * was already up when the container started, so count from
470
                                 * our own startup. */
471
                                _fallthrough_;
257✔
472
                        case TIMER_STARTUP:
473
                                base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
257✔
474
                                break;
257✔
475

476
                        case TIMER_UNIT_ACTIVE:
283✔
477
                                leave_around = true;
283✔
478
                                base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
283✔
479
                                if (base <= 0)
283✔
480
                                        continue;
275✔
481
                                break;
482

483
                        case TIMER_UNIT_INACTIVE:
×
484
                                leave_around = true;
×
485
                                base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
×
486
                                if (base <= 0)
×
487
                                        continue;
×
488
                                break;
489

490
                        default:
×
491
                                assert_not_reached();
×
492
                        }
493

494
                        if (!time_change)
287✔
495
                                v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
831✔
496

497
                        if (dual_timestamp_is_set(&t->last_trigger) &&
287✔
498
                            !time_change &&
12✔
499
                            v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
24✔
500
                            IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
4✔
501
                                /* This is a one time trigger, disable it now */
502
                                v->disabled = true;
4✔
503
                                continue;
4✔
504
                        }
505

506
                        if (!found_monotonic)
283✔
507
                                t->next_elapse_monotonic_or_boottime = v->next_elapse;
283✔
508
                        else
509
                                t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
×
510

511
                        found_monotonic = true;
512
                }
513
        }
514

515
        if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
425✔
516
                log_unit_debug(UNIT(t), "Timer is elapsed.");
×
517
                timer_enter_elapsed(t, leave_around);
×
518
                return;
425✔
519
        }
520

521
        if (found_monotonic) {
425✔
522
                usec_t left;
283✔
523

524
                add_random_delay(t, &t->next_elapse_monotonic_or_boottime);
283✔
525

526
                left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
566✔
527
                log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
283✔
528

529
                if (t->monotonic_event_source) {
283✔
530
                        r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
26✔
531
                        if (r < 0) {
26✔
532
                                log_unit_warning_errno(UNIT(t), r, "Failed to reschedule monotonic event source: %m");
×
533
                                goto fail;
×
534
                        }
535

536
                        r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
26✔
537
                        if (r < 0) {
26✔
538
                                log_unit_warning_errno(UNIT(t), r, "Failed to enable monotonic event source: %m");
×
539
                                goto fail;
×
540
                        }
541
                } else {
542
                        r = sd_event_add_time(
1,028✔
543
                                        UNIT(t)->manager->event,
257✔
544
                                        &t->monotonic_event_source,
545
                                        t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
257✔
546
                                        t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
257✔
547
                                        timer_dispatch, t);
548
                        if (r < 0) {
257✔
549
                                log_unit_warning_errno(UNIT(t), r, "Failed to add monotonic event source: %m");
×
550
                                goto fail;
×
551
                        }
552

553
                        (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
257✔
554
                }
555

556
        } else {
557
                r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
142✔
558
                if (r < 0) {
142✔
559
                        log_unit_warning_errno(UNIT(t), r, "Failed to disable monotonic event source: %m");
×
560
                        goto fail;
×
561
                }
562
        }
563

564
        if (found_realtime) {
425✔
565
                add_random_delay(t, &t->next_elapse_realtime);
142✔
566

567
                log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
142✔
568

569
                if (t->realtime_event_source) {
142✔
570
                        r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
×
571
                        if (r < 0) {
×
572
                                log_unit_warning_errno(UNIT(t), r, "Failed to reschedule realtime event source: %m");
×
573
                                goto fail;
×
574
                        }
575

576
                        r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
×
577
                        if (r < 0) {
×
578
                                log_unit_warning_errno(UNIT(t), r, "Failed to enable realtime event source: %m");
×
579
                                goto fail;
×
580
                        }
581
                } else {
582
                        r = sd_event_add_time(
568✔
583
                                        UNIT(t)->manager->event,
142✔
584
                                        &t->realtime_event_source,
585
                                        t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
142✔
586
                                        t->next_elapse_realtime, t->accuracy_usec,
142✔
587
                                        timer_dispatch, t);
588
                        if (r < 0) {
142✔
589
                                log_unit_warning_errno(UNIT(t), r, "Failed to add realtime event source: %m");
×
590
                                goto fail;
×
591
                        }
592

593
                        (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
142✔
594
                }
595

596
        } else if (t->realtime_event_source) {
283✔
597

598
                r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
×
599
                if (r < 0) {
×
600
                        log_unit_warning_errno(UNIT(t), r, "Failed to disable realtime event source: %m");
×
601
                        goto fail;
×
602
                }
603
        }
604

605
        timer_set_state(t, TIMER_WAITING);
425✔
606
        return;
607

608
fail:
×
609
        timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
×
610
}
611

612
static void timer_enter_running(Timer *t) {
7✔
613
        _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
7✔
614
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
7✔
615
        Unit *trigger;
7✔
616
        Job *job;
7✔
617
        int r;
7✔
618

619
        assert(t);
7✔
620

621
        /* Don't start job if we are supposed to go down */
622
        if (unit_stop_pending(UNIT(t)))
7✔
623
                return;
624

625
        trigger = UNIT_TRIGGER(UNIT(t));
7✔
626
        if (!trigger) {
7✔
627
                log_unit_error(UNIT(t), "Unit to trigger vanished.");
×
628
                goto fail;
×
629
        }
630

631
        details = activation_details_new(UNIT(t));
7✔
632
        if (!details) {
7✔
633
                log_oom();
×
634
                goto fail;
×
635
        }
636

637
        r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, &error, &job);
7✔
638
        if (r < 0) {
7✔
639
                log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
×
640
                goto fail;
×
641
        }
642

643
        dual_timestamp_now(&t->last_trigger);
7✔
644
        ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
7✔
645

646
        job_set_activation_details(job, details);
7✔
647

648
        if (t->stamp_path)
7✔
649
                touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
×
650

651
        timer_set_state(t, TIMER_RUNNING);
7✔
652
        return;
653

654
fail:
×
655
        timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
×
656
}
657

658
static int timer_start(Unit *u) {
273✔
659
        Timer *t = ASSERT_PTR(TIMER(u));
273✔
660
        int r;
273✔
661

662
        assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
273✔
663

664
        r = unit_test_trigger_loaded(u);
273✔
665
        if (r < 0)
273✔
666
                return r;
667

668
        r = unit_acquire_invocation_id(u);
273✔
669
        if (r < 0)
273✔
670
                return r;
671

672
        /* Reenable all timers that depend on unit activation time */
673
        LIST_FOREACH(value, v, t->values)
757✔
674
                if (v->base == TIMER_ACTIVE)
484✔
675
                        v->disabled = false;
×
676

677
        if (t->stamp_path) {
273✔
678
                struct stat st;
61✔
679

680
                if (stat(t->stamp_path, &st) >= 0) {
61✔
681
                        usec_t ft;
14✔
682

683
                        /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
684
                         * something is wrong with the system clock. */
685

686
                        ft = timespec_load(&st.st_mtim);
14✔
687
                        if (ft < now(CLOCK_REALTIME))
14✔
688
                                t->last_trigger.realtime = ft;
14✔
689
                        else
690
                                log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
×
691
                                                 FORMAT_TIMESTAMP(ft));
692

693
                } else if (errno == ENOENT)
47✔
694
                        /* The timer has never run before, make sure a stamp file exists. */
695
                        (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
47✔
696
        }
697

698
        t->result = TIMER_SUCCESS;
273✔
699
        timer_enter_waiting(t, false);
273✔
700
        return 1;
273✔
701
}
702

703
static int timer_stop(Unit *u) {
243✔
704
        Timer *t = ASSERT_PTR(TIMER(u));
243✔
705

706
        assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
243✔
707

708
        timer_enter_dead(t, TIMER_SUCCESS);
243✔
709
        return 1;
243✔
710
}
711

712
static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
172✔
713
        Timer *t = ASSERT_PTR(TIMER(u));
172✔
714

715
        assert(f);
172✔
716
        assert(fds);
172✔
717

718
        (void) serialize_item(f, "state", timer_state_to_string(t->state));
172✔
719
        (void) serialize_item(f, "result", timer_result_to_string(t->result));
172✔
720

721
        if (dual_timestamp_is_set(&t->last_trigger))
172✔
722
                (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
×
723

724
        if (t->last_trigger.monotonic > 0)
172✔
725
                (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
×
726

727
        return 0;
172✔
728
}
729

730
static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
252✔
731
        Timer *t = ASSERT_PTR(TIMER(u));
252✔
732

733
        assert(key);
252✔
734
        assert(value);
252✔
735
        assert(fds);
252✔
736

737
        if (streq(key, "state")) {
252✔
738
                TimerState state;
126✔
739

740
                state = timer_state_from_string(value);
126✔
741
                if (state < 0)
126✔
742
                        log_unit_debug(u, "Failed to parse state value: %s", value);
×
743
                else
744
                        t->deserialized_state = state;
126✔
745

746
        } else if (streq(key, "result")) {
126✔
747
                TimerResult f;
126✔
748

749
                f = timer_result_from_string(value);
126✔
750
                if (f < 0)
126✔
751
                        log_unit_debug(u, "Failed to parse result value: %s", value);
×
752
                else if (f != TIMER_SUCCESS)
126✔
753
                        t->result = f;
×
754

755
        } else if (streq(key, "last-trigger-realtime"))
×
756
                (void) deserialize_usec(value, &t->last_trigger.realtime);
×
757
        else if (streq(key, "last-trigger-monotonic"))
×
758
                (void) deserialize_usec(value, &t->last_trigger.monotonic);
×
759
        else
760
                log_unit_debug(u, "Unknown serialization key: %s", key);
×
761

762
        return 0;
252✔
763
}
764

765
static UnitActiveState timer_active_state(Unit *u) {
12,316✔
766
        Timer *t = ASSERT_PTR(TIMER(u));
12,316✔
767

768
        return state_translation_table[t->state];
12,316✔
769
}
770

771
static const char *timer_sub_state_to_string(Unit *u) {
409✔
772
        Timer *t = ASSERT_PTR(TIMER(u));
409✔
773

774
        return timer_state_to_string(t->state);
409✔
775
}
776

777
static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
7✔
778
        Timer *t = ASSERT_PTR(TIMER(userdata));
7✔
779

780
        if (t->state != TIMER_WAITING)
7✔
781
                return 0;
782

783
        log_unit_debug(UNIT(t), "Timer elapsed.");
7✔
784
        timer_enter_running(t);
7✔
785
        return 0;
7✔
786
}
787

788
static void timer_trigger_notify(Unit *u, Unit *other) {
20✔
789
        Timer *t = ASSERT_PTR(TIMER(u));
20✔
790

791
        assert(other);
20✔
792

793
        /* Filter out invocations with bogus state */
794
        assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
20✔
795

796
        /* Reenable all timers that depend on unit state */
797
        LIST_FOREACH(value, v, t->values)
52✔
798
                if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
32✔
799
                        v->disabled = false;
12✔
800

801
        switch (t->state) {
20✔
802

803
        case TIMER_WAITING:
4✔
804
        case TIMER_ELAPSED:
805

806
                /* Recalculate sleep time */
807
                timer_enter_waiting(t, false);
4✔
808
                break;
4✔
809

810
        case TIMER_RUNNING:
16✔
811

812
                if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
16✔
813
                        log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
6✔
814
                        timer_enter_waiting(t, false);
6✔
815
                }
816
                break;
817

818
        case TIMER_DEAD:
819
        case TIMER_FAILED:
820
                break;
821

822
        default:
×
823
                assert_not_reached();
×
824
        }
825
}
20✔
826

827
static void timer_reset_failed(Unit *u) {
3✔
828
        Timer *t = ASSERT_PTR(TIMER(u));
3✔
829

830
        if (t->state == TIMER_FAILED)
3✔
831
                timer_set_state(t, TIMER_DEAD);
×
832

833
        t->result = TIMER_SUCCESS;
3✔
834
}
3✔
835

836
static void timer_time_change(Unit *u) {
10✔
837
        Timer *t = ASSERT_PTR(TIMER(u));
10✔
838
        usec_t ts;
10✔
839

840
        if (t->state != TIMER_WAITING)
10✔
841
                return;
842

843
        /* If we appear to have triggered in the future, the system clock must
844
         * have been set backwards.  So let's rewind our own clock and allow
845
         * the future triggers to happen again :).  Exactly the same as when
846
         * you start a timer unit with Persistent=yes. */
847
        ts = now(CLOCK_REALTIME);
10✔
848
        if (t->last_trigger.realtime > ts)
10✔
849
                t->last_trigger.realtime = ts;
×
850

851
        if (t->on_clock_change) {
10✔
852
                log_unit_debug(u, "Time change, triggering activation.");
×
853
                timer_enter_running(t);
×
854
        } else {
855
                log_unit_debug(u, "Time change, recalculating next elapse.");
10✔
856
                timer_enter_waiting(t, true);
10✔
857
        }
858
}
859

860
static void timer_timezone_change(Unit *u) {
67✔
861
        Timer *t = ASSERT_PTR(TIMER(u));
67✔
862

863
        if (t->state != TIMER_WAITING)
67✔
864
                return;
865

866
        if (t->on_timezone_change) {
12✔
867
                log_unit_debug(u, "Timezone change, triggering activation.");
×
868
                timer_enter_running(t);
×
869
        } else {
870
                log_unit_debug(u, "Timezone change, recalculating next elapse.");
12✔
871
                timer_enter_waiting(t, false);
12✔
872
        }
873
}
874

875
static int timer_clean(Unit *u, ExecCleanMask mask) {
×
876
        Timer *t = ASSERT_PTR(TIMER(u));
×
877
        int r;
×
878

879
        assert(mask != 0);
×
880

881
        if (t->state != TIMER_DEAD)
×
882
                return -EBUSY;
883

884
        if (mask != EXEC_CLEAN_STATE)
×
885
                return -EUNATCH;
886

887
        r = timer_setup_persistent(t);
×
888
        if (r < 0)
×
889
                return r;
890

891
        if (!t->stamp_path)
×
892
                return -EUNATCH;
893

894
        if (unlink(t->stamp_path) && errno != ENOENT)
×
895
                return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
×
896

897
        return 0;
898
}
899

900
static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
7✔
901
        Timer *t = ASSERT_PTR(TIMER(u));
7✔
902

903
        assert(ret);
7✔
904

905
        *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
7✔
906
        return 0;
7✔
907
}
908

909
static int timer_can_start(Unit *u) {
273✔
910
        Timer *t = ASSERT_PTR(TIMER(u));
273✔
911
        int r;
273✔
912

913
        r = unit_test_start_limit(u);
273✔
914
        if (r < 0) {
273✔
915
                timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
×
916
                return r;
×
917
        }
918

919
        return 1;
920
}
921

922
static void activation_details_timer_serialize(const ActivationDetails *details, FILE *f) {
×
923
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
×
924

925
        assert(f);
×
926
        assert(t);
×
927

928
        (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
×
929
}
×
930

931
static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
×
932
        int r;
×
933

934
        assert(key);
×
935
        assert(value);
×
936

937
        if (!details || !*details)
×
938
                return -EINVAL;
939

940
        ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
×
941
        if (!t)
×
942
                return -EINVAL;
943

944
        if (!streq(key, "activation-details-timer-last-trigger"))
×
945
                return -EINVAL;
946

947
        r = deserialize_dual_timestamp(value, &t->last_trigger);
×
948
        if (r < 0)
×
949
                return r;
×
950

951
        return 0;
952
}
953

954
static int activation_details_timer_append_env(const ActivationDetails *details, char ***strv) {
7✔
955
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
7✔
956
        int r;
7✔
957

958
        assert(strv);
7✔
959
        assert(t);
7✔
960

961
        if (!dual_timestamp_is_set(&t->last_trigger))
7✔
962
                return 0;
963

964
        r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
7✔
965
        if (r < 0)
7✔
966
                return r;
967

968
        r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
7✔
969
        if (r < 0)
7✔
970
                return r;
×
971

972
        return 2; /* Return the number of variables added to the env block */
973
}
974

975
static int activation_details_timer_append_pair(const ActivationDetails *details, char ***strv) {
19✔
976
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
19✔
977
        int r;
19✔
978

979
        assert(strv);
19✔
980
        assert(t);
19✔
981

982
        if (!dual_timestamp_is_set(&t->last_trigger))
19✔
983
                return 0;
984

985
        r = strv_extend(strv, "trigger_timer_realtime_usec");
19✔
986
        if (r < 0)
19✔
987
                return r;
988

989
        r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
19✔
990
        if (r < 0)
19✔
991
                return r;
992

993
        r = strv_extend(strv, "trigger_timer_monotonic_usec");
19✔
994
        if (r < 0)
19✔
995
                return r;
996

997
        r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
19✔
998
        if (r < 0)
19✔
999
                return r;
×
1000

1001
        return 2; /* Return the number of pairs added to the env block */
1002
}
1003

1004
uint64_t timer_next_elapse_monotonic(const Timer *t) {
374✔
1005
        assert(t);
374✔
1006

1007
        return (uint64_t) usec_shift_clock(t->next_elapse_monotonic_or_boottime,
374✔
1008
                                           TIMER_MONOTONIC_CLOCK(t), CLOCK_MONOTONIC);
374✔
1009
}
1010

1011
static const char* const timer_base_table[_TIMER_BASE_MAX] = {
1012
        [TIMER_ACTIVE]        = "OnActiveSec",
1013
        [TIMER_BOOT]          = "OnBootSec",
1014
        [TIMER_STARTUP]       = "OnStartupSec",
1015
        [TIMER_UNIT_ACTIVE]   = "OnUnitActiveSec",
1016
        [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
1017
        [TIMER_CALENDAR]      = "OnCalendar",
1018
};
1019

1020
DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
66✔
1021

1022
char* timer_base_to_usec_string(TimerBase i) {
4✔
1023
        _cleanup_free_ char *buf = NULL;
8✔
1024
        const char *s;
4✔
1025
        size_t l;
4✔
1026

1027
        s = timer_base_to_string(i);
4✔
1028

1029
        if (endswith(s, "Sec")) {
4✔
1030
                /* s/Sec/USec/ */
1031
                l = strlen(s);
4✔
1032
                buf = new(char, l+2);
4✔
1033
                if (!buf)
4✔
1034
                        return NULL;
1035

1036
                memcpy(buf, s, l-3);
4✔
1037
                memcpy(buf+l-3, "USec", 5);
4✔
1038
        } else {
1039
                buf = strdup(s);
×
1040
                if (!buf)
×
1041
                        return NULL;
×
1042
        }
1043

1044
        return TAKE_PTR(buf);
1045
}
1046

1047
static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
1048
        [TIMER_SUCCESS]                 = "success",
1049
        [TIMER_FAILURE_RESOURCES]       = "resources",
1050
        [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1051
};
1052

1053
DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
967✔
1054

1055
const UnitVTable timer_vtable = {
1056
        .object_size = sizeof(Timer),
1057

1058
        .sections =
1059
                "Unit\0"
1060
                "Timer\0"
1061
                "Install\0",
1062
        .private_section = "Timer",
1063

1064
        .can_transient = true,
1065
        .can_fail = true,
1066
        .can_trigger = true,
1067

1068
        .init = timer_init,
1069
        .done = timer_done,
1070
        .load = timer_load,
1071

1072
        .coldplug = timer_coldplug,
1073

1074
        .dump = timer_dump,
1075

1076
        .start = timer_start,
1077
        .stop = timer_stop,
1078

1079
        .clean = timer_clean,
1080
        .can_clean = timer_can_clean,
1081

1082
        .serialize = timer_serialize,
1083
        .deserialize_item = timer_deserialize_item,
1084

1085
        .active_state = timer_active_state,
1086
        .sub_state_to_string = timer_sub_state_to_string,
1087

1088
        .trigger_notify = timer_trigger_notify,
1089

1090
        .reset_failed = timer_reset_failed,
1091
        .time_change = timer_time_change,
1092
        .timezone_change = timer_timezone_change,
1093

1094
        .bus_set_property = bus_timer_set_property,
1095

1096
        .can_start = timer_can_start,
1097
};
1098

1099
const ActivationDetailsVTable activation_details_timer_vtable = {
1100
        .object_size = sizeof(ActivationDetailsTimer),
1101

1102
        .serialize = activation_details_timer_serialize,
1103
        .deserialize = activation_details_timer_deserialize,
1104
        .append_env = activation_details_timer_append_env,
1105
        .append_pair = activation_details_timer_append_pair,
1106
};
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc