zoter 0.2.0

Restart systemd services without dropping their clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! The file descriptor store of a service, through which it hands over to its next instance:
//! [`Store`], and what a hand-over stored: [`Stored`].

use std::{
    collections::{BTreeSet, HashMap},
    env, io,
    ops::Range,
    os::fd::{AsFd, BorrowedFd, OwnedFd},
    time::Duration,
};

use rustix::{
    io::{Errno, fcntl_dupfd_cloexec},
    pipe::{PipeFlags, pipe_with},
};

use crate::{
    Error, Passed, Restored, Result, Save,
    layout::{self, Entry, Layout},
    memfd,
    notifier::{MAX_FDS, Notifier},
    queue::{self, Queue},
    restored::Slot,
};

/// The file descriptor store of a service, through which the service hands over to its next
/// instance under a key of its own.
///
/// systemd keeps the store for the service across its restarts: what the service stores in it,
/// systemd passes the next instance as it starts it, along with the sockets of socket activation.
/// [`hand_over`](Self::hand_over) stores what the service hands over as it stops: its state, and
/// items, such as the connections of its clients, under ids of its own, each what [`Save`] saves,
/// a record of bytes and file descriptors. [`take_over`](Self::take_over) gives it back in the
/// next instance, under the same key, as a [`Restored`]. Several keys keep several hand-overs
/// apart, in one store.
///
/// A service needs three things, without which there is no `Store`, as
/// [`from_env`](Self::from_env) tells. It needs a socket unit, which has systemd keep the socket
/// that the service listens on, and the clients that connect meanwhile, while no instance runs, and
/// `Requires=` on it in the unit of the service, as systemd otherwise starts the service without
/// the socket where the socket unit isn't active. It needs `FileDescriptorStoreMax=` of 2 at least,
/// for systemd to keep a store. And it needs systemd 254 or later, which tells the service how many
/// file descriptors the store takes, in `$FDSTORE`.
///
/// # What the store holds
///
/// A hand-over takes a memfd, stored under `<key>/state`, that holds the record of the state and
/// those of the items, each of which the next instance reads in place, and one or more sockets,
/// stored under `<key>/fds`, whose queues hold the file descriptors of the state and of the items:
/// some 70000 in each, with the default size of its send buffer. The store takes each as one, so
/// the hand-over takes few of its file descriptors, and few names in `$LISTEN_FDNAMES`, which Linux
/// takes 128 KiB of at most, however many file descriptors it holds. The store keeps one file
/// descriptor of each open file description, while a queue keeps each as it is, so two of one file,
/// such as one that a client sent twice, go to the next instance as two.
///
/// # Limits
///
/// A hand-over is stored whole, or [`hand_over`](Self::hand_over) fails, and it is taken over
/// whole, or [`take_over`](Self::take_over) fails: nothing of it is left out. The next instance
/// takes the file descriptors out of the queues under its soft limit of open files, which
/// [`raise_fd_limit`](crate::raise_fd_limit) raises to the hard one, and fails to take over if
/// they don't fit under it. The store keeps a few file descriptors open from its creation on, which
/// it gives up for those that storing a hand-over opens, so that storing can't fail for want of
/// them, however many the service has open by then.
#[derive(Debug)]
pub struct Store {
    notifier: Notifier,
    key: String,
    /// How many file descriptors the store takes, `$FDSTORE`: [`MIN_STORE`] at least.
    max: usize,
    /// The file descriptors kept to give up for those that storing opens.
    reserve: Option<Reserve>,
}

impl Store {
    /// The store that systemd keeps for the service, under `key`.
    ///
    /// The service reaches it through the notification socket that `$NOTIFY_SOCKET` names, and it
    /// takes as many file descriptors as `$FDSTORE` tells. systemd sets both for a service whose
    /// unit has a `FileDescriptorStoreMax=` above 0, `$FDSTORE` from version 254 on.
    ///
    /// `passed` is what systemd passed the service, as [`Passed::from_env`] takes it. The store is
    /// only for a service that systemd passed a socket of socket activation, for the reason that
    /// [`take_over`](Self::take_over) gives. What was taken out of `passed` before doesn't matter:
    /// this goes by what `passed` was created with.
    ///
    /// The key is 1 to 200 printable ASCII characters other than `:` and `/`. For any other key,
    /// this fails with [`Error::InvalidName`].
    ///
    /// It fails with [`Error::NoManager`] if `$NOTIFY_SOCKET` is unset or empty. systemd then
    /// takes no notifications from the process, as when it doesn't run it at all, and keeps no
    /// store for it. A service that also runs without systemd goes on without a store then.
    ///
    /// It fails with [`Error::NoStore`] if `$FDSTORE` is unset or not a number. systemd then takes
    /// notifications from the service, as for a unit of `Type=notify`, but keeps no store for it,
    /// or is older than 254. It fails with [`Error::StoreTooSmall`] if `$FDSTORE` is less than 2,
    /// the fewest that a hand-over takes: the memfd and a queue socket.
    ///
    /// It fails with [`Error::NoSocket`] if systemd passed the service nothing but what is stored
    /// under the key, if that. A file descriptor under any other name counts as a socket, even one
    /// that is stored under another key, which this doesn't tell from a socket. The checks run in
    /// the order above, so a service that lacks both a store and a socket is told of the store
    /// first.
    ///
    /// `$NOTIFY_SOCKET` is the path of a socket if it starts with a `/`, and the name of an
    /// abstract socket, after the `@`, if it starts with one. A `/` or an `@` alone names nothing,
    /// and fails with [`Error::Environment`]. systemd also has `vsock:` addresses, which a virtual
    /// machine uses to tell its host that it has booted. zoter doesn't support them: they fail
    /// with [`Error::Environment`] too, like any other address that is neither a path nor an
    /// abstract name. A name too long for a socket address fails with [`Error::Io`] of
    /// `ENAMETOOLONG`.
    pub fn from_env(key: &str, passed: &Passed) -> Result<Self> {
        let notifier = Notifier::from_env()?.ok_or(Error::NoManager)?;
        let max = fd_store_max().ok_or(Error::NoStore)?;
        let store = Self::with_notifier(notifier, key, max)?;
        if !passed.had_other_than(&format!("{key}/")) {
            return Err(Error::NoSocket);
        }

        Ok(store)
    }

    /// Take over from the previous instance: take the file descriptors stored under the key out
    /// of `passed`, remove them from the store, and read the hand-over that they hold, if any.
    ///
    /// They are removed from the store first, whatever comes of it, so that a hand-over that this
    /// instance fails on, or crashes on, isn't found by the one after it. The file descriptors
    /// under the key that this version of zoter doesn't know of, as those that another version
    /// stored, close. What is left in `passed` is the sockets of socket activation, and what the
    /// service stored itself, if anything.
    ///
    /// It returns `None` if nothing was handed over. Otherwise it returns the whole hand-over: the
    /// state and every item, with all of their file descriptors.
    ///
    /// It fails with [`Error::Io`] of the system's error for too many open files (`EMFILE`) if the
    /// file descriptors don't fit under the process's soft limit of open files.
    /// [`raise_fd_limit`](crate::raise_fd_limit) raises that limit, up to the hard limit that the
    /// service's `LimitNOFILE=` sets. It fails with [`Error::InvalidHandover`] for a hand-over that
    /// this version of zoter can't make sense of. That includes file descriptors of the state or
    /// of an item that are missing for any reason other than that limit. It fails with
    /// [`Error::UnsupportedHandover`] for a hand-over that a later version of zoter laid out. On
    /// failure, the file descriptors of the hand-over are closed, which disconnects the peers of
    /// the items.
    ///
    /// Taking over also tells systemd that the service has started, which a unit of `Type=notify`
    /// waits for. It does so whatever comes of the take-over: with nothing handed over, or with a
    /// hand-over that fails to be taken over, the service starts afresh. So a service takes over
    /// each time it starts, and tells systemd nothing of its start itself. Its clients wait for
    /// it meanwhile in the sockets of socket activation, which systemd keeps, and in those that
    /// it takes over. That is why there is no `Store` without such a socket
    /// ([`Error::NoSocket`]). A failure to tell systemd only logs a warning.
    pub fn take_over(&mut self, passed: &mut Passed) -> Result<Option<Restored>> {
        let restored = self.take_handover(passed);
        // With the hand-over or without it, the service goes on from here, so it has started.
        if let Err(e) = self.notifier.notify("READY=1") {
            warn!("Failed to tell systemd that the service has started: {e}");
        }

        restored
    }

    /// Hand over to the next instance: store `state`, the state of the service, and `items`, in
    /// their order, each under its id, for the next instance, and wait for systemd to have dealt
    /// with them.
    ///
    /// The service does this once it stopped taking requests.
    ///
    /// The state of a service that has none is `&[][..]`. zoter doesn't look at the ids, nor
    /// checks that they are unique: it gives each back with its item, for the state to refer to
    /// the item by. The items are of any type, borrowed or owned, those of different types as
    /// `&dyn Save` or `Box<dyn Save>`.
    ///
    /// Either the whole hand-over is stored, or this fails: no part of it is left out. It fails
    /// with [`Error::Unsaved`] if the state or an item can't be saved, or if saving its record
    /// fails. The error names the id of the item, and nothing is stored. It fails with
    /// [`Error::StoreFull`] if the file descriptors don't fit in the store. The service's
    /// `FileDescriptorStoreMax=` makes the store hold more. It fails with [`Error::Io`] for any I/O
    /// error while storing the memfd or the file descriptors, or while queueing them for the
    /// store. It fails with [`Error::TimedOut`] if systemd takes longer than 5 s to process what
    /// was stored. A hand-over that fails after the memfd was stored may leave part of itself in
    /// the store. The next instance fails to take that part over, and removes it from the store
    /// like any other hand-over.
    pub fn hand_over<S, I, T>(self, state: S, items: I) -> Result<Stored>
    where
        S: Save,
        I: IntoIterator<Item = (u64, T)>,
        T: Save,
    {
        let items: Vec<_> = items.into_iter().collect();
        // The rest takes no generics, so that it is built once, whatever the types.
        let items: Vec<_> = items
            .iter()
            .map(|(id, item)| (*id, item as &dyn Save))
            .collect();

        self.store_all(&state, &items)
    }

    /// The store of the service that `notifier` reaches, under `key`, which takes `max` file
    /// descriptors. It fails as [`from_env`](Self::from_env) does for such a key and size.
    pub(crate) fn with_notifier(notifier: Notifier, key: &str, max: usize) -> Result<Self> {
        check_key(key)?;
        if max < MIN_STORE {
            return Err(Error::StoreTooSmall { max });
        }
        let reserve = Reserve::new()
            .inspect_err(|e| warn!("Failed to keep file descriptors to hand over with: {e}"))
            .ok();

        Ok(Self {
            notifier,
            key: key.to_owned(),
            max,
            reserve,
        })
    }

    /// What the previous instance handed over, out of `passed`, as
    /// [`take_over`](Self::take_over) tells.
    fn take_handover(&self, passed: &mut Passed) -> Result<Option<Restored>> {
        let prefix = format!("{}/", self.key);
        let stored = passed.take_prefixed(&prefix);
        // More than one file descriptor may come under a name, as the queue sockets do.
        let names: BTreeSet<_> = stored.iter().map(|(name, _)| name.as_str()).collect();
        for name in names {
            if let Err(e) = self.notifier.remove(name) {
                warn!("Failed to remove `{name}` from the file descriptor store: {e}");
            }
        }

        let mut state = None;
        let mut queues = Vec::new();
        for (name, fd) in stored {
            match &name[prefix.len()..] {
                STATE if state.is_none() => state = Some(fd),
                FDS => queues.push(fd),
                _ => {
                    warn!("Closing `{name}` of the file descriptor store, which zoter doesn't know")
                }
            }
        }
        let Some(state) = state else {
            if !queues.is_empty() {
                warn!("Closing the file descriptors that were stored without their hand-over");
            }

            return Ok(None);
        };
        let view = memfd::view(state.as_fd())?;
        let contents = layout::read(&view)?;

        let mut fds = take_queued(queues)?;
        let state_fds = take_fds(&mut fds, 0..contents.state_fds).ok_or_else(|| {
            Error::InvalidHandover(
                "file descriptors of the state of the hand-over are missing".to_owned(),
            )
        })?;
        let mut items = Vec::with_capacity(contents.entries.len());
        for Entry {
            id,
            record,
            fds: indexes,
        } in contents.entries
        {
            let Some(fds) = take_fds(&mut fds, indexes) else {
                return Err(Error::InvalidHandover(format!(
                    "file descriptors of item {id} of the hand-over are missing"
                )));
            };
            items.push(Slot { id, record, fds });
        }
        if !fds.is_empty() {
            warn!(
                "Closing {} file descriptors of the store that no item of the hand-over has",
                fds.len()
            );
        }

        Ok(Some(Restored {
            view,
            state: contents.state,
            state_fds,
            items,
        }))
    }

    /// Store `state` and `items`, as [`hand_over`](Self::hand_over) tells.
    fn store_all(mut self, state: &dyn Save, items: &[(u64, &dyn Save)]) -> Result<Stored> {
        // The store takes the memfd, and as many queue sockets as it has room for besides: one at
        // least, as `new` checked.
        let room = self.max - 1;
        // The file descriptors kept from the start are given up for those that storing opens, each
        // closed before the next opens: the memfd, the two ends of each pair whose one end is a
        // queue socket, and the two ends of the pipe of the barrier.
        self.reserve = None;

        let state_len = state.saved_len().ok_or(Error::Unsaved {
            item: None,
            source: None,
        })?;
        let lens = items
            .iter()
            .map(|(id, item)| {
                item.saved_len().ok_or(Error::Unsaved {
                    item: Some(*id),
                    source: None,
                })
            })
            .collect::<Result<Vec<_>>>()?;
        let state_fds = state.fds();
        let item_fds: Vec<_> = items.iter().map(|(_, item)| item.fds()).collect();

        let layout = Layout::new(state_len, lens.into_iter())?;
        {
            let name = self.name(STATE);
            let memfd = memfd::filled(&name, layout.len(), |memfd| -> Result<()> {
                state
                    .save(&mut memfd[layout.state()])
                    .map_err(|e| Error::Unsaved {
                        item: None,
                        source: Some(Box::new(e)),
                    })?;
                let mut entries = Vec::with_capacity(items.len());
                let mut next = state_fds.len() as u64;
                for (place, ((id, item), fds)) in items.iter().zip(&item_fds).enumerate() {
                    item.save(&mut memfd[layout.item(place)])
                        .map_err(|e| Error::Unsaved {
                            item: Some(*id),
                            source: Some(Box::new(e)),
                        })?;
                    let first = next;
                    next += fds.len() as u64;
                    entries.push(Entry {
                        id: *id,
                        record: layout.item(place),
                        fds: first..next,
                    });
                }
                layout.write(memfd, state_fds.len(), &entries);

                Ok(())
            })?;
            self.notifier.store(&name, &[memfd.as_fd()])?;
        }

        let fds: Vec<_> = state_fds
            .iter()
            .chain(item_fds.iter().flatten())
            .copied()
            .collect();
        let name = self.name(FDS);
        queue_fds(fds.chunks(MAX_FDS), room, |socket| {
            self.notifier.store(&name, &[socket.as_fd()])
        })?;

        // The service manager ties what it gets to the service by the process that sent it, which
        // goes next.
        self.notifier.barrier(BARRIER_TIMEOUT)?;
        debug!(
            "Stored {} items and {} file descriptors under `{}` for the next instance",
            items.len(),
            fds.len(),
            self.key
        );

        Ok(Stored {
            items: items.len(),
            fds: fds.len(),
        })
    }

    /// The name that the store keeps the file descriptors of the hand-over that `kind` tells
    /// under.
    fn name(&self, kind: &str) -> String {
        format!("{}/{kind}", self.key)
    }
}

/// What [`Store::hand_over`] stored: all of the hand-over.
#[derive(Debug)]
pub struct Stored {
    items: usize,
    fds: usize,
}

impl Stored {
    /// How many items were stored, whole.
    pub fn items(&self) -> usize {
        self.items
    }

    /// How many file descriptors were stored, those of the state included.
    pub fn fds(&self) -> usize {
        self.fds
    }
}

/// File descriptors that a store keeps from its creation on, to give up for those that storing a
/// hand-over opens: however many file descriptors the service has open by then, it has those to
/// spare.
#[derive(Debug)]
struct Reserve {
    /// For what storing opens, in turn, each closed before the next opens: the memfd, the two ends
    /// of each pair whose one end is a queue socket, and the two ends of the pipe of the barrier.
    _storing: [OwnedFd; 3],
}

impl Reserve {
    /// Three file descriptors to spare: the ends of a pipe, and a duplicate of one of them.
    fn new() -> io::Result<Self> {
        let (read, write) = pipe_with(PipeFlags::CLOEXEC)?;
        let duplicate = fcntl_dupfd_cloexec(&read, 0)?;

        Ok(Self {
            _storing: [read, write, duplicate],
        })
    }
}

/// Queue the file descriptors of `chunks`, in order, each chunk as one datagram, in queue sockets,
/// as many as that takes, `room` at most, and hand each one to `store`, once it took all that it
/// takes.
///
/// It fails with [`Error::StoreFull`] if `room` queue sockets can't hold all of them. If queueing
/// them fails, it fails with that error. The queue sockets that `store` received up to then stay
/// stored.
fn queue_fds<'c, 'f, C, S>(chunks: C, room: usize, mut store: S) -> Result<()>
where
    'f: 'c,
    C: IntoIterator<Item = &'c [BorrowedFd<'f>]>,
    S: FnMut(OwnedFd) -> Result<()>,
{
    let mut chunks = chunks.into_iter().peekable();
    let mut index = 0;
    for _ in 0..room {
        if chunks.peek().is_none() {
            return Ok(());
        }
        let queue = Queue::new()?;
        let mut took = false;
        while let Some(chunk) = chunks.peek() {
            let pushed = queue.push(index, chunk).map_err(|e| {
                io::Error::new(
                    e.kind(),
                    format!("the file descriptors of the hand-over failed to be queued: {e}"),
                )
            })?;
            if !pushed {
                // The next queue takes the rest.
                break;
            }
            index += chunk.len() as u64;
            took = true;
            chunks.next();
        }
        if !took {
            // Any other queue would take none either.
            return Err(io::Error::other(
                "a queue socket took none of the file descriptors of the hand-over",
            )
            .into());
        }
        store(queue.into_socket())?;
    }
    if chunks.peek().is_none() {
        return Ok(());
    }

    Err(Error::StoreFull)
}

/// The file descriptors out of the queue sockets that hold them, `queues`, as [`queue::take`]
/// takes them, by the index that each was queued as, whatever the order of the queue sockets.
///
/// It fails with the system's error of too many open files (`EMFILE`) if the kernel closed any of
/// them, as it does with those that the process can't have open. It warns of a queue socket that
/// fails to give them, whose file descriptors from there on close with it, and are missing then.
fn take_queued(queues: Vec<OwnedFd>) -> Result<HashMap<u64, OwnedFd>> {
    let mut fds = HashMap::new();
    let mut complete = true;
    for queue in queues {
        let taken = queue::take(queue.as_fd(), |index, taken, all| {
            for (n, fd) in (0..).zip(taken) {
                fds.insert(index.wrapping_add(n), fd);
            }
            complete &= all;
        });
        if let Err(e) = taken {
            warn!("Failed to take file descriptors of the hand-over out of the store: {e}");
        }
    }
    if !complete {
        warn!(
            "Failed to take file descriptors of the hand-over out of the store, as the process has \
             too many open: raise the hard limit of `LimitNOFILE=` of the service."
        );

        return Err(Error::os(Errno::MFILE));
    }

    Ok(fds)
}

/// Take the file descriptors at `indexes` out of `fds`, if they are all there.
///
/// Those that are there go either way, so that those of an item that lacks one close with it.
fn take_fds(fds: &mut HashMap<u64, OwnedFd>, indexes: Range<u64>) -> Option<Vec<OwnedFd>> {
    // More than there are can't all be there, and aren't looked for one by one.
    if indexes.end.saturating_sub(indexes.start) > fds.len() as u64 {
        // Those that are there go all the same.
        fds.retain(|index, _| !indexes.contains(index));

        return None;
    }
    let taken: Vec<_> = indexes.map(|index| fds.remove(&index)).collect();

    taken.into_iter().collect()
}

/// How many file descriptors the store of the service takes, `$FDSTORE`, if systemd tells.
///
/// systemd sets it to the `FileDescriptorStoreMax=` of the unit when that isn't 0, from version 254
/// on. It is `None` if the variable is unset or not a number.
fn fd_store_max() -> Option<usize> {
    env::var("FDSTORE").ok()?.parse().ok()
}

/// Check that `key` is one that the names of the store can start with: 1 to [`MAX_KEY_LEN`]
/// printable ASCII characters, other than `:`, which no name of the store has, and `/`, which
/// comes after the key in a name.
fn check_key(key: &str) -> Result<()> {
    let valid = |b: u8| (b' '..=b'~').contains(&b) && b != b':' && b != b'/';
    if key.is_empty() || key.len() > MAX_KEY_LEN || !key.bytes().all(valid) {
        return Err(Error::InvalidName(format!(
            "a key is 1 to {MAX_KEY_LEN} printable ASCII characters, other than `:` and `/`"
        )));
    }

    Ok(())
}

/// The fewest file descriptors that the store has to take for a hand-over: the memfd and a queue
/// socket.
pub(crate) const MIN_STORE: usize = 2;
/// How long a hand-over waits for the service manager to deal with what it stored.
const BARRIER_TIMEOUT: Duration = Duration::from_secs(5);
/// The longest key.
const MAX_KEY_LEN: usize = 200;
/// What the name of the memfd of a hand-over ends with, after the key and a `/`.
const STATE: &str = "state";
/// What the name of each queue socket of a hand-over ends with, after the key and a `/`.
const FDS: &str = "fds";

#[cfg(test)]
mod tests;