[linux] Tests: unpacking hostile archives, the atomic switch, health check and auto rollback (red: the code follows)
This commit is contained in:
@@ -0,0 +1,254 @@
|
||||
// This Source Code Form is subject to the terms of the Mozilla Public
|
||||
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! The Linux target (mandatory, tests first): the atomic symlink switch, the restart, the health
|
||||
//! check, and auto rollback when the check fails. Real files and symlinks; systemd and the health
|
||||
//! endpoint are fakes here (the container test, tests/linux, uses real systemd).
|
||||
|
||||
#![cfg(any(target_os = "linux", target_os = "android"))]
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use common::*;
|
||||
use legatus_linux::{Health, Layout, LinuxBackend, Outcome, Plan, Services};
|
||||
|
||||
/// systemd as the tests see it: records restarts; a release is "active" unless its dir holds BROKEN.
|
||||
struct FakeSystemd {
|
||||
layout: Layout,
|
||||
calls: RefCell<Vec<String>>,
|
||||
fail_restart_of: Option<String>,
|
||||
}
|
||||
|
||||
impl Services for FakeSystemd {
|
||||
fn restart(&self, unit: &str) -> Result<(), String> {
|
||||
let v = self.layout.current("shop").unwrap_or_default();
|
||||
self.calls.borrow_mut().push(format!("restart {unit} @{v}"));
|
||||
if self.fail_restart_of.as_deref() == Some(v.as_str()) {
|
||||
return Err(format!("Job for {unit} failed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn is_active(&self, _unit: &str) -> bool {
|
||||
let cur = self.layout.current_dir("shop");
|
||||
cur.is_some_and(|d| !d.join("BROKEN").exists())
|
||||
}
|
||||
}
|
||||
|
||||
/// The health URL answers 2xx unless the current release holds UNHEALTHY.
|
||||
struct FakeHealth(Layout);
|
||||
impl Health for FakeHealth {
|
||||
fn check(&self, _url: &str) -> bool {
|
||||
self.0
|
||||
.current_dir("shop")
|
||||
.is_some_and(|d| !d.join("UNHEALTHY").exists())
|
||||
}
|
||||
}
|
||||
|
||||
fn backend(
|
||||
fail_restart_of: Option<&str>,
|
||||
) -> (tempfile::TempDir, LinuxBackend<FakeSystemd, FakeHealth>) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let layout = Layout::new(dir.path().join("apps"));
|
||||
let sd = FakeSystemd {
|
||||
layout: layout.clone(),
|
||||
calls: RefCell::new(Vec::new()),
|
||||
fail_restart_of: fail_restart_of.map(str::to_owned),
|
||||
};
|
||||
let b = LinuxBackend::new(layout.clone(), sd, FakeHealth(layout))
|
||||
.with_poll(Duration::from_millis(5));
|
||||
(dir, b)
|
||||
}
|
||||
|
||||
fn plan(version: &str) -> Plan<'_> {
|
||||
Plan {
|
||||
app: "shop",
|
||||
version,
|
||||
unit: "shop.service",
|
||||
health_url: Some("http://127.0.0.1:8080/health"),
|
||||
health_timeout: Duration::from_millis(200),
|
||||
keep: 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn good(v: &str) -> Vec<u8> {
|
||||
targz(&[("bin/shop", format!("version {v}").as_bytes(), true)])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_healthy_release_is_switched_to_and_restarted() {
|
||||
let (_d, b) = backend(None);
|
||||
let out = b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
assert_eq!(out, Outcome::Succeeded { previous: None });
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
let out = b.deploy(&plan("1.1.0"), &good("2")[..], "s2").unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::Succeeded {
|
||||
previous: Some("1.0.0".into())
|
||||
}
|
||||
);
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.1.0"));
|
||||
assert_eq!(
|
||||
*b.services().calls.borrow(),
|
||||
vec![
|
||||
"restart shop.service @1.0.0".to_owned(),
|
||||
"restart shop.service @1.1.0".to_owned()
|
||||
]
|
||||
);
|
||||
// `current` is a relative symlink into releases/.
|
||||
let link = std::fs::read_link(b.layout().current_link("shop")).unwrap();
|
||||
assert_eq!(link, PathBuf::from("releases/1.1.0"));
|
||||
assert_eq!(b.deployed(), vec![("shop".to_owned(), "1.1.0".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_health_check_rolls_back_automatically() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
Outcome::RolledBack {
|
||||
to: "1.0.0".into(),
|
||||
healthy: true,
|
||||
reason: out.reason().to_owned()
|
||||
}
|
||||
);
|
||||
assert!(out.reason().contains("health"), "{}", out.reason());
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
// Restarted on the new release, then again on the old one.
|
||||
assert_eq!(
|
||||
*b.services().calls.borrow(),
|
||||
vec![
|
||||
"restart shop.service @1.0.0".to_owned(),
|
||||
"restart shop.service @2.0.0".to_owned(),
|
||||
"restart shop.service @1.0.0".to_owned()
|
||||
]
|
||||
);
|
||||
// The failed release stays on disk for a look, but is not current.
|
||||
assert!(b.layout().release_dir("shop", "2.0.0").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inactive_unit_rolls_back_even_without_a_health_url() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let crashes = targz(&[("bin/shop", b"v2", true), ("BROKEN", b"", false)]);
|
||||
let mut p = plan("2.0.0");
|
||||
p.health_url = None;
|
||||
let out = b.deploy(&p, &crashes[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { ref to, healthy: true, .. } if to == "1.0.0"),
|
||||
"{out:?}"
|
||||
);
|
||||
assert_eq!(b.layout().current("shop").as_deref(), Some("1.0.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_restart_rolls_back() {
|
||||
let (_d, b) = backend(Some("2.0.0"));
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
let out = b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { ref to, .. } if to == "1.0.0"),
|
||||
"{out:?}"
|
||||
);
|
||||
assert!(out.reason().contains("failed"), "{}", out.reason());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_first_release_that_fails_has_nothing_to_roll_back_to() {
|
||||
let (_d, b) = backend(None);
|
||||
let bad = targz(&[("bin/shop", b"v1", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("1.0.0"), &bad[..], "s1").unwrap();
|
||||
assert!(matches!(out, Outcome::Failed { .. }), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rollback_that_is_unhealthy_too_says_so() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
// The old release breaks meanwhile (say, a database it needs is gone).
|
||||
std::fs::write(
|
||||
b.layout().release_dir("shop", "1.0.0").join("UNHEALTHY"),
|
||||
b"",
|
||||
)
|
||||
.unwrap();
|
||||
let bad = targz(&[("bin/shop", b"v2", true), ("UNHEALTHY", b"", false)]);
|
||||
let out = b.deploy(&plan("2.0.0"), &bad[..], "s2").unwrap();
|
||||
assert!(
|
||||
matches!(out, Outcome::RolledBack { healthy: false, .. }),
|
||||
"{out:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_switch_is_atomic() {
|
||||
let (_d, b) = backend(None);
|
||||
b.deploy(&plan("1.0.0"), &good("1")[..], "s1").unwrap();
|
||||
b.deploy(&plan("2.0.0"), &good("2")[..], "s2").unwrap();
|
||||
let link = b.layout().current_link("shop");
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let reader = {
|
||||
let (link, stop) = (link.clone(), stop.clone());
|
||||
std::thread::spawn(move || {
|
||||
let mut reads = 0u64;
|
||||
while !stop.load(Ordering::Relaxed) {
|
||||
// `current` always exists and always points at a whole release.
|
||||
let target = std::fs::read_link(&link).expect("current vanished during a switch");
|
||||
let s = target.to_string_lossy().into_owned();
|
||||
assert!(s == "releases/1.0.0" || s == "releases/2.0.0", "{s}");
|
||||
assert!(link.join("bin/shop").exists(), "current pointed at nothing");
|
||||
reads += 1;
|
||||
}
|
||||
reads
|
||||
})
|
||||
};
|
||||
for i in 0..400 {
|
||||
let v = if i % 2 == 0 { "1.0.0" } else { "2.0.0" };
|
||||
b.switch("shop", v).unwrap();
|
||||
}
|
||||
stop.store(true, Ordering::Relaxed);
|
||||
let reads = reader.join().unwrap();
|
||||
assert!(reads > 0);
|
||||
// No temporary links are left behind.
|
||||
let names: Vec<String> = std::fs::read_dir(b.layout().app_dir("shop"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
names.iter().filter(|n| n.starts_with('.')).count(),
|
||||
0,
|
||||
"{names:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_releases_are_pruned_but_current_and_previous_kept() {
|
||||
let (_d, b) = backend(None);
|
||||
for (i, v) in ["1.0.0", "1.1.0", "1.2.0", "1.3.0", "1.4.0"]
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut p = plan(v);
|
||||
p.keep = 2;
|
||||
b.deploy(&p, &good(&i.to_string())[..], &format!("s{i}"))
|
||||
.unwrap();
|
||||
}
|
||||
let mut left: Vec<String> = std::fs::read_dir(b.layout().releases_dir("shop"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| !n.ends_with(".sha256"))
|
||||
.collect();
|
||||
left.sort();
|
||||
assert_eq!(left, vec!["1.3.0".to_owned(), "1.4.0".to_owned()]);
|
||||
}
|
||||
Reference in New Issue
Block a user