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

systemd / systemd / 15720680019

17 Jun 2025 07:58PM UTC coverage: 72.087% (-0.02%) from 72.109%
15720680019

push

github

web-flow
sd-lldp: several improvements (#37845)

This makes
- sd-lldp-tx not send machine ID as chassis ID, but use application
specific machine ID,
- sd-lldp-tx emit vlan ID if it is running on a vlan interface,
- Describe() DBus method also reply LLDP configurations,
- io.systemd.Network.GetLLDPNeighbors varlink method provides vlan ID,
if received.

Closes #37613.

59 of 76 new or added lines in 3 files covered. (77.63%)

4663 existing lines in 75 files now uncovered.

300494 of 416851 relevant lines covered (72.09%)

704683.58 hits per line

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

65.56
/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) {
494✔
39
        Timer *t = ASSERT_PTR(TIMER(u));
494✔
40

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

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

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

52
        assert(t);
494✔
53

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

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

63
        timer_free_values(t);
494✔
64

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

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

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

75
        if (!t->values && !t->on_clock_change && !t->on_timezone_change)
494✔
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) {
494✔
82
        int r;
494✔
83

84
        assert(t);
494✔
85

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

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

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

98
                LIST_FOREACH(value, v, t->values) {
538✔
99
                        if (v->base != TIMER_CALENDAR)
428✔
100
                                continue;
220✔
101

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

108
                        break;
208✔
109
                }
110
        }
111

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

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

119
        assert(t);
494✔
120

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

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

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

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

135
        assert(t);
494✔
136

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

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

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

146
                stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
206✔
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)
206✔
166
                return log_oom();
×
167

168
        return free_and_replace(t->stamp_path, stamp_path);
206✔
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) {
494✔
202
        Timer *t = ASSERT_PTR(TIMER(u));
494✔
203
        int r;
494✔
204

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

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

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

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

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

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

227
        return timer_verify(t);
494✔
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) {
665✔
283
        TimerState old_state;
665✔
284

285
        assert(t);
665✔
286

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

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

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

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

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

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

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

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

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

316
        if (t->deserialized_state == TIMER_WAITING)
156✔
317
                timer_enter_waiting(t, false);
156✔
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) {
224✔
325
        assert(t);
224✔
326

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

330
        unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
224✔
331
        timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
448✔
332
}
224✔
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) {
435✔
352
        usec_t add;
435✔
353

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

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

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

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

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

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

379
        assert(t);
435✔
380

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

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

390
        LIST_FOREACH(value, v, t->values) {
1,146✔
391
                if (v->disabled)
711✔
392
                        continue;
6✔
393

394
                if (v->base == TIMER_CALENDAR) {
705✔
395
                        usec_t b, rebased, random_offset = 0;
159✔
396

397
                        if (t->random_offset_usec != 0)
159✔
UNCOV
398
                                random_offset = timer_get_fixed_delay_hash(t) % t->random_offset_usec;
×
399

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

409
                        if (t->defer_reactivation &&
159✔
UNCOV
410
                            dual_timestamp_is_set(&trigger->inactive_enter_timestamp)) {
×
UNCOV
411
                                if (dual_timestamp_is_set(&t->last_trigger))
×
UNCOV
412
                                        b = MAX(trigger->inactive_enter_timestamp.realtime,
×
413
                                                t->last_trigger.realtime);
414
                                else
415
                                        b = trigger->inactive_enter_timestamp.realtime;
416
                        } else if (dual_timestamp_is_set(&t->last_trigger))
159✔
417
                                b = t->last_trigger.realtime;
418
                        else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
145✔
419
                                b = UNIT(t)->inactive_exit_timestamp.realtime - random_offset;
104✔
420
                        else
421
                                b = ts.realtime - random_offset;
41✔
422

423
                        r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
159✔
424
                        if (r < 0)
159✔
UNCOV
425
                                continue;
×
426

427
                        v->next_elapse += random_offset;
159✔
428

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

438
                        if (!found_realtime)
159✔
439
                                t->next_elapse_realtime = v->next_elapse;
159✔
440
                        else
441
                                t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
×
442

443
                        found_realtime = true;
444

445
                } else {
446
                        usec_t base;
546✔
447

448
                        switch (v->base) {
546✔
449

UNCOV
450
                        case TIMER_ACTIVE:
×
UNCOV
451
                                if (state_translation_table[t->state] == UNIT_ACTIVE)
×
UNCOV
452
                                        base = UNIT(t)->inactive_exit_timestamp.monotonic;
×
453
                                else
UNCOV
454
                                        base = ts.monotonic;
×
455
                                break;
456

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

471
                        case TIMER_UNIT_ACTIVE:
276✔
472
                                leave_around = true;
276✔
473
                                base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
276✔
474
                                if (base <= 0)
276✔
475
                                        continue;
264✔
476
                                break;
477

UNCOV
478
                        case TIMER_UNIT_INACTIVE:
×
UNCOV
479
                                leave_around = true;
×
UNCOV
480
                                base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
×
UNCOV
481
                                if (base <= 0)
×
UNCOV
482
                                        continue;
×
483
                                break;
484

UNCOV
485
                        default:
×
UNCOV
486
                                assert_not_reached();
×
487
                        }
488

489
                        v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
564✔
490

491
                        if (dual_timestamp_is_set(&t->last_trigger) &&
282✔
492
                            !time_change &&
18✔
493
                            v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
36✔
494
                            IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
6✔
495
                                /* This is a one time trigger, disable it now */
496
                                v->disabled = true;
6✔
497
                                continue;
6✔
498
                        }
499

500
                        if (!found_monotonic)
276✔
501
                                t->next_elapse_monotonic_or_boottime = v->next_elapse;
276✔
502
                        else
UNCOV
503
                                t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
×
504

505
                        found_monotonic = true;
506
                }
507
        }
508

509
        if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
435✔
UNCOV
510
                log_unit_debug(UNIT(t), "Timer is elapsed.");
×
UNCOV
511
                timer_enter_elapsed(t, leave_around);
×
512
                return;
435✔
513
        }
514

515
        if (found_monotonic) {
435✔
516
                usec_t left;
276✔
517

518
                add_random_delay(t, &t->next_elapse_monotonic_or_boottime);
276✔
519

520
                left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
552✔
521
                log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
552✔
522

523
                if (t->monotonic_event_source) {
276✔
524
                        r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
19✔
525
                        if (r < 0) {
19✔
UNCOV
526
                                log_unit_warning_errno(UNIT(t), r, "Failed to reschedule monotonic event source: %m");
×
UNCOV
527
                                goto fail;
×
528
                        }
529

530
                        r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
19✔
531
                        if (r < 0) {
19✔
UNCOV
532
                                log_unit_warning_errno(UNIT(t), r, "Failed to enable monotonic event source: %m");
×
UNCOV
533
                                goto fail;
×
534
                        }
535
                } else {
536
                        r = sd_event_add_time(
1,028✔
537
                                        UNIT(t)->manager->event,
257✔
538
                                        &t->monotonic_event_source,
539
                                        t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
257✔
540
                                        t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
257✔
541
                                        timer_dispatch, t);
542
                        if (r < 0) {
257✔
UNCOV
543
                                log_unit_warning_errno(UNIT(t), r, "Failed to add monotonic event source: %m");
×
544
                                goto fail;
×
545
                        }
546

547
                        (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
257✔
548
                }
549

550
        } else {
551
                r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
159✔
552
                if (r < 0) {
159✔
UNCOV
553
                        log_unit_warning_errno(UNIT(t), r, "Failed to disable monotonic event source: %m");
×
UNCOV
554
                        goto fail;
×
555
                }
556
        }
557

558
        if (found_realtime) {
435✔
559
                add_random_delay(t, &t->next_elapse_realtime);
159✔
560

561
                log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
159✔
562

563
                if (t->realtime_event_source) {
159✔
564
                        r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
×
UNCOV
565
                        if (r < 0) {
×
UNCOV
566
                                log_unit_warning_errno(UNIT(t), r, "Failed to reschedule realtime event source: %m");
×
UNCOV
567
                                goto fail;
×
568
                        }
569

UNCOV
570
                        r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
×
UNCOV
571
                        if (r < 0) {
×
UNCOV
572
                                log_unit_warning_errno(UNIT(t), r, "Failed to enable realtime event source: %m");
×
UNCOV
573
                                goto fail;
×
574
                        }
575
                } else {
576
                        r = sd_event_add_time(
636✔
577
                                        UNIT(t)->manager->event,
159✔
578
                                        &t->realtime_event_source,
579
                                        t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
159✔
580
                                        t->next_elapse_realtime, t->accuracy_usec,
159✔
581
                                        timer_dispatch, t);
582
                        if (r < 0) {
159✔
583
                                log_unit_warning_errno(UNIT(t), r, "Failed to add realtime event source: %m");
×
584
                                goto fail;
×
585
                        }
586

587
                        (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
159✔
588
                }
589

590
        } else if (t->realtime_event_source) {
276✔
591

UNCOV
592
                r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
×
593
                if (r < 0) {
×
594
                        log_unit_warning_errno(UNIT(t), r, "Failed to disable realtime event source: %m");
×
UNCOV
595
                        goto fail;
×
596
                }
597
        }
598

599
        timer_set_state(t, TIMER_WAITING);
435✔
600
        return;
601

UNCOV
602
fail:
×
UNCOV
603
        timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
×
604
}
605

606
static void timer_enter_running(Timer *t) {
6✔
607
        _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
6✔
608
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
6✔
609
        Unit *trigger;
6✔
610
        Job *job;
6✔
611
        int r;
6✔
612

613
        assert(t);
6✔
614

615
        /* Don't start job if we are supposed to go down */
616
        if (unit_stop_pending(UNIT(t)))
6✔
617
                return;
618

619
        trigger = UNIT_TRIGGER(UNIT(t));
6✔
620
        if (!trigger) {
6✔
UNCOV
621
                log_unit_error(UNIT(t), "Unit to trigger vanished.");
×
UNCOV
622
                goto fail;
×
623
        }
624

625
        details = activation_details_new(UNIT(t));
6✔
626
        if (!details) {
6✔
UNCOV
627
                log_oom();
×
UNCOV
628
                goto fail;
×
629
        }
630

631
        r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, &error, &job);
6✔
632
        if (r < 0) {
6✔
UNCOV
633
                log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
×
634
                goto fail;
×
635
        }
636

637
        dual_timestamp_now(&t->last_trigger);
6✔
638
        ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
6✔
639

640
        job_set_activation_details(job, details);
6✔
641

642
        if (t->stamp_path)
6✔
UNCOV
643
                touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
×
644

645
        timer_set_state(t, TIMER_RUNNING);
6✔
646
        return;
647

UNCOV
648
fail:
×
UNCOV
649
        timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
×
650
}
651

652
static int timer_start(Unit *u) {
254✔
653
        Timer *t = ASSERT_PTR(TIMER(u));
254✔
654
        int r;
254✔
655

656
        assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
254✔
657

658
        r = unit_test_trigger_loaded(u);
254✔
659
        if (r < 0)
254✔
660
                return r;
661

662
        r = unit_acquire_invocation_id(u);
254✔
663
        if (r < 0)
254✔
664
                return r;
665

666
        t->last_trigger = DUAL_TIMESTAMP_NULL;
254✔
667

668
        /* Reenable all timers that depend on unit activation time */
669
        LIST_FOREACH(value, v, t->values)
705✔
670
                if (v->base == TIMER_ACTIVE)
451✔
UNCOV
671
                        v->disabled = false;
×
672

673
        if (t->stamp_path) {
254✔
674
                struct stat st;
57✔
675

676
                if (stat(t->stamp_path, &st) >= 0) {
57✔
677
                        usec_t ft;
14✔
678

679
                        /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
680
                         * something is wrong with the system clock. */
681

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

689
                } else if (errno == ENOENT)
43✔
690
                        /* The timer has never run before, make sure a stamp file exists. */
691
                        (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
43✔
692
        }
693

694
        t->result = TIMER_SUCCESS;
254✔
695
        timer_enter_waiting(t, false);
254✔
696
        return 1;
697
}
698

699
static int timer_stop(Unit *u) {
224✔
700
        Timer *t = ASSERT_PTR(TIMER(u));
224✔
701

702
        assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
224✔
703

704
        timer_enter_dead(t, TIMER_SUCCESS);
224✔
705
        return 1;
224✔
706
}
707

708
static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
204✔
709
        Timer *t = ASSERT_PTR(TIMER(u));
204✔
710

711
        assert(f);
204✔
712
        assert(fds);
204✔
713

714
        (void) serialize_item(f, "state", timer_state_to_string(t->state));
204✔
715
        (void) serialize_item(f, "result", timer_result_to_string(t->result));
204✔
716

717
        if (dual_timestamp_is_set(&t->last_trigger))
204✔
UNCOV
718
                (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
×
719

720
        if (t->last_trigger.monotonic > 0)
204✔
UNCOV
721
                (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
×
722

723
        return 0;
204✔
724
}
725

726
static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
324✔
727
        Timer *t = ASSERT_PTR(TIMER(u));
324✔
728

729
        assert(key);
324✔
730
        assert(value);
324✔
731
        assert(fds);
324✔
732

733
        if (streq(key, "state")) {
324✔
734
                TimerState state;
162✔
735

736
                state = timer_state_from_string(value);
162✔
737
                if (state < 0)
162✔
738
                        log_unit_debug(u, "Failed to parse state value: %s", value);
×
739
                else
740
                        t->deserialized_state = state;
162✔
741

742
        } else if (streq(key, "result")) {
162✔
743
                TimerResult f;
162✔
744

745
                f = timer_result_from_string(value);
162✔
746
                if (f < 0)
162✔
747
                        log_unit_debug(u, "Failed to parse result value: %s", value);
×
748
                else if (f != TIMER_SUCCESS)
162✔
UNCOV
749
                        t->result = f;
×
750

UNCOV
751
        } else if (streq(key, "last-trigger-realtime"))
×
UNCOV
752
                (void) deserialize_usec(value, &t->last_trigger.realtime);
×
UNCOV
753
        else if (streq(key, "last-trigger-monotonic"))
×
UNCOV
754
                (void) deserialize_usec(value, &t->last_trigger.monotonic);
×
755
        else
UNCOV
756
                log_unit_debug(u, "Unknown serialization key: %s", key);
×
757

758
        return 0;
324✔
759
}
760

761
static UnitActiveState timer_active_state(Unit *u) {
12,376✔
762
        Timer *t = ASSERT_PTR(TIMER(u));
12,376✔
763

764
        return state_translation_table[t->state];
12,376✔
765
}
766

767
static const char *timer_sub_state_to_string(Unit *u) {
417✔
768
        Timer *t = ASSERT_PTR(TIMER(u));
417✔
769

770
        return timer_state_to_string(t->state);
417✔
771
}
772

773
static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
6✔
774
        Timer *t = ASSERT_PTR(TIMER(userdata));
6✔
775

776
        if (t->state != TIMER_WAITING)
6✔
777
                return 0;
778

779
        log_unit_debug(UNIT(t), "Timer elapsed.");
6✔
780
        timer_enter_running(t);
6✔
781
        return 0;
6✔
782
}
783

784
static void timer_trigger_notify(Unit *u, Unit *other) {
18✔
785
        Timer *t = ASSERT_PTR(TIMER(u));
18✔
786

787
        assert(other);
18✔
788

789
        /* Filter out invocations with bogus state */
790
        assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
18✔
791

792
        /* Reenable all timers that depend on unit state */
793
        LIST_FOREACH(value, v, t->values)
54✔
794
                if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
36✔
795
                        v->disabled = false;
18✔
796

797
        switch (t->state) {
18✔
798

799
        case TIMER_WAITING:
6✔
800
        case TIMER_ELAPSED:
801

802
                /* Recalculate sleep time */
803
                timer_enter_waiting(t, false);
6✔
804
                break;
6✔
805

806
        case TIMER_RUNNING:
12✔
807

808
                if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
12✔
809
                        log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
6✔
810
                        timer_enter_waiting(t, false);
6✔
811
                }
812
                break;
813

814
        case TIMER_DEAD:
815
        case TIMER_FAILED:
816
                break;
817

818
        default:
×
UNCOV
819
                assert_not_reached();
×
820
        }
821
}
18✔
822

823
static void timer_reset_failed(Unit *u) {
3✔
824
        Timer *t = ASSERT_PTR(TIMER(u));
3✔
825

826
        if (t->state == TIMER_FAILED)
3✔
UNCOV
827
                timer_set_state(t, TIMER_DEAD);
×
828

829
        t->result = TIMER_SUCCESS;
3✔
830
}
3✔
831

832
static void timer_time_change(Unit *u) {
3✔
833
        Timer *t = ASSERT_PTR(TIMER(u));
3✔
834
        usec_t ts;
3✔
835

836
        if (t->state != TIMER_WAITING)
3✔
837
                return;
838

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

847
        if (t->on_clock_change) {
3✔
UNCOV
848
                log_unit_debug(u, "Time change, triggering activation.");
×
UNCOV
849
                timer_enter_running(t);
×
850
        } else {
851
                log_unit_debug(u, "Time change, recalculating next elapse.");
3✔
852
                timer_enter_waiting(t, true);
3✔
853
        }
854
}
855

856
static void timer_timezone_change(Unit *u) {
25✔
857
        Timer *t = ASSERT_PTR(TIMER(u));
25✔
858

859
        if (t->state != TIMER_WAITING)
25✔
860
                return;
861

862
        if (t->on_timezone_change) {
10✔
863
                log_unit_debug(u, "Timezone change, triggering activation.");
×
864
                timer_enter_running(t);
×
865
        } else {
866
                log_unit_debug(u, "Timezone change, recalculating next elapse.");
10✔
867
                timer_enter_waiting(t, false);
10✔
868
        }
869
}
870

871
static int timer_clean(Unit *u, ExecCleanMask mask) {
×
UNCOV
872
        Timer *t = ASSERT_PTR(TIMER(u));
×
UNCOV
873
        int r;
×
874

875
        assert(mask != 0);
×
876

UNCOV
877
        if (t->state != TIMER_DEAD)
×
878
                return -EBUSY;
879

UNCOV
880
        if (mask != EXEC_CLEAN_STATE)
×
881
                return -EUNATCH;
882

UNCOV
883
        r = timer_setup_persistent(t);
×
UNCOV
884
        if (r < 0)
×
885
                return r;
886

UNCOV
887
        if (!t->stamp_path)
×
888
                return -EUNATCH;
889

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

893
        return 0;
894
}
895

896
static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
10✔
897
        Timer *t = ASSERT_PTR(TIMER(u));
10✔
898

899
        assert(ret);
10✔
900

901
        *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
10✔
902
        return 0;
10✔
903
}
904

905
static int timer_can_start(Unit *u) {
254✔
906
        Timer *t = ASSERT_PTR(TIMER(u));
254✔
907
        int r;
254✔
908

909
        r = unit_test_start_limit(u);
254✔
910
        if (r < 0) {
254✔
UNCOV
911
                timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
×
912
                return r;
×
913
        }
914

915
        return 1;
916
}
917

918
static void activation_details_timer_serialize(const ActivationDetails *details, FILE *f) {
×
919
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
×
920

921
        assert(f);
×
922
        assert(t);
×
923

924
        (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
×
UNCOV
925
}
×
926

927
static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
×
928
        int r;
×
929

UNCOV
930
        assert(key);
×
931
        assert(value);
×
932

UNCOV
933
        if (!details || !*details)
×
934
                return -EINVAL;
935

936
        ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
×
UNCOV
937
        if (!t)
×
938
                return -EINVAL;
939

UNCOV
940
        if (!streq(key, "activation-details-timer-last-trigger"))
×
941
                return -EINVAL;
942

UNCOV
943
        r = deserialize_dual_timestamp(value, &t->last_trigger);
×
UNCOV
944
        if (r < 0)
×
UNCOV
945
                return r;
×
946

947
        return 0;
948
}
949

950
static int activation_details_timer_append_env(const ActivationDetails *details, char ***strv) {
6✔
951
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
6✔
952
        int r;
6✔
953

954
        assert(strv);
6✔
955
        assert(t);
6✔
956

957
        if (!dual_timestamp_is_set(&t->last_trigger))
6✔
958
                return 0;
959

960
        r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
6✔
961
        if (r < 0)
6✔
962
                return r;
963

964
        r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
6✔
965
        if (r < 0)
6✔
966
                return r;
×
967

968
        return 2; /* Return the number of variables added to the env block */
969
}
970

UNCOV
971
static int activation_details_timer_append_pair(const ActivationDetails *details, char ***strv) {
×
972
        const ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
×
973
        int r;
×
974

UNCOV
975
        assert(strv);
×
976
        assert(t);
×
977

UNCOV
978
        if (!dual_timestamp_is_set(&t->last_trigger))
×
979
                return 0;
980

981
        r = strv_extend(strv, "trigger_timer_realtime_usec");
×
UNCOV
982
        if (r < 0)
×
983
                return r;
984

985
        r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
×
986
        if (r < 0)
×
987
                return r;
988

UNCOV
989
        r = strv_extend(strv, "trigger_timer_monotonic_usec");
×
UNCOV
990
        if (r < 0)
×
991
                return r;
992

UNCOV
993
        r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
×
UNCOV
994
        if (r < 0)
×
UNCOV
995
                return r;
×
996

997
        return 2; /* Return the number of pairs added to the env block */
998
}
999

1000
uint64_t timer_next_elapse_monotonic(const Timer *t) {
376✔
1001
        assert(t);
376✔
1002

1003
        return (uint64_t) usec_shift_clock(t->next_elapse_monotonic_or_boottime,
376✔
1004
                                           TIMER_MONOTONIC_CLOCK(t), CLOCK_MONOTONIC);
376✔
1005
}
1006

1007
static const char* const timer_base_table[_TIMER_BASE_MAX] = {
1008
        [TIMER_ACTIVE]        = "OnActiveSec",
1009
        [TIMER_BOOT]          = "OnBootSec",
1010
        [TIMER_STARTUP]       = "OnStartupSec",
1011
        [TIMER_UNIT_ACTIVE]   = "OnUnitActiveSec",
1012
        [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
1013
        [TIMER_CALENDAR]      = "OnCalendar",
1014
};
1015

1016
DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
70✔
1017

1018
char* timer_base_to_usec_string(TimerBase i) {
6✔
1019
        _cleanup_free_ char *buf = NULL;
12✔
1020
        const char *s;
6✔
1021
        size_t l;
6✔
1022

1023
        s = timer_base_to_string(i);
6✔
1024

1025
        if (endswith(s, "Sec")) {
6✔
1026
                /* s/Sec/USec/ */
1027
                l = strlen(s);
6✔
1028
                buf = new(char, l+2);
6✔
1029
                if (!buf)
6✔
1030
                        return NULL;
1031

1032
                memcpy(buf, s, l-3);
6✔
1033
                memcpy(buf+l-3, "USec", 5);
6✔
1034
        } else {
UNCOV
1035
                buf = strdup(s);
×
UNCOV
1036
                if (!buf)
×
UNCOV
1037
                        return NULL;
×
1038
        }
1039

1040
        return TAKE_PTR(buf);
1041
}
1042

1043
static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
1044
        [TIMER_SUCCESS]                 = "success",
1045
        [TIMER_FAILURE_RESOURCES]       = "resources",
1046
        [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
1047
};
1048

1049
DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1,018✔
1050

1051
const UnitVTable timer_vtable = {
1052
        .object_size = sizeof(Timer),
1053

1054
        .sections =
1055
                "Unit\0"
1056
                "Timer\0"
1057
                "Install\0",
1058
        .private_section = "Timer",
1059

1060
        .can_transient = true,
1061
        .can_fail = true,
1062
        .can_trigger = true,
1063

1064
        .init = timer_init,
1065
        .done = timer_done,
1066
        .load = timer_load,
1067

1068
        .coldplug = timer_coldplug,
1069

1070
        .dump = timer_dump,
1071

1072
        .start = timer_start,
1073
        .stop = timer_stop,
1074

1075
        .clean = timer_clean,
1076
        .can_clean = timer_can_clean,
1077

1078
        .serialize = timer_serialize,
1079
        .deserialize_item = timer_deserialize_item,
1080

1081
        .active_state = timer_active_state,
1082
        .sub_state_to_string = timer_sub_state_to_string,
1083

1084
        .trigger_notify = timer_trigger_notify,
1085

1086
        .reset_failed = timer_reset_failed,
1087
        .time_change = timer_time_change,
1088
        .timezone_change = timer_timezone_change,
1089

1090
        .bus_set_property = bus_timer_set_property,
1091

1092
        .can_start = timer_can_start,
1093
};
1094

1095
const ActivationDetailsVTable activation_details_timer_vtable = {
1096
        .object_size = sizeof(ActivationDetailsTimer),
1097

1098
        .serialize = activation_details_timer_serialize,
1099
        .deserialize = activation_details_timer_deserialize,
1100
        .append_env = activation_details_timer_append_env,
1101
        .append_pair = activation_details_timer_append_pair,
1102
};
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