kunobi-daemon 0.10.1

Process ownership, request draining, and verified upgrades for local daemons
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
//! Lifecycle scenarios adapted from Kunobi broker/relay conformance and interop.
//! The daemon, relay and test controller are separate operating-system processes.

#![cfg(feature = "async")]

mod support;

use kunobi_daemon::{ProcessLock, ensure_current};
use std::{
    io,
    sync::{
        Arc,
        atomic::{AtomicUsize, Ordering},
    },
};
use support::{BUDGET, Fixture, connect, read_line, send, wait_file};
use tokio::time::Instant;

struct ExclusiveReplacement {
    fixture: Arc<Fixture>,
    draining: bool,
    candidate: Option<u32>,
    proof: Option<support::Identity>,
}
impl kunobi_daemon::replacement::AsyncDriver for ExclusiveReplacement {
    type Error = io::Error;
    async fn perform(
        &mut self,
        step: kunobi_daemon::replacement::Step,
        _: Option<Instant>,
    ) -> io::Result<kunobi_daemon::replacement::Progress> {
        use kunobi_daemon::replacement::{Progress, Step};
        match step {
            Step::Recheck | Step::Prepare | Step::Commit => {}
            Step::Drain => {
                if !self.draining {
                    self.fixture.request_drain().await?;
                    self.draining = true;
                }
                if ProcessLock::is_held(self.fixture.root().join("run.lock"))? {
                    return Ok(Progress::Pending);
                }
            }
            Step::Start => {
                assert!(self.candidate.is_none(), "candidate spawned twice");
                self.candidate = Some(self.fixture.spawn("daemon", 2));
            }
            Step::Verify | Step::Validate => {
                if let Some((id, _)) = connect(self.fixture.root()).await?
                    && Some(id.pid) == self.candidate
                    && id.build == 2
                {
                    self.proof = Some(id);
                } else if step == Step::Verify {
                    return Ok(Progress::Pending);
                } else {
                    return Err(io::Error::other("candidate lost readiness"));
                }
            }
            Step::Retire => unreachable!("exclusive mode"),
        }
        Ok(Progress::Done)
    }
}

#[tokio::test]
async fn exclusive_coordinator_drains_the_reply_before_starting_and_the_same_relay_reconnects() {
    use kunobi_daemon::replacement::{self, Budgets, Mode, Outcome};
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (relay, mut client) = fixture.relay().await;
    send(&mut client, "CALL 1 hold").await.unwrap();
    wait_file(&fixture.root().join("accepted-ready-1")).await;
    let owner = Arc::clone(&fixture);
    let upgrade = tokio::spawn(async move {
        let lock = ProcessLock::try_acquire(owner.root().join("upgrade.lock"))
            .unwrap()
            .unwrap();
        let mut driver = ExclusiveReplacement {
            fixture: owner,
            draining: false,
            candidate: None,
            proof: None,
        };
        let result = replacement::run_async(
            &lock,
            Mode::Exclusive,
            Budgets {
                setup: BUDGET,
                drain: None,
            },
            &mut driver,
        )
        .await
        .unwrap();
        assert_eq!(result, Outcome::Complete);
        driver.proof.unwrap()
    });
    wait_file(&fixture.root().join(format!("draining-{}", old.pid))).await;
    assert!(!upgrade.is_finished());
    assert!(fixture.alive(old.pid));
    std::fs::write(fixture.root().join("release-1"), b"").unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 1 {} 1", old.pid)
    );
    let new = upgrade.await.unwrap();
    fixture.exited_cleanly(old.pid).await;
    wait_file(
        &fixture
            .root()
            .join(format!("relay-{relay}-connected-{}", new.pid)),
    )
    .await;
    send(&mut client, "CALL 2 ok").await.unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 2 {} 2", new.pid)
    );
    assert!(fixture.alive(relay));
}

#[test]
#[ignore = "child-process entry point, invoked by the E2E fixtures"]
fn fixture_process() {
    support::child_main();
}

#[tokio::test]
async fn client_eof_preserves_the_late_reply_and_closes_the_same_relay_cleanly() {
    use tokio::io::AsyncWriteExt;
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (relay_pid, mut client) = fixture.relay().await;
    send(&mut client, "CALL 30 hold").await.unwrap();
    wait_file(&fixture.root().join("accepted-ready-30")).await;
    client.get_mut().shutdown().await.unwrap();
    std::fs::write(fixture.root().join("release-30"), b"").unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 30 {} 1", old.pid)
    );
    fixture.exited_cleanly(relay_pid).await;
    assert!(fixture.alive(old.pid));
}

#[tokio::test]
async fn drain_finishes_the_old_reply_then_the_same_relay_reaches_the_new_daemon() {
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (relay_pid, mut client) = fixture.relay().await;
    send(&mut client, "CALL 1 hold").await.unwrap();
    wait_file(&fixture.root().join("accepted-ready-1")).await;

    let upgrade = {
        let fixture = Arc::clone(&fixture);
        tokio::spawn(async move {
            ensure_current(
                &fixture.root().join("upgrade.lock"),
                Instant::now() + BUDGET,
                || async { Ok::<_, io::Error>(connect(fixture.root()).await?.map(|(id, _)| id)) },
                |id| id.build == 2,
                || async {
                    fixture.request_drain().await?;
                    let pid = fixture.spawn("daemon", 2);
                    kunobi_daemon::publish_record(
                        &fixture.root().join("candidate.pid"),
                        pid.to_string().as_bytes(),
                    )?;
                    Ok(())
                },
            )
            .await
            .unwrap()
        })
    };
    wait_file(&fixture.root().join(format!("draining-{}", old.pid))).await;
    wait_file(&fixture.root().join("candidate.pid")).await;
    let candidate: u32 = std::fs::read_to_string(fixture.root().join("candidate.pid"))
        .unwrap()
        .parse()
        .unwrap();
    wait_file(&fixture.root().join(format!("attempted-lock-{candidate}"))).await;
    assert!(fixture.alive(old.pid), "old daemon exited before its reply");
    assert!(
        !upgrade.is_finished(),
        "replacement declared ready while the old owner held the lock"
    );
    assert!(
        ProcessLock::try_acquire(fixture.root().join("run.lock"))
            .unwrap()
            .is_none()
    );

    std::fs::write(fixture.root().join("release-1"), b"").unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 1 {} 1", old.pid)
    );
    let new = upgrade.await.unwrap();
    assert_eq!(new.pid, candidate);
    assert_ne!(new.pid, old.pid);
    fixture.exited_cleanly(old.pid).await;
    wait_file(
        &fixture
            .root()
            .join(format!("relay-{relay_pid}-connected-{}", new.pid)),
    )
    .await;
    send(&mut client, "CALL 2 ok").await.unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 2 {} 2", new.pid)
    );
    assert!(
        fixture.alive(relay_pid),
        "client session required a new relay process"
    );
}

#[tokio::test]
async fn a_crash_reports_the_pending_id_once_without_replaying_it_on_the_replacement() {
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (relay_pid, mut client) = fixture.relay().await;
    send(&mut client, "CALL 10 hold").await.unwrap();
    wait_file(&fixture.root().join("accepted-ready-10")).await;
    fixture.kill(old.pid);
    assert!(
        fixture.root().join("daemon.addr").exists(),
        "crash must leave stale discovery"
    );
    assert_eq!(read_line(&mut client).await.unwrap(), "UNCERTAIN 10");
    let new = ensure_current(
        &fixture.root().join("upgrade.lock"),
        Instant::now() + BUDGET,
        || async { Ok::<_, io::Error>(connect(fixture.root()).await?.map(|(id, _)| id)) },
        |id| id.build == 2,
        || async {
            fixture.spawn("daemon", 2);
            Ok(())
        },
    )
    .await
    .unwrap();
    wait_file(
        &fixture
            .root()
            .join(format!("relay-{relay_pid}-connected-{}", new.pid)),
    )
    .await;
    send(&mut client, "CALL 11 ok").await.unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 11 {} 2", new.pid)
    );
    assert_eq!(
        std::fs::read_to_string(fixture.root().join("accepted-10")).unwrap(),
        format!("{}\n", old.pid)
    );
    assert!(fixture.alive(relay_pid));
}

#[tokio::test]
async fn a_compatible_live_daemon_keeps_its_process_and_client_session() {
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (relay_pid, mut client) = fixture.relay().await;
    let accepted = ensure_current(
        &fixture.root().join("upgrade.lock"),
        Instant::now() + BUDGET,
        || async { Ok::<_, io::Error>(connect(fixture.root()).await?.map(|(id, _)| id)) },
        |id| id.build >= 1,
        || async { panic!("compatible build must not be replaced") },
    )
    .await
    .unwrap();
    assert_eq!(accepted, old);
    send(&mut client, "CALL 20 ok").await.unwrap();
    assert_eq!(
        read_line(&mut client).await.unwrap(),
        format!("OK 20 {} 1", old.pid)
    );
    assert!(fixture.alive(relay_pid));
    assert!(
        !fixture
            .root()
            .join(format!("draining-{}", old.pid))
            .exists()
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn concurrent_clients_create_one_replacement_process() {
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let barrier = Arc::new(tokio::sync::Barrier::new(8));
    let replacements = Arc::new(AtomicUsize::new(0));
    let mut tasks = Vec::new();
    for _ in 0..8 {
        let fixture = Arc::clone(&fixture);
        let barrier = Arc::clone(&barrier);
        let replacements = Arc::clone(&replacements);
        tasks.push(tokio::spawn(async move {
            let mut first = true;
            ensure_current(
                &fixture.root().join("upgrade.lock"),
                Instant::now() + BUDGET,
                || {
                    let first = std::mem::replace(&mut first, false);
                    let fixture = Arc::clone(&fixture);
                    let barrier = Arc::clone(&barrier);
                    async move {
                        let observed = connect(fixture.root()).await?.map(|(id, _)| id);
                        if first {
                            barrier.wait().await;
                        }
                        Ok::<_, io::Error>(observed)
                    }
                },
                |id| id.build == 2,
                || async {
                    replacements.fetch_add(1, Ordering::SeqCst);
                    fixture.request_drain().await?;
                    fixture.spawn("daemon", 2);
                    Ok(())
                },
            )
            .await
            .unwrap()
        }));
    }
    let mut ids = Vec::new();
    for task in tasks {
        ids.push(task.await.unwrap());
    }
    assert!(
        ids.iter()
            .all(|id| id == &ids[0] && id.pid != old.pid && id.build == 2)
    );
    assert_eq!(replacements.load(Ordering::SeqCst), 1);
    fixture.exited_cleanly(old.pid).await;
}

#[cfg(feature = "wire-async")]
#[tokio::test]
async fn legacy_and_binary_endpoints_share_admission_and_preserve_both_inflight_replies() {
    use kunobi_daemon::wire::{AsyncSession, Control, Hello, capability};
    let fixture = Fixture::new();
    let old = fixture.start(1).await;
    let (_relay_pid, mut legacy) = fixture.relay().await;
    wait_file(&fixture.root().join("daemon.v2.addr")).await;
    let address = std::fs::read_to_string(fixture.root().join("daemon.v2.addr")).unwrap();
    assert_ne!(
        address,
        std::fs::read_to_string(fixture.root().join("daemon.addr")).unwrap()
    );
    let socket = tokio::net::TcpStream::connect(address).await.unwrap();
    socket.set_nodelay(true).unwrap();
    let mut binary = AsyncSession::connect(
        socket,
        &Hello::new(
            &kunobi_daemon::ServiceIdentity::new([1; 16], "fixture", "stable", "default").unwrap(),
            capability::APPLICATION,
            capability::APPLICATION,
        ),
    )
    .await
    .unwrap();
    send(&mut legacy, "CALL 80 hold").await.unwrap();
    binary
        .send(&Control {
            kind: kunobi_daemon::wire::MessageKind::Application.into(),
            operation: 1,
            request_id: 81,
            payload: b"hold".to_vec(),
            ..Default::default()
        })
        .await
        .unwrap();
    wait_file(&fixture.root().join("accepted-ready-80")).await;
    wait_file(&fixture.root().join("accepted-ready-81")).await;
    fixture.request_drain().await.unwrap();
    assert!(fixture.alive(old.pid));
    std::fs::write(fixture.root().join("release-80"), b"").unwrap();
    assert_eq!(
        read_line(&mut legacy).await.unwrap(),
        format!("OK 80 {} 1", old.pid)
    );
    assert!(
        fixture.alive(old.pid),
        "binary request was omitted from the common drain count"
    );
    std::fs::write(fixture.root().join("release-81"), b"").unwrap();
    let reply = tokio::time::timeout(BUDGET, binary.receive())
        .await
        .unwrap()
        .unwrap();
    assert_eq!(reply.request_id, 81);
    assert_eq!(reply.payload, format!("OK 81 {} 1", old.pid).as_bytes());
    fixture.exited_cleanly(old.pid).await;
    assert!(!fixture.root().join("daemon.addr").exists());
    assert!(!fixture.root().join("daemon.v2.addr").exists());
}