shipslip 0.14.0

Deploy Laravel apps over SSH with a preview, a deploy lock, and a receipt.
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
//! Runs deploy steps detached on the server, so a step survives a dropped
//! connection, a sleeping laptop, or a detach, and can be re-attached.
//!
//! Each step gets `~/.shipslip/runs/<run_id>/<key>/` holding `script.sh`,
//! `log` (stdout + stderr), `pid`, and `exit` (written atomically when the
//! step ends). A step is launched at most once: nothing here ever re-sends
//! the launch.

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use tokio::sync::{mpsc, oneshot};

use crate::receipt::now_ms;
use crate::script::shell_quote;
use crate::transport::{Transport, TransportError, LINE_QUEUE, SCRIPT_LINE_LIMIT, STEP_LINE_LIMIT};

/// Waits before each reconnect attempt after the connection drops.
const RECONNECT_DELAYS: [Duration; 4] = [
    Duration::from_secs(1),
    Duration::from_secs(2),
    Duration::from_secs(4),
    Duration::from_secs(8),
];

/// Upper bound on connection drops survived by a single step.
const MAX_REATTACHES: usize = 5;

/// Printed by the observer before the log, so anything a login shell prints
/// first is not taken for step output.
pub(crate) const LOG_START: &str = "shipslip-log-start";

/// Starts the line the observer prints on stderr while a step is silent, so
/// a lost connection's gap starts when the server was last heard.
pub(crate) const ALIVE: &str = "shipslip-alive-";

/// Seconds between the observer's alive lines; below ssh's 15 s keepalive.
const ALIVE_INTERVAL_SECS: u64 = 5;

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum StepResult {
    Exited(i32),
    /// The step was never started on the server.
    NotStarted(String),
    /// The step's process ended without recording an exit code.
    Gone,
    /// The server could not be reached again; the step may still be running.
    Interrupted(String),
}

#[derive(Debug, PartialEq, Eq)]
enum Probe {
    Exited(i32),
    Running,
    Gone,
    NotStarted,
}

pub(crate) enum ConnectionChange {
    Lost { at_ms: u128, detail: String },
    Reattached { at_ms: u128 },
}

pub(crate) enum Observed {
    Line(String),
    Drained(oneshot::Sender<()>),
}

pub(crate) struct Connection<'a> {
    reattaches: usize,
    lost: bool,
    heard_at_ms: u128,
    pub result_seen_at_ms: Option<u128>,
    notify: &'a (dyn Fn(ConnectionChange) -> Result<(), String> + Sync),
}

impl<'a> Connection<'a> {
    pub fn new(notify: &'a (dyn Fn(ConnectionChange) -> Result<(), String> + Sync)) -> Self {
        Self {
            reattaches: 0,
            lost: false,
            heard_at_ms: now_ms(),
            result_seen_at_ms: None,
            notify,
        }
    }

    fn heard(&mut self) {
        self.heard_at_ms = now_ms();
    }

    fn reattached(&mut self, probe: &Probe) -> Result<(), StepResult> {
        if self.lost {
            let at_ms = now_ms();
            if matches!(probe, Probe::Exited(_)) {
                self.result_seen_at_ms.get_or_insert(at_ms);
            }
            (self.notify)(ConnectionChange::Reattached { at_ms })
                .map_err(StepResult::Interrupted)?;
            self.lost = false;
        }
        Ok(())
    }
}

fn run_dir(run_id: &str) -> String {
    format!("\"$HOME\"/.shipslip/runs/{}", shell_quote(run_id))
}

/// Defines `ident PID`: the boot id and the process start time. A process ID
/// reused after a reboot, or by a later process, gives a different value.
const IDENT_FN: &str = r#"ident() { s=$(cat "/proc/$1/stat" 2>/dev/null) || return 0; s=${s##*) }; set -- $s; echo "$(cat /proc/sys/kernel/random/boot_id 2>/dev/null) ${20}"; }"#;

/// True unless `$d/ident` was recorded and `$d/pid` is now another process.
/// Runs launched before `ident` was recorded fall back to `kill -0`.
const SAME_PROCESS_FN: &str = r#"same_process() { [ ! -s "$d/ident" ] || [ "$(ident "$(cat "$d/pid")")" = "$(cat "$d/ident")" ]; }"#;

pub(crate) fn launch_script(run_id: &str, key: &str, script: &str) -> String {
    // Keep run records private without imposing that mask on app files created
    // by Composer, Artisan, or other recipe commands.
    format!(
        r#"set -e
recipe_umask=$(umask)
umask 077
mkdir -p {runs}
chmod 700 "$HOME"/.shipslip "$HOME"/.shipslip/runs
printf '%s' {script} > {runs}/{key}.sh
mkdir {runs}/{key}
d={runs}/{key}
mv "$d.sh" "$d/script.sh"
setsid nohup bash -c 'echo $$ > "$1/pid.tmp" && mv "$1/pid.tmp" "$1/pid"; (umask "$2"; bash -l -s < "$1/script.sh"); echo $? > "$1/exit.tmp"; mv "$1/exit.tmp" "$1/exit"' _ "$d" "$recipe_umask" > "$d/log" 2>&1 < /dev/null &
{ident}
for _ in $(seq 100); do
  if [ -s "$d/pid" ]; then
    ident "$(cat "$d/pid")" > "$d/ident.tmp" && mv "$d/ident.tmp" "$d/ident"
    exit 0
  fi
  sleep 0.05
done
exit 1
"#,
        runs = run_dir(run_id),
        script = shell_quote(script),
        ident = IDENT_FN,
    )
}

/// Streams the step's log from line `skip + 1` until the step's process ends,
/// printing `alive` on stderr meanwhile. If its process ID now belongs to
/// another process, prints the rest and stops.
pub(crate) fn observe_script(run_id: &str, key: &str, skip: usize, alive: &str) -> String {
    format!(
        r#"d={runs}/{key}
echo {LOG_START}
{ident}
{same_process}
same_process || exec tail -n +{from} "$d/log" 2>/dev/null
(while sleep {ALIVE_INTERVAL_SECS} </dev/null >/dev/null 2>&1; do echo {alive} >&2 || exit; done) </dev/null >/dev/null &
alive=$!
tail -n +{from} -s 0.2 --pid="$(cat "$d/pid")" -f "$d/log" 2>/dev/null
status=$?
kill "$alive" 2>/dev/null
exit "$status"
"#,
        runs = run_dir(run_id),
        from = skip + 1,
        ident = IDENT_FN,
        same_process = SAME_PROCESS_FN,
    )
}

/// An alive line no step output is expected to match.
fn alive_marker() -> String {
    static SEQ: AtomicU64 = AtomicU64::new(0);
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or_default();
    let seq = SEQ.fetch_add(1, Ordering::Relaxed);
    format!("{ALIVE}{nanos:x}-{:x}-{seq:x}", std::process::id())
}

pub(crate) fn probe_script(run_id: &str, key: &str) -> String {
    format!(
        r#"d={runs}/{key}
{ident}
{same_process}
state() {{
  if [ -e "$d/exit" ]; then echo "exited $(cat "$d/exit")"
  elif [ ! -d "$d" ]; then echo not-started
  elif [ -s "$d/pid" ] && kill -0 "$(cat "$d/pid")" 2>/dev/null && same_process; then echo running
  else return 1
  fi
}}
state || {{ sleep 1; state || echo gone; }}
"#,
        runs = run_dir(run_id),
        ident = IDENT_FN,
        same_process = SAME_PROCESS_FN,
    )
}

fn parse_probe(lines: &[String]) -> Option<Probe> {
    // Login shell startup files may print first; the answer is the last line.
    let last = lines.iter().rev().find(|l| !l.trim().is_empty())?.trim();
    match last {
        "running" => Some(Probe::Running),
        "gone" => Some(Probe::Gone),
        "not-started" => Some(Probe::NotStarted),
        _ => last
            .strip_prefix("exited ")?
            .parse()
            .ok()
            .map(Probe::Exited),
    }
}

/// Sends the step's launch once and settles whether it started. `Ok` means
/// the step is on the server (running or already ended); follow it with
/// [`follow_existing`]. Callers must not cancel this midway, or whether the
/// step started is unknown.
pub(crate) async fn launch_step<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    script: &str,
    connection: &mut Connection<'_>,
) -> Result<(), StepResult> {
    let (launch, launch_output) = run_collect(transport, &launch_script(run_id, key, script)).await;
    if launch.is_ok() {
        connection.heard();
    }
    if let Err(e @ TransportError::Connect(_)) = &launch {
        return Err(StepResult::NotStarted(e.to_string()));
    }
    if launch != Ok(0) {
        // Unclear whether the step started: ask the server. Never launch again.
        let mut last = launch.clone();
        loop {
            if let Err(reason) = reconnect_if_lost(transport, &last, connection, None).await {
                return Err(StepResult::Interrupted(reason));
            }
            let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
            if result.is_err() {
                last = result;
                continue;
            }
            let probe = parse_probe(&lines).ok_or_else(|| unexpected(&lines))?;
            connection.reattached(&probe)?;
            match probe {
                Probe::NotStarted => {
                    return Err(StepResult::NotStarted(match &launch {
                        Err(e) => e.to_string(),
                        Ok(code) => {
                            format!("launcher exited with {code}: {}", launch_output.join("\n"))
                        }
                    }))
                }
                _ => break,
            }
        }
    }
    Ok(())
}

/// Observes a previously launched step without sending its command again.
pub(crate) async fn attach_step<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    output: &mpsc::Sender<Observed>,
    connection: &mut Connection<'_>,
) -> StepResult {
    loop {
        let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
        if let Err(reason) = reconnect_if_lost(transport, &result, connection, Some(output)).await {
            return StepResult::Interrupted(reason);
        }
        if result.is_err() {
            continue;
        }
        let Some(probe) = parse_probe(&lines) else {
            return unexpected(&lines);
        };
        if let Err(result) = connection.reattached(&probe) {
            return result;
        }
        match probe {
            Probe::NotStarted => {
                return StepResult::NotStarted(
                    "the step was not launched before Shipslip exited".into(),
                )
            }
            Probe::Gone => return StepResult::Gone,
            Probe::Running | Probe::Exited(_) => break,
        }
    }
    follow_existing(transport, run_id, key, output, connection).await
}

pub(crate) async fn follow_existing<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    output: &mpsc::Sender<Observed>,
    connection: &mut Connection<'_>,
) -> StepResult {
    let mut seen = 0;
    loop {
        if connection.lost {
            let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
            if let Err(reason) =
                reconnect_if_lost(transport, &result, connection, Some(output)).await
            {
                return StepResult::Interrupted(reason);
            }
            if result.is_err() {
                continue;
            }
            let Some(probe) = parse_probe(&lines) else {
                return unexpected(&lines);
            };
            if let Err(result) = connection.reattached(&probe) {
                return result;
            }
        }
        let observed = observe(transport, run_id, key, &mut seen, output, connection).await;
        if let Err(reason) = reconnect_if_lost(transport, &observed, connection, Some(output)).await
        {
            return StepResult::Interrupted(reason);
        }
        if observed.is_err() {
            continue;
        }
        let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
        if let Err(reason) = reconnect_if_lost(transport, &result, connection, Some(output)).await {
            return StepResult::Interrupted(reason);
        }
        if result.is_err() {
            continue;
        }
        match parse_probe(&lines) {
            Some(Probe::Exited(code)) => return StepResult::Exited(code),
            Some(Probe::Gone) => return StepResult::Gone,
            // The observer returns only once the step's process has ended.
            Some(Probe::Running | Probe::NotStarted) => {
                connection.reattaches += 1;
                if connection.reattaches > MAX_REATTACHES {
                    return StepResult::Interrupted("could not follow the step's output".into());
                }
            }
            None => return unexpected(&lines),
        }
    }
}

fn unexpected(lines: &[String]) -> StepResult {
    StepResult::Interrupted(format!(
        "unexpected status from the server: {}",
        lines.join("\n")
    ))
}

/// Runs one of Shipslip's own scripts and returns all of its output, read
/// while the script runs. Their output is small or limited on the server.
pub(crate) async fn run_collect<T: Transport>(
    transport: &T,
    script: &str,
) -> (Result<i32, TransportError>, Vec<String>) {
    run_collect_each(transport, script, |_| {}).await
}

/// Like [`run_collect`], also showing each line to `each` as it arrives.
pub(crate) async fn run_collect_each<T: Transport>(
    transport: &T,
    script: &str,
    mut each: impl FnMut(&str),
) -> (Result<i32, TransportError>, Vec<String>) {
    let (tx, mut rx) = mpsc::channel::<String>(LINE_QUEUE);
    let collect = async {
        let mut lines = Vec::new();
        while let Some(line) = rx.recv().await {
            each(&line);
            lines.push(line);
        }
        lines
    };
    tokio::join!(transport.run(script, tx, SCRIPT_LINE_LIMIT), collect)
}

/// Forwards log lines after the first `seen` to `output`, counting them.
async fn observe<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    seen: &mut usize,
    output: &mpsc::Sender<Observed>,
    connection: &mut Connection<'_>,
) -> Result<i32, TransportError> {
    let alive = alive_marker();
    let script = observe_script(run_id, key, *seen, &alive);
    let (tx, mut rx) = mpsc::channel(LINE_QUEUE);
    let forward = async {
        let mut started = false;
        while let Some(line) = rx.recv().await {
            connection.heard();
            if line == alive {
                continue;
            }
            if !started {
                started = line == LOG_START;
                continue;
            }
            *seen += 1;
            let _ = output.send(Observed::Line(line)).await;
        }
    };
    let (result, ()) = tokio::join!(transport.run(&script, tx, STEP_LINE_LIMIT), forward);
    result
}

/// On a transport error, reconnects with backoff. `Ok` when there was no
/// error or the connection is back.
async fn reconnect_if_lost<T: Transport>(
    transport: &T,
    result: &Result<i32, TransportError>,
    connection: &mut Connection<'_>,
    output: Option<&mpsc::Sender<Observed>>,
) -> Result<(), String> {
    let Err(err) = result else {
        connection.heard();
        return Ok(());
    };
    if !connection.lost {
        let at_ms = connection.heard_at_ms;
        if let Some(output) = output {
            let (acknowledge, drained) = oneshot::channel();
            let _ = output.send(Observed::Drained(acknowledge)).await;
            let _ = drained.await;
        }
        (connection.notify)(ConnectionChange::Lost {
            at_ms,
            detail: err.to_string(),
        })?;
        connection.lost = true;
    }
    connection.reattaches += 1;
    if connection.reattaches > MAX_REATTACHES {
        return Err(err.to_string());
    }
    let mut last = err.to_string();
    for delay in RECONNECT_DELAYS {
        tokio::time::sleep(delay).await;
        match transport.reconnect().await {
            Ok(()) => return Ok(()),
            Err(e) => last = e.to_string(),
        }
    }
    Err(last)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn launch_refuses_to_start_a_step_twice() {
        let s = launch_script("r1", "step-2", "true");
        let guard = s
            .find("mkdir \"$HOME\"/.shipslip/runs/'r1'/step-2\n")
            .unwrap();
        assert!(guard < s.find("setsid").unwrap());
        assert!(s.starts_with("set -e\n"));
    }

    #[test]
    fn launch_embeds_the_script_quoted() {
        let s = launch_script("r1", "step-0", "echo 'hi' \"$HOME\"");
        assert!(s.contains(r#"printf '%s' 'echo '\''hi'\'' "$HOME"' >"#));
    }

    #[test]
    fn observe_resumes_after_seen_lines() {
        assert!(observe_script("r1", "step-1", 0, "x").contains("tail -n +1 "));
        assert!(observe_script("r1", "step-1", 7, "x").contains("tail -n +8 "));
    }

    #[test]
    fn probe_output_is_parsed_from_the_last_line() {
        let lines = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert_eq!(
            parse_probe(&lines(&["motd", "exited 3"])),
            Some(Probe::Exited(3))
        );
        assert_eq!(parse_probe(&lines(&["running", ""])), Some(Probe::Running));
        assert_eq!(parse_probe(&lines(&["gone"])), Some(Probe::Gone));
        assert_eq!(
            parse_probe(&lines(&["not-started"])),
            Some(Probe::NotStarted)
        );
        assert_eq!(parse_probe(&lines(&["exited x"])), None);
        assert_eq!(parse_probe(&[]), None);
    }

    /// Runs the real scripts with bash; they rely on Linux `/proc`.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_reused_process_id_is_not_the_running_step() {
        use std::process::Command;
        use std::time::{Duration, Instant};

        let home = std::env::temp_dir().join(format!("shipslip-runner-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&home);
        std::fs::create_dir_all(&home).unwrap();
        let run = |script: &str| {
            let output = Command::new("bash")
                .arg("-c")
                .arg(script)
                .env("HOME", &home)
                .output()
                .unwrap();
            String::from_utf8_lossy(&output.stdout)
                .lines()
                .map(String::from)
                .collect::<Vec<_>>()
        };
        let probe = || parse_probe(&run(&probe_script("r1", "step-1")));
        let dir = home.join(".shipslip/runs/r1/step-1");

        run(&launch_script("r1", "step-1", "echo hi; sleep 30"));
        let pid = std::fs::read_to_string(dir.join("pid")).unwrap();
        assert!(!std::fs::read_to_string(dir.join("ident"))
            .unwrap()
            .trim()
            .is_empty());
        assert_eq!(probe(), Some(Probe::Running));

        std::fs::write(dir.join("ident"), "another-boot 1\n").unwrap();
        assert_eq!(probe(), Some(Probe::Gone));
        let started = Instant::now();
        let observed = run(&observe_script("r1", "step-1", 0, &alive_marker()));
        assert!(started.elapsed() < Duration::from_secs(10));
        assert_eq!(observed.last().map(String::as_str), Some("hi"));

        // Runs launched before the identity was recorded.
        std::fs::remove_file(dir.join("ident")).unwrap();
        assert_eq!(probe(), Some(Probe::Running));

        let _ = Command::new("kill")
            .arg("--")
            .arg(format!("-{}", pid.trim()))
            .status();
        let _ = std::fs::remove_dir_all(&home);
    }
}