shipslip 0.6.2

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
//! 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::time::Duration;

use tokio::sync::mpsc;

use crate::script::shell_quote;
use crate::transport::{Transport, TransportError};

/// 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";

#[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,
}

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.
/// 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) -> String {
    format!(
        r#"d={runs}/{key}
echo {LOG_START}
{ident}
{same_process}
same_process || exec tail -n +{from} "$d/log" 2>/dev/null
exec tail -n +{from} -s 0.2 --pid="$(cat "$d/pid")" -f "$d/log" 2>/dev/null
"#,
        runs = run_dir(run_id),
        from = skip + 1,
        ident = IDENT_FN,
        same_process = SAME_PROCESS_FN,
    )
}

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),
    }
}

/// Launches `script` detached as `key` (e.g. `step-2`) of `run_id` and
/// follows it to the end, re-attaching after dropped connections. Output
/// lines go to `output`.
pub(crate) async fn run_step<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    script: &str,
    output: &mpsc::UnboundedSender<String>,
) -> StepResult {
    let mut reattaches = 0;
    if let Err(result) = launch_step(transport, run_id, key, script, &mut reattaches).await {
        return result;
    }
    follow_existing(transport, run_id, key, output, &mut reattaches).await
}

/// 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,
    reattaches: &mut usize,
) -> Result<(), StepResult> {
    let (launch, launch_output) = run_collect(transport, &launch_script(run_id, key, script)).await;
    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, reattaches).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;
            }
            match parse_probe(&lines) {
                Some(Probe::NotStarted) => {
                    return Err(StepResult::NotStarted(match &launch {
                        Err(e) => e.to_string(),
                        Ok(code) => {
                            format!("launcher exited with {code}: {}", launch_output.join("\n"))
                        }
                    }))
                }
                Some(_) => break,
                None => return Err(unexpected(&lines)),
            }
        }
    }
    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::UnboundedSender<String>,
) -> StepResult {
    let mut reattaches = 0;
    loop {
        let (result, lines) = run_collect(transport, &probe_script(run_id, key)).await;
        if let Err(reason) = reconnect_if_lost(transport, &result, &mut reattaches).await {
            return StepResult::Interrupted(reason);
        }
        if result.is_err() {
            continue;
        }
        match parse_probe(&lines) {
            Some(Probe::NotStarted) => {
                return StepResult::NotStarted(
                    "the step was not launched before Shipslip exited".into(),
                )
            }
            Some(Probe::Gone) => return StepResult::Gone,
            Some(Probe::Running | Probe::Exited(_)) => break,
            None => return unexpected(&lines),
        }
    }
    follow_existing(transport, run_id, key, output, &mut reattaches).await
}

pub(crate) async fn follow_existing<T: Transport>(
    transport: &T,
    run_id: &str,
    key: &str,
    output: &mpsc::UnboundedSender<String>,
    reattaches: &mut usize,
) -> StepResult {
    // After a reconnect, observe again before probing so output written
    // while disconnected is still shown.
    let mut seen = 0;
    loop {
        let observed = observe(transport, run_id, key, &mut seen, output).await;
        if let Err(reason) = reconnect_if_lost(transport, &observed, reattaches).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, reattaches).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) => {
                *reattaches += 1;
                if *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")
    ))
}

pub(crate) async fn run_collect<T: Transport>(
    transport: &T,
    script: &str,
) -> (Result<i32, TransportError>, Vec<String>) {
    let (tx, mut rx) = mpsc::unbounded_channel();
    let result = transport.run(script, tx).await;
    let mut lines = Vec::new();
    while let Some(line) = rx.recv().await {
        lines.push(line);
    }
    (result, lines)
}

/// 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::UnboundedSender<String>,
) -> Result<i32, TransportError> {
    let script = observe_script(run_id, key, *seen);
    let (tx, mut rx) = mpsc::unbounded_channel();
    let forward = async {
        let mut started = false;
        while let Some(line) = rx.recv().await {
            if !started {
                started = line == LOG_START;
                continue;
            }
            *seen += 1;
            let _ = output.send(line);
        }
    };
    let (result, ()) = tokio::join!(transport.run(&script, tx), 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>,
    reattaches: &mut usize,
) -> Result<(), String> {
    let Err(err) = result else {
        return Ok(());
    };
    *reattaches += 1;
    if *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).contains("tail -n +1 "));
        assert!(observe_script("r1", "step-1", 7).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));
        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);
    }
}