diff --git a/crates/piqueld-docker/src/engine.rs b/crates/piqueld-docker/src/engine/mod.rs similarity index 65% rename from crates/piqueld-docker/src/engine.rs rename to crates/piqueld-docker/src/engine/mod.rs index cc15f5b5e..560b891dc 100644 --- a/crates/piqueld-docker/src/engine.rs +++ b/crates/piqueld-docker/src/engine/mod.rs @@ -633,323 +633,4 @@ impl BollardDocker { } #[cfg(test)] -mod tests { - use super::{BollardDocker, StatusCode, WireError}; - - struct EngineStub { - docker: BollardDocker, - task: tokio::task::JoinHandle<()>, - _directory: tempfile::TempDir, - } - - /// A client of the engine socket in a new directory, and the listener - /// behind it. - fn listen() -> (tempfile::TempDir, tokio::net::UnixListener, BollardDocker) { - let directory = tempfile::tempdir().unwrap(); - let socket = directory.path().join("docker.sock"); - let listener = tokio::net::UnixListener::bind(&socket).unwrap(); - let docker = BollardDocker::connect(&socket).unwrap(); - (directory, listener, docker) - } - - impl EngineStub { - /// Serves one raw 200 response whose declared length may disagree with the body. - fn respond(body: &'static str, declared_length: usize) -> Self { - Self::serve(vec![( - None, - format!( - "HTTP/1.1 200 OK\r\nContent-Length: {declared_length}\r\nConnection: close\r\n\r\n{body}" - ), - )]) - } - - /// Serves JSON responses in order, asserting each request line. - fn sequence(responses: Vec<(String, u16, serde_json::Value)>) -> Self { - Self::serve( - responses - .into_iter() - .map(|(request, status, body)| { - let body = body.to_string(); - ( - Some(request), - format!( - "HTTP/1.1 {status} fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ), - ) - }) - .collect(), - ) - } - - /// Answers one connection per exchange with its raw response, checking - /// the request line when one is expected. - fn serve(exchanges: Vec<(Option, String)>) -> Self { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let (directory, listener, docker) = listen(); - let task = tokio::spawn(async move { - for (expected, response) in exchanges { - let (mut stream, _) = listener.accept().await.unwrap(); - let mut headers = Vec::new(); - while !headers.ends_with(b"\r\n\r\n") { - headers.push(stream.read_u8().await.unwrap()); - } - let headers = String::from_utf8(headers).unwrap(); - if let Some(expected) = expected { - assert_eq!( - headers.lines().next().unwrap(), - format!("{expected} HTTP/1.1") - ); - } - let length: usize = headers - .lines() - .find_map(|line| { - let (key, value) = line.split_once(':')?; - key.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse().unwrap()) - }) - .unwrap_or_default(); - stream.read_exact(&mut vec![0; length]).await.unwrap(); - stream.write_all(response.as_bytes()).await.unwrap(); - stream.shutdown().await.unwrap(); - } - }); - Self { - docker, - task, - _directory: directory, - } - } - } - - #[tokio::test] - async fn service_update_retry_uses_id_and_rechecks_ownership() { - use piqueld_core::resource::{ - APPLICATION_LABEL, INSTANCE_LABEL, MANAGED_LABEL, SERVICE_LABEL, SPEC_HASH_LABEL, - }; - let app = piqueld_core::EnvironmentId::parse("app-update-race").unwrap(); - let name = piqueld_core::docker_resource_name( - &app, - piqueld_core::ResourceKind::Service, - Some("web"), - ); - let spec = bollard::models::ServiceSpec { - name: Some(name.clone()), - labels: Some(std::collections::HashMap::from([ - (MANAGED_LABEL.into(), "true".into()), - (INSTANCE_LABEL.into(), "test-instance".into()), - (APPLICATION_LABEL.into(), app.to_string()), - (SERVICE_LABEL.into(), "web".into()), - (SPEC_HASH_LABEL.into(), format!("sha256:{}", "a".repeat(64))), - ])), - ..Default::default() - }; - for changed in ["none", "owner", "id", "name", "removed"] { - let mut refreshed = - serde_json::json!({"ID":"immutable-id", "Version":{"Index":42}, "Spec":spec}); - match changed { - "owner" => refreshed["Spec"]["Labels"][INSTANCE_LABEL] = "another-instance".into(), - "id" => refreshed["ID"] = "replacement-id".into(), - "name" => refreshed["Spec"]["Name"] = "renamed-service".into(), - _ => {} - } - let mut responses = vec![ - ( - "POST /services/immutable-id/update?version=1®istryAuthFrom=spec".into(), - 500, - serde_json::json!({"message":"rpc error: code = Unknown desc = update out of sequence"}), - ), - ( - "GET /services/immutable-id".into(), - if changed == "removed" { 404 } else { 200 }, - refreshed, - ), - ]; - if changed == "none" { - responses.push(( - "POST /services/immutable-id/update?version=42®istryAuthFrom=spec".into(), - 200, - serde_json::json!({}), - )); - } - let stub = EngineStub::sequence(responses); - let result = stub - .docker - .update_service_wire("immutable-id", 1, &spec) - .await; - if changed == "none" { - result.unwrap(); - } else { - assert!( - matches!(result, Err(super::DockerError::OwnershipConflict)), - "{changed}: {result:?}" - ); - } - stub.task.await.unwrap(); - } - } - - #[tokio::test] - async fn cancelling_service_request_closes_connection_driver() { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let (_directory, listener, docker) = listen(); - let request = tokio::spawn(async move { docker.inspect_service_wire("test").await }); - let (mut stream, _) = listener.accept().await.unwrap(); - let mut headers = Vec::new(); - while !headers.ends_with(b"\r\n\r\n") { - headers.push(stream.read_u8().await.unwrap()); - } - // Leave the body pending so the driver still owns an open connection. - stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n{") - .await - .unwrap(); - tokio::task::yield_now().await; - request.abort(); - assert!(request.await.unwrap_err().is_cancelled()); - let mut byte = [0]; - let read = - tokio::time::timeout(std::time::Duration::from_secs(1), stream.read(&mut byte)).await; - assert_eq!(read.expect("cancelled connection must close").unwrap(), 0); - } - - #[tokio::test] - async fn missing_engine_retains_io_cause_and_public_classification() { - use std::error::Error; - let (directory, listener, docker) = listen(); - drop(listener); - std::fs::remove_file(directory.path().join("docker.sock")).unwrap(); - let error = docker.inspect_service_wire("test").await.unwrap_err(); - let source = error - .source() - .unwrap() - .downcast_ref::() - .unwrap(); - assert_eq!(source.kind(), std::io::ErrorKind::NotFound); - assert!( - matches!(error, super::DockerError::UnavailableSource { .. }), - "{error:?}" - ); - } - - /// A malformed or truncated response fails the request with its decode - /// or transport cause. - #[tokio::test] - async fn bad_service_responses_retain_their_cause() { - use std::error::Error; - for (body, declared_length, decoding) in [("not JSON", 8, true), ("{", 20, false)] { - let engine = EngineStub::respond(body, declared_length); - let error = engine - .docker - .inspect_service_wire("test") - .await - .unwrap_err(); - engine.task.await.unwrap(); - let source = error.source().unwrap(); - if decoding { - assert!(source.is::(), "{error:?}"); - assert_eq!( - error.to_string(), - "Docker request failed while decode service response" - ); - } else { - assert!(source.is::(), "{error:?}"); - } - assert!( - matches!(error, super::DockerError::RequestSource { .. }), - "{error:?}" - ); - } - } - - /// A secret that another request created, then removed before the - /// recheck, fails the request: Docker answered, so it is no outage. - #[tokio::test] - async fn a_secret_removed_during_creation_is_a_request_failure() { - let response = |status: u16| { - let body = r#"{"message":"fixture"}"#; - ( - None, - format!( - "HTTP/1.1 {status} fixture\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ), - ) - }; - let stub = EngineStub::serve(vec![response(404), response(409), response(404)]); - let error = stub - .docker - .provision_secret("secret", b"value", &std::collections::BTreeMap::new()) - .await - .unwrap_err(); - stub.task.await.unwrap(); - assert!( - matches!( - error, - super::DockerError::Request(_) | super::DockerError::RequestSource { .. } - ), - "{error:?}" - ); - } - - /// Both of Docker's answers to a start over a taken host port are - /// recognized; other failures are not. - #[test] - fn a_taken_host_port_is_recognized_in_either_wording() { - let response = |message: &str| WireError::Response { - path: "/containers/gateway/start".into(), - status: StatusCode::INTERNAL_SERVER_ERROR, - body: serde_json::json!({ "message": message }) - .to_string() - .into_bytes(), - }; - assert!(response("driver failed programming external connectivity on endpoint gateway: Bind for 0.0.0.0:80 failed: port is already allocated").port_in_use()); - assert!(response("failed to listen on TCP socket: listen tcp4 0.0.0.0:443: bind: address already in use").port_in_use()); - assert!(!response("container gateway is not running").port_in_use()); - assert!(!WireError::Public(super::DockerError::Request("start container")).port_in_use()); - } - - #[test] - fn update_retry_requires_the_exact_transient_daemon_response() { - let transient = WireError::Response { - path: "/services/web/update".into(), - status: StatusCode::INTERNAL_SERVER_ERROR, - body: br#"{"message":"rpc error: code = Unknown desc = update out of sequence"}"# - .to_vec(), - }; - let different_message = WireError::Response { - path: "/services/web/update".into(), - status: StatusCode::INTERNAL_SERVER_ERROR, - body: - br#"{"message":"rpc error: code = Unknown desc = update out of sequence: other"}"# - .to_vec(), - }; - let different_status = WireError::Response { - path: "/services/web/update".into(), - status: StatusCode::CONFLICT, - body: br#"{"message":"rpc error: code = Unknown desc = update out of sequence"}"# - .to_vec(), - }; - - assert!(BollardDocker::update_out_of_sequence(&transient)); - assert!(!BollardDocker::update_out_of_sequence(&different_message)); - assert!(!BollardDocker::update_out_of_sequence(&different_status)); - } - - #[test] - fn healthcheck_key_is_translated_at_the_docker_wire_boundary() { - let mut value = serde_json::json!({ - "TaskTemplate": {"ContainerSpec": {"HealthCheck": {"Test": ["CMD", "true"]}}} - }); - BollardDocker::rename_swarm_healthcheck(&mut value, "HealthCheck", "Healthcheck"); - let container = &value["TaskTemplate"]["ContainerSpec"]; - assert!(container.get("HealthCheck").is_none()); - assert!(container.get("Healthcheck").is_some()); - - let mut response = serde_json::json!({"Spec": value}); - BollardDocker::rename_swarm_healthcheck(&mut response, "Healthcheck", "HealthCheck"); - let container = &response["Spec"]["TaskTemplate"]["ContainerSpec"]; - assert!(container.get("HealthCheck").is_some()); - assert!(container.get("Healthcheck").is_none()); - } -} +mod tests; diff --git a/crates/piqueld-docker/src/engine/tests.rs b/crates/piqueld-docker/src/engine/tests.rs new file mode 100644 index 000000000..fd1078456 --- /dev/null +++ b/crates/piqueld-docker/src/engine/tests.rs @@ -0,0 +1,317 @@ +use super::{BollardDocker, StatusCode, WireError}; + +struct EngineStub { + docker: BollardDocker, + task: tokio::task::JoinHandle<()>, + _directory: tempfile::TempDir, +} + +/// A client of the engine socket in a new directory, and the listener +/// behind it. +fn listen() -> (tempfile::TempDir, tokio::net::UnixListener, BollardDocker) { + let directory = tempfile::tempdir().unwrap(); + let socket = directory.path().join("docker.sock"); + let listener = tokio::net::UnixListener::bind(&socket).unwrap(); + let docker = BollardDocker::connect(&socket).unwrap(); + (directory, listener, docker) +} + +impl EngineStub { + /// Serves one raw 200 response whose declared length may disagree with the body. + fn respond(body: &'static str, declared_length: usize) -> Self { + Self::serve(vec![( + None, + format!( + "HTTP/1.1 200 OK\r\nContent-Length: {declared_length}\r\nConnection: close\r\n\r\n{body}" + ), + )]) + } + + /// Serves JSON responses in order, asserting each request line. + fn sequence(responses: Vec<(String, u16, serde_json::Value)>) -> Self { + Self::serve( + responses + .into_iter() + .map(|(request, status, body)| { + let body = body.to_string(); + ( + Some(request), + format!( + "HTTP/1.1 {status} fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ), + ) + }) + .collect(), + ) + } + + /// Answers one connection per exchange with its raw response, checking + /// the request line when one is expected. + fn serve(exchanges: Vec<(Option, String)>) -> Self { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (directory, listener, docker) = listen(); + let task = tokio::spawn(async move { + for (expected, response) in exchanges { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(stream.read_u8().await.unwrap()); + } + let headers = String::from_utf8(headers).unwrap(); + if let Some(expected) = expected { + assert_eq!( + headers.lines().next().unwrap(), + format!("{expected} HTTP/1.1") + ); + } + let length: usize = headers + .lines() + .find_map(|line| { + let (key, value) = line.split_once(':')?; + key.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }) + .unwrap_or_default(); + stream.read_exact(&mut vec![0; length]).await.unwrap(); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.shutdown().await.unwrap(); + } + }); + Self { + docker, + task, + _directory: directory, + } + } +} + +#[tokio::test] +async fn service_update_retry_uses_id_and_rechecks_ownership() { + use piqueld_core::resource::{ + APPLICATION_LABEL, INSTANCE_LABEL, MANAGED_LABEL, SERVICE_LABEL, SPEC_HASH_LABEL, + }; + let app = piqueld_core::EnvironmentId::parse("app-update-race").unwrap(); + let name = + piqueld_core::docker_resource_name(&app, piqueld_core::ResourceKind::Service, Some("web")); + let spec = bollard::models::ServiceSpec { + name: Some(name.clone()), + labels: Some(std::collections::HashMap::from([ + (MANAGED_LABEL.into(), "true".into()), + (INSTANCE_LABEL.into(), "test-instance".into()), + (APPLICATION_LABEL.into(), app.to_string()), + (SERVICE_LABEL.into(), "web".into()), + (SPEC_HASH_LABEL.into(), format!("sha256:{}", "a".repeat(64))), + ])), + ..Default::default() + }; + for changed in ["none", "owner", "id", "name", "removed"] { + let mut refreshed = + serde_json::json!({"ID":"immutable-id", "Version":{"Index":42}, "Spec":spec}); + match changed { + "owner" => refreshed["Spec"]["Labels"][INSTANCE_LABEL] = "another-instance".into(), + "id" => refreshed["ID"] = "replacement-id".into(), + "name" => refreshed["Spec"]["Name"] = "renamed-service".into(), + _ => {} + } + let mut responses = vec![ + ( + "POST /services/immutable-id/update?version=1®istryAuthFrom=spec".into(), + 500, + serde_json::json!({"message":"rpc error: code = Unknown desc = update out of sequence"}), + ), + ( + "GET /services/immutable-id".into(), + if changed == "removed" { 404 } else { 200 }, + refreshed, + ), + ]; + if changed == "none" { + responses.push(( + "POST /services/immutable-id/update?version=42®istryAuthFrom=spec".into(), + 200, + serde_json::json!({}), + )); + } + let stub = EngineStub::sequence(responses); + let result = stub + .docker + .update_service_wire("immutable-id", 1, &spec) + .await; + if changed == "none" { + result.unwrap(); + } else { + assert!( + matches!(result, Err(super::DockerError::OwnershipConflict)), + "{changed}: {result:?}" + ); + } + stub.task.await.unwrap(); + } +} + +#[tokio::test] +async fn cancelling_service_request_closes_connection_driver() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let (_directory, listener, docker) = listen(); + let request = tokio::spawn(async move { docker.inspect_service_wire("test").await }); + let (mut stream, _) = listener.accept().await.unwrap(); + let mut headers = Vec::new(); + while !headers.ends_with(b"\r\n\r\n") { + headers.push(stream.read_u8().await.unwrap()); + } + // Leave the body pending so the driver still owns an open connection. + stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n{") + .await + .unwrap(); + tokio::task::yield_now().await; + request.abort(); + assert!(request.await.unwrap_err().is_cancelled()); + let mut byte = [0]; + let read = + tokio::time::timeout(std::time::Duration::from_secs(1), stream.read(&mut byte)).await; + assert_eq!(read.expect("cancelled connection must close").unwrap(), 0); +} + +#[tokio::test] +async fn missing_engine_retains_io_cause_and_public_classification() { + use std::error::Error; + let (directory, listener, docker) = listen(); + drop(listener); + std::fs::remove_file(directory.path().join("docker.sock")).unwrap(); + let error = docker.inspect_service_wire("test").await.unwrap_err(); + let source = error + .source() + .unwrap() + .downcast_ref::() + .unwrap(); + assert_eq!(source.kind(), std::io::ErrorKind::NotFound); + assert!( + matches!(error, super::DockerError::UnavailableSource { .. }), + "{error:?}" + ); +} + +/// A malformed or truncated response fails the request with its decode +/// or transport cause. +#[tokio::test] +async fn bad_service_responses_retain_their_cause() { + use std::error::Error; + for (body, declared_length, decoding) in [("not JSON", 8, true), ("{", 20, false)] { + let engine = EngineStub::respond(body, declared_length); + let error = engine + .docker + .inspect_service_wire("test") + .await + .unwrap_err(); + engine.task.await.unwrap(); + let source = error.source().unwrap(); + if decoding { + assert!(source.is::(), "{error:?}"); + assert_eq!( + error.to_string(), + "Docker request failed while decode service response" + ); + } else { + assert!(source.is::(), "{error:?}"); + } + assert!( + matches!(error, super::DockerError::RequestSource { .. }), + "{error:?}" + ); + } +} + +/// A secret that another request created, then removed before the +/// recheck, fails the request: Docker answered, so it is no outage. +#[tokio::test] +async fn a_secret_removed_during_creation_is_a_request_failure() { + let response = |status: u16| { + let body = r#"{"message":"fixture"}"#; + ( + None, + format!( + "HTTP/1.1 {status} fixture\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ), + ) + }; + let stub = EngineStub::serve(vec![response(404), response(409), response(404)]); + let error = stub + .docker + .provision_secret("secret", b"value", &std::collections::BTreeMap::new()) + .await + .unwrap_err(); + stub.task.await.unwrap(); + assert!( + matches!( + error, + super::DockerError::Request(_) | super::DockerError::RequestSource { .. } + ), + "{error:?}" + ); +} + +/// Both of Docker's answers to a start over a taken host port are +/// recognized; other failures are not. +#[test] +fn a_taken_host_port_is_recognized_in_either_wording() { + let response = |message: &str| WireError::Response { + path: "/containers/gateway/start".into(), + status: StatusCode::INTERNAL_SERVER_ERROR, + body: serde_json::json!({ "message": message }) + .to_string() + .into_bytes(), + }; + assert!(response("driver failed programming external connectivity on endpoint gateway: Bind for 0.0.0.0:80 failed: port is already allocated").port_in_use()); + assert!( + response( + "failed to listen on TCP socket: listen tcp4 0.0.0.0:443: bind: address already in use" + ) + .port_in_use() + ); + assert!(!response("container gateway is not running").port_in_use()); + assert!(!WireError::Public(super::DockerError::Request("start container")).port_in_use()); +} + +#[test] +fn update_retry_requires_the_exact_transient_daemon_response() { + let transient = WireError::Response { + path: "/services/web/update".into(), + status: StatusCode::INTERNAL_SERVER_ERROR, + body: br#"{"message":"rpc error: code = Unknown desc = update out of sequence"}"#.to_vec(), + }; + let different_message = WireError::Response { + path: "/services/web/update".into(), + status: StatusCode::INTERNAL_SERVER_ERROR, + body: br#"{"message":"rpc error: code = Unknown desc = update out of sequence: other"}"# + .to_vec(), + }; + let different_status = WireError::Response { + path: "/services/web/update".into(), + status: StatusCode::CONFLICT, + body: br#"{"message":"rpc error: code = Unknown desc = update out of sequence"}"#.to_vec(), + }; + + assert!(BollardDocker::update_out_of_sequence(&transient)); + assert!(!BollardDocker::update_out_of_sequence(&different_message)); + assert!(!BollardDocker::update_out_of_sequence(&different_status)); +} + +#[test] +fn healthcheck_key_is_translated_at_the_docker_wire_boundary() { + let mut value = serde_json::json!({ + "TaskTemplate": {"ContainerSpec": {"HealthCheck": {"Test": ["CMD", "true"]}}} + }); + BollardDocker::rename_swarm_healthcheck(&mut value, "HealthCheck", "Healthcheck"); + let container = &value["TaskTemplate"]["ContainerSpec"]; + assert!(container.get("HealthCheck").is_none()); + assert!(container.get("Healthcheck").is_some()); + + let mut response = serde_json::json!({"Spec": value}); + BollardDocker::rename_swarm_healthcheck(&mut response, "Healthcheck", "HealthCheck"); + let container = &response["Spec"]["TaskTemplate"]["ContainerSpec"]; + assert!(container.get("HealthCheck").is_some()); + assert!(container.get("Healthcheck").is_none()); +} diff --git a/crates/piqueld-docker/src/policy.rs b/crates/piqueld-docker/src/policy/mod.rs similarity index 52% rename from crates/piqueld-docker/src/policy.rs rename to crates/piqueld-docker/src/policy/mod.rs index 01833a120..5a7144455 100644 --- a/crates/piqueld-docker/src/policy.rs +++ b/crates/piqueld-docker/src/policy/mod.rs @@ -327,350 +327,4 @@ impl ServiceRuntimePolicy { } #[cfg(test)] -mod tests { - use super::super::HealthCheck; - use super::*; - use bollard::models::{ServiceSpecRollbackConfig, ServiceSpecUpdateConfigOrderEnum}; - use piqueld_core::manifest::{ - RolloutOrder, ValidatedResourceLimits as ResourceLimits, ValidatedRollout as Rollout, - }; - use piqueld_core::resource::{DesiredMount, DesiredService, ResolvedSource}; - use std::collections::BTreeMap; - - /// Specification authored for a service attached to its private network. - fn authored() -> ServiceSpec { - BollardDocker::service_spec(&desired(Vec::new()), "local-node") - .expect("authored specification") - } - - /// Desired service attached to its private network and mounting `mounts`. - fn desired(mounts: Vec) -> DesiredService { - let image = format!("ghcr.io/example/notes@sha256:{}", "a".repeat(64)); - let application = piqueld_core::EnvironmentId::parse("app-policy").unwrap(); - DesiredService { - link_aliases: BTreeMap::new(), - secrets: Vec::new(), - files: Vec::new(), - logical_name: piqueld_core::ServiceName::parse("web").unwrap(), - name: piqueld_core::DockerServiceName::parse("app-policy-web").unwrap(), - source: ResolvedSource::Image { - requested: piqueld_core::ImageReference::parse("ghcr.io/example/notes:1.4.0") - .unwrap(), - digest_reference: piqueld_core::RepositoryDigest::parse(image.clone()).unwrap(), - }, - image: piqueld_core::ImmutableImage::parse(image).unwrap(), - replicas: 2, - environment: BTreeMap::from([("NOTES_PORT".into(), "8080".into())]), - command: vec!["/bin/notes".into()], - arguments: vec!["--listen".into(), "8080".into()], - mounts, - healthcheck: None, - resources: Some(ResourceLimits { - cpu_millis: Some(250), - memory_bytes: Some(1024), - }), - networks: vec![piqueld_core::DockerNetworkName::for_application( - &application, - )], - labels: piqueld_core::Ownership { - instance_id: piqueld_core::InstanceId::parse("instance").unwrap(), - environment_id: application, - service: Some(piqueld_core::ServiceName::parse("web").unwrap()), - spec_hash: format!("sha256:{}", "b".repeat(64)), - } - .labels(), - depends_on: Vec::new(), - rollout: Rollout::default(), - receives_telemetry: false, - telemetry: None, - } - } - - #[test] - fn authored_rollout_is_observed_back() { - let mount = |read_only| DesiredMount { - volume_name: piqueld_core::DockerVolumeName::parse("app-policy-data").unwrap(), - target: "/data".into(), - read_only, - }; - let observed = |desired: &DesiredService| { - let spec = BollardDocker::service_spec(desired, "local-node").unwrap(); - assert!(ServiceRuntimePolicy::matches(&spec, "local-node")); - BollardDocker::observed_rollout(&spec) - }; - - let read_only = desired(vec![mount(true)]); - assert_eq!(observed(&read_only), Some(read_only.rollout_policy())); - let mut writable = desired(vec![mount(true), mount(false)]); - assert_eq!( - observed(&writable).map(|rollout| rollout.order), - Some(RolloutOrder::StopFirst) - ); - writable.rollout = Rollout { - order: Some(RolloutOrder::StartFirst), - monitor_seconds: Some(5), - }; - assert_eq!(observed(&writable), Some(writable.rollout_policy())); - - // Values piqueld never authors are not mistaken for a rollout policy. - let mut spec = BollardDocker::service_spec(&writable, "local-node").unwrap(); - let update = spec.update_config.as_mut().unwrap(); - update.monitor = Some(1_500_000_000); - assert_eq!(BollardDocker::observed_rollout(&spec), None); - let update = spec.update_config.as_mut().unwrap(); - update.monitor = Some(5_000_000_000); - update.order = Some(ServiceSpecUpdateConfigOrderEnum::EMPTY); - assert_eq!(BollardDocker::observed_rollout(&spec), None); - } - - /// Swarm would expand `{{` as a Go template, so it is escaped when - /// authored and read back as written. - #[test] - fn template_text_is_authored_literally_and_observed_back() { - let text = r#"${{ vars.x }} {{.Service.Name}} {{{ {{"{{"}}"#; - let mut desired = desired(vec![DesiredMount { - volume_name: piqueld_core::DockerVolumeName::parse("app-policy-data").unwrap(), - target: "/data/{{.Task.Slot}}".into(), - read_only: false, - }]); - desired.environment.insert("TEXT".into(), text.into()); - let spec = BollardDocker::service_spec(&desired, "local-node").unwrap(); - let container = spec.task_template.as_ref().unwrap().container_spec.as_ref(); - assert!(container.unwrap().env.as_ref().unwrap().contains( - &r#"TEXT=${{"{{"}} vars.x }} {{"{{"}}.Service.Name}} {{"{{"}}{ {{"{{"}}"{{"{{"}}"}}"#.into() - )); - let observed = BollardDocker::observe_service(&spec, "local-node", Vec::new(), None) - .expect("observed service"); - assert_eq!(observed.environment, desired.environment); - assert_eq!(observed.mounts[0].target, "/data/{{.Task.Slot}}"); - assert!(observed.matches(&desired)); - - // Specs written before escaping are drift, so reconciling rewrites them. - let unescaped = |edit: fn(&mut TaskSpecContainerSpec)| { - let mut spec = spec.clone(); - edit( - spec.task_template - .as_mut() - .unwrap() - .container_spec - .as_mut() - .unwrap(), - ); - BollardDocker::observe_service(&spec, "local-node", Vec::new(), None) - .expect("observed service") - .drift(&desired) - }; - assert_eq!( - unescaped(|container| container.env = Some(vec!["TEXT={{.Service.Name}}".into()])), - ["environment", "runtime_policy"] - ); - assert_eq!( - unescaped(|container| { - container.mounts.as_mut().unwrap()[0].target = Some("/data/{{.Task.Slot}}".into()); - }), - ["runtime_policy"] - ); - } - - #[test] - fn logical_name_is_the_only_accepted_alias() { - let mut spec = authored(); - assert!(ServiceRuntimePolicy::matches(&spec, "local-node")); - let network = &mut spec - .task_template - .as_mut() - .unwrap() - .networks - .as_mut() - .unwrap()[0]; - assert_eq!(network.aliases, Some(vec!["web".into()])); - network.aliases.as_mut().unwrap().push("other".into()); - assert!(!ServiceRuntimePolicy::matches(&spec, "local-node")); - } - - /// Including a start period and retries other than Docker's defaults. - #[test] - fn generated_http_health_check_round_trips_through_observation() { - let health_check = HealthCheck::Http { - port: 8080, - path: "/health".into(), - interval_seconds: 10, - timeout_seconds: 3, - start_period_seconds: 30, - retries: 5, - }; - let config = BollardDocker::health_config(&health_check); - - assert_eq!(BollardDocker::observed_health(&config), Some(health_check)); - assert!(ServiceRuntimePolicy::supported_health_config(&config)); - } - - /// The probe vector piqueld authors for `Http { port: 8080, path: "/health", .. }`. - fn probe_vector(arguments: &[&str]) -> Vec { - std::iter::once(piqueld_probe::CONTAINER_PATH) - .chain(arguments.iter().copied()) - .map(String::from) - .collect() - } - - #[test] - fn command_health_check_accepts_equivalent_http_vector() { - let health_check = HealthCheck::Command { - command: probe_vector(&[ - "http", - "--port", - "8080", - "--path", - "/health", - "--timeout", - "3", - ]), - interval_seconds: 10, - timeout_seconds: 3, - start_period_seconds: 0, - retries: 3, - }; - - let config = BollardDocker::health_config(&health_check); - let observed = BollardDocker::observed_health(&config).unwrap(); - assert!(matches!(observed, HealthCheck::Http { port: 8080, .. })); - assert_eq!(observed.execution(), health_check.execution()); - assert!(ServiceRuntimePolicy::supported_health_config(&config)); - } - - /// Near matches, including the `wget` vector earlier daemons authored for - /// HTTP checks, stay commands; HTTP services deployed before the probe - /// therefore drift and roll onto it. - #[test] - fn near_http_command_health_checks_round_trip_as_commands() { - for command in [ - probe_vector(&[ - "http", - "--path", - "/health", - "--port", - "8080", - "--timeout", - "3", - ]), - probe_vector(&[ - "http", - "--port", - "8080", - "--path", - "/health", - "--timeout", - "5", - ]), - [ - "wget", - "-q", - "-T", - "3", - "-O", - "/dev/null", - "http://127.0.0.1:8080/health", - ] - .map(String::from) - .into(), - ] { - let health_check = HealthCheck::Command { - command, - interval_seconds: 10, - timeout_seconds: 3, - start_period_seconds: 0, - retries: 3, - }; - - let config = BollardDocker::health_config(&health_check); - assert_eq!( - BollardDocker::observed_health(&config).as_ref(), - Some(&health_check) - ); - assert!(ServiceRuntimePolicy::supported_health_config(&config)); - } - } - - #[test] - fn policy_verifies_exactly_the_authored_fields() { - let authored = authored(); - assert!(ServiceRuntimePolicy::matches(&authored, "local-node")); - // Services are pinned to the local node. - assert!(!ServiceRuntimePolicy::matches(&authored, "another-node")); - let mut unpinned = authored.clone(); - unpinned.task_template.as_mut().unwrap().placement = None; - assert!(!ServiceRuntimePolicy::matches(&unpinned, "local-node")); - - // Known Engine defaults are accepted, while unsupported non-default - // behavior remains visible as drift. - let mut echoed = authored.clone(); - let task = echoed.task_template.as_mut().expect("task"); - task.resources.as_mut().expect("resources").reservations = - Some(bollard::models::ResourceObject::default()); - task.runtime = Some("container".into()); - task.force_update = Some(0); - task.placement.as_mut().expect("placement").max_replicas = Some(0); - task.restart_policy.as_mut().expect("restart").max_attempts = Some(0); - task.container_spec.as_mut().expect("container").dns_config = - Some(bollard::models::TaskSpecContainerSpecDnsConfig::default()); - echoed.rollback_config = Some(ServiceSpecRollbackConfig { - parallelism: Some(1), - failure_action: Some( - bollard::models::ServiceSpecRollbackConfigFailureActionEnum::PAUSE, - ), - monitor: Some(5 * super::super::NANOSECONDS_PER_SECOND), - max_failure_ratio: Some(0.0), - order: Some(bollard::models::ServiceSpecRollbackConfigOrderEnum::STOP_FIRST), - ..Default::default() - }); - assert!(ServiceRuntimePolicy::matches(&echoed, "local-node")); - - echoed.rollback_config = Some(ServiceSpecRollbackConfig::default()); - if let Some(container) = echoed - .task_template - .as_mut() - .and_then(|task| task.container_spec.as_mut()) - { - container.stop_grace_period = Some(12_345); - container.hostname = Some("echoed".into()); - } - assert!(!ServiceRuntimePolicy::matches(&echoed, "local-node")); - - // A non-default runtime is out-of-band modification. - let mut runtime = authored.clone(); - runtime.task_template.as_mut().unwrap().runtime = Some("custom-runtime".into()); - assert!(!ServiceRuntimePolicy::matches(&runtime, "local-node")); - - // Drift in a field piqueld authors is still rejected. - let mut drifted = authored.clone(); - if let Some(update) = drifted.update_config.as_mut() { - update.parallelism = Some(4); - } - assert!(!ServiceRuntimePolicy::matches(&drifted, "local-node")); - - // Out-of-band security settings are rejected even though piqueld - // cannot author them. - let mut injected_capability = authored.clone(); - if let Some(container) = injected_capability - .task_template - .as_mut() - .and_then(|task| task.container_spec.as_mut()) - { - container.capability_add = Some(vec!["NET_ADMIN".into()]); - } - assert!(!ServiceRuntimePolicy::matches( - &injected_capability, - "local-node" - )); - - let mut injected_user = authored; - if let Some(container) = injected_user - .task_template - .as_mut() - .and_then(|task| task.container_spec.as_mut()) - { - container.user = Some("0".into()); - } - assert!(!ServiceRuntimePolicy::matches(&injected_user, "local-node")); - } -} +mod tests; diff --git a/crates/piqueld-docker/src/policy/tests.rs b/crates/piqueld-docker/src/policy/tests.rs new file mode 100644 index 000000000..44a3bacea --- /dev/null +++ b/crates/piqueld-docker/src/policy/tests.rs @@ -0,0 +1,344 @@ +use super::super::HealthCheck; +use super::*; +use bollard::models::{ServiceSpecRollbackConfig, ServiceSpecUpdateConfigOrderEnum}; +use piqueld_core::manifest::{ + RolloutOrder, ValidatedResourceLimits as ResourceLimits, ValidatedRollout as Rollout, +}; +use piqueld_core::resource::{DesiredMount, DesiredService, ResolvedSource}; +use std::collections::BTreeMap; + +/// Specification authored for a service attached to its private network. +fn authored() -> ServiceSpec { + BollardDocker::service_spec(&desired(Vec::new()), "local-node").expect("authored specification") +} + +/// Desired service attached to its private network and mounting `mounts`. +fn desired(mounts: Vec) -> DesiredService { + let image = format!("ghcr.io/example/notes@sha256:{}", "a".repeat(64)); + let application = piqueld_core::EnvironmentId::parse("app-policy").unwrap(); + DesiredService { + link_aliases: BTreeMap::new(), + secrets: Vec::new(), + files: Vec::new(), + logical_name: piqueld_core::ServiceName::parse("web").unwrap(), + name: piqueld_core::DockerServiceName::parse("app-policy-web").unwrap(), + source: ResolvedSource::Image { + requested: piqueld_core::ImageReference::parse("ghcr.io/example/notes:1.4.0").unwrap(), + digest_reference: piqueld_core::RepositoryDigest::parse(image.clone()).unwrap(), + }, + image: piqueld_core::ImmutableImage::parse(image).unwrap(), + replicas: 2, + environment: BTreeMap::from([("NOTES_PORT".into(), "8080".into())]), + command: vec!["/bin/notes".into()], + arguments: vec!["--listen".into(), "8080".into()], + mounts, + healthcheck: None, + resources: Some(ResourceLimits { + cpu_millis: Some(250), + memory_bytes: Some(1024), + }), + networks: vec![piqueld_core::DockerNetworkName::for_application( + &application, + )], + labels: piqueld_core::Ownership { + instance_id: piqueld_core::InstanceId::parse("instance").unwrap(), + environment_id: application, + service: Some(piqueld_core::ServiceName::parse("web").unwrap()), + spec_hash: format!("sha256:{}", "b".repeat(64)), + } + .labels(), + depends_on: Vec::new(), + rollout: Rollout::default(), + receives_telemetry: false, + telemetry: None, + } +} + +#[test] +fn authored_rollout_is_observed_back() { + let mount = |read_only| DesiredMount { + volume_name: piqueld_core::DockerVolumeName::parse("app-policy-data").unwrap(), + target: "/data".into(), + read_only, + }; + let observed = |desired: &DesiredService| { + let spec = BollardDocker::service_spec(desired, "local-node").unwrap(); + assert!(ServiceRuntimePolicy::matches(&spec, "local-node")); + BollardDocker::observed_rollout(&spec) + }; + + let read_only = desired(vec![mount(true)]); + assert_eq!(observed(&read_only), Some(read_only.rollout_policy())); + let mut writable = desired(vec![mount(true), mount(false)]); + assert_eq!( + observed(&writable).map(|rollout| rollout.order), + Some(RolloutOrder::StopFirst) + ); + writable.rollout = Rollout { + order: Some(RolloutOrder::StartFirst), + monitor_seconds: Some(5), + }; + assert_eq!(observed(&writable), Some(writable.rollout_policy())); + + // Values piqueld never authors are not mistaken for a rollout policy. + let mut spec = BollardDocker::service_spec(&writable, "local-node").unwrap(); + let update = spec.update_config.as_mut().unwrap(); + update.monitor = Some(1_500_000_000); + assert_eq!(BollardDocker::observed_rollout(&spec), None); + let update = spec.update_config.as_mut().unwrap(); + update.monitor = Some(5_000_000_000); + update.order = Some(ServiceSpecUpdateConfigOrderEnum::EMPTY); + assert_eq!(BollardDocker::observed_rollout(&spec), None); +} + +/// Swarm would expand `{{` as a Go template, so it is escaped when +/// authored and read back as written. +#[test] +fn template_text_is_authored_literally_and_observed_back() { + let text = r#"${{ vars.x }} {{.Service.Name}} {{{ {{"{{"}}"#; + let mut desired = desired(vec![DesiredMount { + volume_name: piqueld_core::DockerVolumeName::parse("app-policy-data").unwrap(), + target: "/data/{{.Task.Slot}}".into(), + read_only: false, + }]); + desired.environment.insert("TEXT".into(), text.into()); + let spec = BollardDocker::service_spec(&desired, "local-node").unwrap(); + let container = spec.task_template.as_ref().unwrap().container_spec.as_ref(); + assert!( + container.unwrap().env.as_ref().unwrap().contains( + &r#"TEXT=${{"{{"}} vars.x }} {{"{{"}}.Service.Name}} {{"{{"}}{ {{"{{"}}"{{"{{"}}"}}"# + .into() + ) + ); + let observed = BollardDocker::observe_service(&spec, "local-node", Vec::new(), None) + .expect("observed service"); + assert_eq!(observed.environment, desired.environment); + assert_eq!(observed.mounts[0].target, "/data/{{.Task.Slot}}"); + assert!(observed.matches(&desired)); + + // Specs written before escaping are drift, so reconciling rewrites them. + let unescaped = |edit: fn(&mut TaskSpecContainerSpec)| { + let mut spec = spec.clone(); + edit( + spec.task_template + .as_mut() + .unwrap() + .container_spec + .as_mut() + .unwrap(), + ); + BollardDocker::observe_service(&spec, "local-node", Vec::new(), None) + .expect("observed service") + .drift(&desired) + }; + assert_eq!( + unescaped(|container| container.env = Some(vec!["TEXT={{.Service.Name}}".into()])), + ["environment", "runtime_policy"] + ); + assert_eq!( + unescaped(|container| { + container.mounts.as_mut().unwrap()[0].target = Some("/data/{{.Task.Slot}}".into()); + }), + ["runtime_policy"] + ); +} + +#[test] +fn logical_name_is_the_only_accepted_alias() { + let mut spec = authored(); + assert!(ServiceRuntimePolicy::matches(&spec, "local-node")); + let network = &mut spec + .task_template + .as_mut() + .unwrap() + .networks + .as_mut() + .unwrap()[0]; + assert_eq!(network.aliases, Some(vec!["web".into()])); + network.aliases.as_mut().unwrap().push("other".into()); + assert!(!ServiceRuntimePolicy::matches(&spec, "local-node")); +} + +/// Including a start period and retries other than Docker's defaults. +#[test] +fn generated_http_health_check_round_trips_through_observation() { + let health_check = HealthCheck::Http { + port: 8080, + path: "/health".into(), + interval_seconds: 10, + timeout_seconds: 3, + start_period_seconds: 30, + retries: 5, + }; + let config = BollardDocker::health_config(&health_check); + + assert_eq!(BollardDocker::observed_health(&config), Some(health_check)); + assert!(ServiceRuntimePolicy::supported_health_config(&config)); +} + +/// The probe vector piqueld authors for `Http { port: 8080, path: "/health", .. }`. +fn probe_vector(arguments: &[&str]) -> Vec { + std::iter::once(piqueld_probe::CONTAINER_PATH) + .chain(arguments.iter().copied()) + .map(String::from) + .collect() +} + +#[test] +fn command_health_check_accepts_equivalent_http_vector() { + let health_check = HealthCheck::Command { + command: probe_vector(&[ + "http", + "--port", + "8080", + "--path", + "/health", + "--timeout", + "3", + ]), + interval_seconds: 10, + timeout_seconds: 3, + start_period_seconds: 0, + retries: 3, + }; + + let config = BollardDocker::health_config(&health_check); + let observed = BollardDocker::observed_health(&config).unwrap(); + assert!(matches!(observed, HealthCheck::Http { port: 8080, .. })); + assert_eq!(observed.execution(), health_check.execution()); + assert!(ServiceRuntimePolicy::supported_health_config(&config)); +} + +/// Near matches, including the `wget` vector earlier daemons authored for +/// HTTP checks, stay commands; HTTP services deployed before the probe +/// therefore drift and roll onto it. +#[test] +fn near_http_command_health_checks_round_trip_as_commands() { + for command in [ + probe_vector(&[ + "http", + "--path", + "/health", + "--port", + "8080", + "--timeout", + "3", + ]), + probe_vector(&[ + "http", + "--port", + "8080", + "--path", + "/health", + "--timeout", + "5", + ]), + [ + "wget", + "-q", + "-T", + "3", + "-O", + "/dev/null", + "http://127.0.0.1:8080/health", + ] + .map(String::from) + .into(), + ] { + let health_check = HealthCheck::Command { + command, + interval_seconds: 10, + timeout_seconds: 3, + start_period_seconds: 0, + retries: 3, + }; + + let config = BollardDocker::health_config(&health_check); + assert_eq!( + BollardDocker::observed_health(&config).as_ref(), + Some(&health_check) + ); + assert!(ServiceRuntimePolicy::supported_health_config(&config)); + } +} + +#[test] +fn policy_verifies_exactly_the_authored_fields() { + let authored = authored(); + assert!(ServiceRuntimePolicy::matches(&authored, "local-node")); + // Services are pinned to the local node. + assert!(!ServiceRuntimePolicy::matches(&authored, "another-node")); + let mut unpinned = authored.clone(); + unpinned.task_template.as_mut().unwrap().placement = None; + assert!(!ServiceRuntimePolicy::matches(&unpinned, "local-node")); + + // Known Engine defaults are accepted, while unsupported non-default + // behavior remains visible as drift. + let mut echoed = authored.clone(); + let task = echoed.task_template.as_mut().expect("task"); + task.resources.as_mut().expect("resources").reservations = + Some(bollard::models::ResourceObject::default()); + task.runtime = Some("container".into()); + task.force_update = Some(0); + task.placement.as_mut().expect("placement").max_replicas = Some(0); + task.restart_policy.as_mut().expect("restart").max_attempts = Some(0); + task.container_spec.as_mut().expect("container").dns_config = + Some(bollard::models::TaskSpecContainerSpecDnsConfig::default()); + echoed.rollback_config = Some(ServiceSpecRollbackConfig { + parallelism: Some(1), + failure_action: Some(bollard::models::ServiceSpecRollbackConfigFailureActionEnum::PAUSE), + monitor: Some(5 * super::super::NANOSECONDS_PER_SECOND), + max_failure_ratio: Some(0.0), + order: Some(bollard::models::ServiceSpecRollbackConfigOrderEnum::STOP_FIRST), + ..Default::default() + }); + assert!(ServiceRuntimePolicy::matches(&echoed, "local-node")); + + echoed.rollback_config = Some(ServiceSpecRollbackConfig::default()); + if let Some(container) = echoed + .task_template + .as_mut() + .and_then(|task| task.container_spec.as_mut()) + { + container.stop_grace_period = Some(12_345); + container.hostname = Some("echoed".into()); + } + assert!(!ServiceRuntimePolicy::matches(&echoed, "local-node")); + + // A non-default runtime is out-of-band modification. + let mut runtime = authored.clone(); + runtime.task_template.as_mut().unwrap().runtime = Some("custom-runtime".into()); + assert!(!ServiceRuntimePolicy::matches(&runtime, "local-node")); + + // Drift in a field piqueld authors is still rejected. + let mut drifted = authored.clone(); + if let Some(update) = drifted.update_config.as_mut() { + update.parallelism = Some(4); + } + assert!(!ServiceRuntimePolicy::matches(&drifted, "local-node")); + + // Out-of-band security settings are rejected even though piqueld + // cannot author them. + let mut injected_capability = authored.clone(); + if let Some(container) = injected_capability + .task_template + .as_mut() + .and_then(|task| task.container_spec.as_mut()) + { + container.capability_add = Some(vec!["NET_ADMIN".into()]); + } + assert!(!ServiceRuntimePolicy::matches( + &injected_capability, + "local-node" + )); + + let mut injected_user = authored; + if let Some(container) = injected_user + .task_template + .as_mut() + .and_then(|task| task.container_spec.as_mut()) + { + container.user = Some("0".into()); + } + assert!(!ServiceRuntimePolicy::matches(&injected_user, "local-node")); +} diff --git a/crates/piqueld-docker/src/probe.rs b/crates/piqueld-docker/src/probe/mod.rs similarity index 66% rename from crates/piqueld-docker/src/probe.rs rename to crates/piqueld-docker/src/probe/mod.rs index e9f6ef8e2..41c14d433 100644 --- a/crates/piqueld-docker/src/probe.rs +++ b/crates/piqueld-docker/src/probe/mod.rs @@ -156,84 +156,4 @@ impl BollardDocker { } #[cfg(test)] -mod tests { - use super::super::HealthCheck; - use super::*; - - /// The probe config belongs exactly when the health check runs the probe, - /// and only as this daemon's version for its installation mounted at the - /// container path. - #[test] - fn the_probe_config_must_match_the_health_check() { - let http = HealthCheck::Http { - port: 8080, - path: "/health".into(), - interval_seconds: 10, - timeout_seconds: 3, - start_period_seconds: 0, - retries: 3, - }; - let command = HealthCheck::Command { - command: vec!["true".into()], - interval_seconds: 10, - timeout_seconds: 3, - start_period_seconds: 0, - retries: 3, - }; - let matches = |health: &HealthCheck, configs: Vec| { - HealthProbe::matches( - &TaskSpecContainerSpec { - health_check: Some(BollardDocker::health_config(health)), - configs: Some(configs), - ..Default::default() - }, - Some("instance-1"), - ) - }; - let probe = HealthProbe::reference("config-id".into(), "instance-1"); - let another_installations = HealthProbe::reference("config-id".into(), "instance-2"); - let older = TaskSpecContainerSpecConfigs { - config_name: Some("piqueld-health-probe-0000000000000000".into()), - ..probe.clone() - }; - let mut writable = probe.clone(); - writable.file.as_mut().unwrap().mode = Some(0o777); - - // Service files mount other configs elsewhere, checked separately. - let file = TaskSpecContainerSpecConfigs { - config_name: Some("piqueld-app-file-0000".into()), - file: Some(TaskSpecContainerSpecFile1 { - name: Some("/etc/app.conf".into()), - ..probe.file.clone().unwrap() - }), - ..probe.clone() - }; - - assert!(matches(&http, vec![probe.clone()])); - assert!(matches(&http, vec![file.clone(), probe.clone()])); - assert!(matches(&command, vec![file])); - assert!(!matches(&http, Vec::new())); - assert!(!matches(&http, vec![older])); - assert!(!matches(&http, vec![another_installations])); - assert!(!matches(&http, vec![writable])); - assert!(!matches( - &http, - vec![HealthProbe::reference(String::new(), "instance-1")] - )); - assert!(!matches(&http, vec![probe.clone(), probe.clone()])); - assert!(!matches(&command, vec![probe])); - assert!(matches(&command, Vec::new())); - } - - #[test] - fn the_embedded_probe_fits_a_swarm_config() { - // Swarm rejects configs over 500 KiB on some Engine versions. - assert!(BINARY.len() <= 500 * 1024, "{} bytes", BINARY.len()); - assert!(BINARY.starts_with(b"\x7fELF")); - // Within Swarm's name limit for the longest instance IDs, and distinct - // per installation. - let name = HealthProbe::name(&"a".repeat(64)); - assert!(name.starts_with("piqueld-health-probe-") && name.len() <= 63); - assert_ne!(name, HealthProbe::name("instance-1")); - } -} +mod tests; diff --git a/crates/piqueld-docker/src/probe/tests.rs b/crates/piqueld-docker/src/probe/tests.rs new file mode 100644 index 000000000..70a0f1156 --- /dev/null +++ b/crates/piqueld-docker/src/probe/tests.rs @@ -0,0 +1,79 @@ +use super::super::HealthCheck; +use super::*; + +/// The probe config belongs exactly when the health check runs the probe, +/// and only as this daemon's version for its installation mounted at the +/// container path. +#[test] +fn the_probe_config_must_match_the_health_check() { + let http = HealthCheck::Http { + port: 8080, + path: "/health".into(), + interval_seconds: 10, + timeout_seconds: 3, + start_period_seconds: 0, + retries: 3, + }; + let command = HealthCheck::Command { + command: vec!["true".into()], + interval_seconds: 10, + timeout_seconds: 3, + start_period_seconds: 0, + retries: 3, + }; + let matches = |health: &HealthCheck, configs: Vec| { + HealthProbe::matches( + &TaskSpecContainerSpec { + health_check: Some(BollardDocker::health_config(health)), + configs: Some(configs), + ..Default::default() + }, + Some("instance-1"), + ) + }; + let probe = HealthProbe::reference("config-id".into(), "instance-1"); + let another_installations = HealthProbe::reference("config-id".into(), "instance-2"); + let older = TaskSpecContainerSpecConfigs { + config_name: Some("piqueld-health-probe-0000000000000000".into()), + ..probe.clone() + }; + let mut writable = probe.clone(); + writable.file.as_mut().unwrap().mode = Some(0o777); + + // Service files mount other configs elsewhere, checked separately. + let file = TaskSpecContainerSpecConfigs { + config_name: Some("piqueld-app-file-0000".into()), + file: Some(TaskSpecContainerSpecFile1 { + name: Some("/etc/app.conf".into()), + ..probe.file.clone().unwrap() + }), + ..probe.clone() + }; + + assert!(matches(&http, vec![probe.clone()])); + assert!(matches(&http, vec![file.clone(), probe.clone()])); + assert!(matches(&command, vec![file])); + assert!(!matches(&http, Vec::new())); + assert!(!matches(&http, vec![older])); + assert!(!matches(&http, vec![another_installations])); + assert!(!matches(&http, vec![writable])); + assert!(!matches( + &http, + vec![HealthProbe::reference(String::new(), "instance-1")] + )); + assert!(!matches(&http, vec![probe.clone(), probe.clone()])); + assert!(!matches(&command, vec![probe])); + assert!(matches(&command, Vec::new())); +} + +#[test] +fn the_embedded_probe_fits_a_swarm_config() { + // Swarm rejects configs over 500 KiB on some Engine versions. + assert!(BINARY.len() <= 500 * 1024, "{} bytes", BINARY.len()); + assert!(BINARY.starts_with(b"\x7fELF")); + // Within Swarm's name limit for the longest instance IDs, and distinct + // per installation. + let name = HealthProbe::name(&"a".repeat(64)); + assert!(name.starts_with("piqueld-health-probe-") && name.len() <= 63); + assert_ne!(name, HealthProbe::name("instance-1")); +}