Compare commits
7 Commits
feat/docke
...
doc/cert-m
| Author | SHA1 | Date | |
|---|---|---|---|
| ce76eb1da9 | |||
| f319f74edf | |||
| f576effeca | |||
| 25c5cd84fe | |||
| dc421fa099 | |||
| 2153edc68c | |||
| 949c9a40be |
@@ -10,7 +10,7 @@ members = [
|
||||
"opnsense-config",
|
||||
"opnsense-config-xml",
|
||||
"harmony_cli",
|
||||
"harmony_tools",
|
||||
"k3d",
|
||||
"harmony_composer",
|
||||
"harmony_inventory_agent",
|
||||
"harmony_secret_derive",
|
||||
|
||||
19
examples/cert_manager/Cargo.toml
Normal file
19
examples/cert_manager/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "cert_manager"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
assert_cmd = "2.0.16"
|
||||
46
examples/cert_manager/src/main.rs
Normal file
46
examples/cert_manager/src/main.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::{
|
||||
cert_manager::{
|
||||
capability::CertificateManagementConfig, score_create_cert::CertificateCreationScore,
|
||||
score_create_issuer::CertificateIssuerScore,
|
||||
score_operator::CertificateManagementScore,
|
||||
},
|
||||
postgresql::{PostgreSQLScore, capability::PostgreSQLConfig},
|
||||
},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let config = CertificateManagementConfig {
|
||||
namespace: Some("test".to_string()),
|
||||
acme_issuer: None,
|
||||
ca_issuer: None,
|
||||
self_signed: true,
|
||||
};
|
||||
|
||||
let cert_manager = CertificateManagementScore {
|
||||
config: config.clone(),
|
||||
};
|
||||
|
||||
let issuer = CertificateIssuerScore {
|
||||
config: config.clone(),
|
||||
issuer_name: "test-self-signed-issuer".to_string(),
|
||||
};
|
||||
|
||||
let cert = CertificateCreationScore {
|
||||
config: config.clone(),
|
||||
cert_name: "test-self-signed-cert".to_string(),
|
||||
issuer_name: "test-self-signed-issuer".to_string(),
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(cert_manager), Box::new(issuer), Box::new(cert)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -9,14 +9,6 @@ license.workspace = true
|
||||
testing = []
|
||||
|
||||
[dependencies]
|
||||
opnsense-config = { path = "../opnsense-config" }
|
||||
opnsense-config-xml = { path = "../opnsense-config-xml" }
|
||||
harmony_macros = { path = "../harmony_macros" }
|
||||
harmony_types = { path = "../harmony_types" }
|
||||
harmony_inventory_agent = { path = "../harmony_inventory_agent" }
|
||||
harmony_secret_derive = { path = "../harmony_secret_derive" }
|
||||
harmony_secret = { path = "../harmony_secret" }
|
||||
harmony_tools = { path = "../harmony_tools" }
|
||||
hex = "0.4"
|
||||
reqwest = { version = "0.11", features = [
|
||||
"blocking",
|
||||
@@ -34,6 +26,10 @@ log.workspace = true
|
||||
env_logger.workspace = true
|
||||
async-trait.workspace = true
|
||||
cidr.workspace = true
|
||||
opnsense-config = { path = "../opnsense-config" }
|
||||
opnsense-config-xml = { path = "../opnsense-config-xml" }
|
||||
harmony_macros = { path = "../harmony_macros" }
|
||||
harmony_types = { path = "../harmony_types" }
|
||||
uuid.workspace = true
|
||||
url.workspace = true
|
||||
kube = { workspace = true, features = ["derive"] }
|
||||
@@ -43,6 +39,7 @@ http.workspace = true
|
||||
serde-value.workspace = true
|
||||
helm-wrapper-rs = "0.4.0"
|
||||
non-blank-string-rs = "1.0.4"
|
||||
k3d-rs = { path = "../k3d" }
|
||||
directories.workspace = true
|
||||
lazy_static.workspace = true
|
||||
dockerfile_builder = "0.1.5"
|
||||
@@ -74,6 +71,9 @@ base64.workspace = true
|
||||
thiserror.workspace = true
|
||||
once_cell = "1.21.3"
|
||||
walkdir = "2.5.0"
|
||||
harmony_inventory_agent = { path = "../harmony_inventory_agent" }
|
||||
harmony_secret_derive = { path = "../harmony_secret_derive" }
|
||||
harmony_secret = { path = "../harmony_secret" }
|
||||
askama.workspace = true
|
||||
sqlx.workspace = true
|
||||
inquire.workspace = true
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Docker Capability
|
||||
#[async_trait]
|
||||
pub trait Docker {
|
||||
async fn ensure_installed(&self) -> Result<(), String>;
|
||||
fn get_docker_env(&self) -> HashMap<String, String>;
|
||||
fn docker_command(&self) -> std::process::Command;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ use kube::{
|
||||
Api, AttachParams, DeleteParams, ListParams, ObjectList, Patch, PatchParams, ResourceExt,
|
||||
},
|
||||
config::{KubeConfigOptions, Kubeconfig},
|
||||
core::ErrorResponse,
|
||||
core::{DynamicResourceScope, ErrorResponse},
|
||||
discovery::{ApiCapabilities, Scope},
|
||||
error::DiscoveryError,
|
||||
runtime::reflector::Lookup,
|
||||
@@ -230,14 +230,26 @@ impl K8sClient {
|
||||
namespace: Option<&str>,
|
||||
gvk: &GroupVersionKind,
|
||||
) -> Result<DynamicObject, Error> {
|
||||
let gvk = ApiResource::from_gvk(gvk);
|
||||
let resource: Api<DynamicObject> = if let Some(ns) = namespace {
|
||||
Api::namespaced_with(self.client.clone(), ns, &gvk)
|
||||
} else {
|
||||
Api::default_namespaced_with(self.client.clone(), &gvk)
|
||||
};
|
||||
let api_resource = ApiResource::from_gvk(gvk);
|
||||
|
||||
resource.get(name).await
|
||||
// 1. Try namespaced first (if a namespace was provided)
|
||||
if let Some(ns) = namespace {
|
||||
let api: Api<DynamicObject> =
|
||||
Api::namespaced_with(self.client.clone(), ns, &api_resource);
|
||||
|
||||
match api.get(name).await {
|
||||
Ok(obj) => return Ok(obj),
|
||||
Err(Error::Api(ae)) if ae.code == 404 => {
|
||||
// fall through and try cluster-scoped
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fallback to cluster-scoped
|
||||
let api: Api<DynamicObject> = Api::all_with(self.client.clone(), &api_resource);
|
||||
|
||||
api.get(name).await
|
||||
}
|
||||
|
||||
pub async fn get_secret_json_value(
|
||||
|
||||
@@ -1,13 +1,7 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
process::Command,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use std::{collections::BTreeMap, process::Command, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::{Engine, engine::general_purpose};
|
||||
use harmony_tools::K3d;
|
||||
use harmony_types::rfc1123::Rfc1123Name;
|
||||
use k8s_openapi::api::{
|
||||
core::v1::Secret,
|
||||
@@ -19,12 +13,15 @@ use serde::Serialize;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use crate::{
|
||||
config::HARMONY_DATA_DIR,
|
||||
executors::ExecutorError,
|
||||
interpret::InterpretStatus,
|
||||
inventory::Inventory,
|
||||
modules::{
|
||||
docker::DockerInstallationScore,
|
||||
cert_manager::{
|
||||
capability::{CertificateManagement, CertificateManagementConfig},
|
||||
crd::{score_certificate::CertificateScore, score_issuer::IssuerScore},
|
||||
operator::CertManagerOperatorScore,
|
||||
},
|
||||
k3d::K3DInstallationScore,
|
||||
k8s::ingress::{K8sIngressScore, PathType},
|
||||
monitoring::{
|
||||
@@ -50,7 +47,7 @@ use crate::{
|
||||
},
|
||||
},
|
||||
score::Score,
|
||||
topology::{Docker, TlsRoute, TlsRouter, ingress::Ingress},
|
||||
topology::{TlsRoute, TlsRouter, ingress::Ingress},
|
||||
};
|
||||
|
||||
use super::super::{
|
||||
@@ -358,24 +355,6 @@ impl PrometheusMonitoring<RHOBObservability> for K8sAnywhereTopology {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Docker for K8sAnywhereTopology {
|
||||
async fn ensure_installed(&self) -> Result<(), String> {
|
||||
DockerInstallationScore::default()
|
||||
.interpret(&Inventory::empty(), self)
|
||||
.await
|
||||
.map_err(|e| format!("Could not ensure docker is installed : {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
fn get_docker_env(&self) -> HashMap<String, String> {
|
||||
harmony_tools::Docker::new(HARMONY_DATA_DIR.join("docker")).get_docker_env()
|
||||
}
|
||||
|
||||
fn docker_command(&self) -> std::process::Command {
|
||||
harmony_tools::Docker::new(HARMONY_DATA_DIR.join("docker")).command()
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for K8sAnywhereTopology {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
@@ -385,6 +364,97 @@ impl Serialize for K8sAnywhereTopology {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CertificateManagement for K8sAnywhereTopology {
|
||||
async fn install(&self) -> Result<PreparationOutcome, PreparationError> {
|
||||
let cert_management_operator = CertManagerOperatorScore::default();
|
||||
|
||||
cert_management_operator
|
||||
.interpret(&Inventory::empty(), self)
|
||||
.await
|
||||
.map_err(|e| PreparationError { msg: e.to_string() })?;
|
||||
|
||||
Ok(PreparationOutcome::Success {
|
||||
details: format!(
|
||||
"Installed cert-manager into ns: {}",
|
||||
cert_management_operator.namespace
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
async fn ensure_certificate_management_ready(
|
||||
&self,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError> {
|
||||
let k8s_client = self.k8s_client().await.unwrap();
|
||||
let gvk = GroupVersionKind {
|
||||
group: "operators.coreos.com".to_string(),
|
||||
version: "v1".to_string(),
|
||||
kind: "Operator".to_string(),
|
||||
};
|
||||
//TODO make this generic across k8s distributions using k8s family
|
||||
match k8s_client
|
||||
.get_resource_json_value("cert-manager.openshift-operators", None, &gvk)
|
||||
.await
|
||||
{
|
||||
Ok(_ready) => Ok(PreparationOutcome::Success {
|
||||
details: "Certificate Management Ready".to_string(),
|
||||
}),
|
||||
Err(e) => {
|
||||
debug!("{} operator not found", e.to_string());
|
||||
self.install().await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_issuer(
|
||||
&self,
|
||||
issuer_name: String,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError> {
|
||||
let issuer_score = IssuerScore {
|
||||
issuer_name: issuer_name.clone(),
|
||||
config: config.clone(),
|
||||
};
|
||||
|
||||
issuer_score
|
||||
.interpret(&Inventory::empty(), self)
|
||||
.await
|
||||
.map_err(|e| PreparationError { msg: e.to_string() })?;
|
||||
|
||||
Ok(PreparationOutcome::Success {
|
||||
details: format!("issuer of kind {} is ready", issuer_name),
|
||||
})
|
||||
}
|
||||
|
||||
async fn create_certificate(
|
||||
&self,
|
||||
cert_name: String,
|
||||
issuer_name: String,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError> {
|
||||
self.certificate_issuer_ready(
|
||||
issuer_name.clone(),
|
||||
self.k8s_client().await.unwrap(),
|
||||
config,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let cert = CertificateScore {
|
||||
cert_name: cert_name,
|
||||
config: config.clone(),
|
||||
issuer_name,
|
||||
};
|
||||
cert.interpret(&Inventory::empty(), self)
|
||||
.await
|
||||
.map_err(|e| PreparationError { msg: e.to_string() })?;
|
||||
|
||||
Ok(PreparationOutcome::Success {
|
||||
details: format!("Created cert into ns: {:#?}", config.namespace.clone()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sAnywhereTopology {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
@@ -404,6 +474,35 @@ impl K8sAnywhereTopology {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn certificate_issuer_ready(
|
||||
&self,
|
||||
issuer_name: String,
|
||||
k8s_client: Arc<K8sClient>,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError> {
|
||||
let ns = config.namespace.clone().ok_or_else(|| PreparationError {
|
||||
msg: "namespace is required".to_string(),
|
||||
})?;
|
||||
|
||||
let gvk = GroupVersionKind {
|
||||
group: "cert-manager.io".to_string(),
|
||||
version: "v1".to_string(),
|
||||
kind: "Issuer".to_string(),
|
||||
};
|
||||
|
||||
match k8s_client
|
||||
.get_resource_json_value(&issuer_name, Some(&ns), &gvk)
|
||||
.await
|
||||
{
|
||||
Ok(_cert_issuer) => Ok(PreparationOutcome::Success {
|
||||
details: format!("issuer of kind {} is ready", issuer_name),
|
||||
}),
|
||||
Err(e) => Err(PreparationError {
|
||||
msg: format!("{} issuer {} not present", e.to_string(), issuer_name),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_k8s_distribution(&self) -> Result<&KubernetesDistribution, PreparationError> {
|
||||
self.k8s_distribution
|
||||
.get_or_try_init(async || {
|
||||
@@ -763,7 +862,7 @@ impl K8sAnywhereTopology {
|
||||
// K3DInstallationScore should expose a method to get_client ? Not too sure what would be a
|
||||
// good implementation due to the stateful nature of the k3d thing. Which is why I went
|
||||
// with this solution for now
|
||||
let k3d = K3d::new(k3d_score.installation_path, Some(k3d_score.cluster_name));
|
||||
let k3d = k3d_rs::K3d::new(k3d_score.installation_path, Some(k3d_score.cluster_name));
|
||||
let state = match k3d.get_client().await {
|
||||
Ok(client) => K8sState {
|
||||
client: Arc::new(K8sClient::new(client)),
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
mod docker;
|
||||
mod failover;
|
||||
mod ha_cluster;
|
||||
pub mod ingress;
|
||||
pub mod node_exporter;
|
||||
pub mod opnsense;
|
||||
pub use docker::*;
|
||||
pub use failover::*;
|
||||
use harmony_types::net::IpAddress;
|
||||
mod host_binding;
|
||||
|
||||
90
harmony/src/modules/cert_manager/capability.rs
Normal file
90
harmony/src/modules/cert_manager/capability.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use async_trait::async_trait;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
modules::cert_manager::crd::{AcmeIssuer, CaIssuer},
|
||||
topology::{PreparationError, PreparationOutcome},
|
||||
};
|
||||
|
||||
/// Certificate management capability for a topology.
|
||||
///
|
||||
/// This trait represents the ability of a topology to provision, manage,
|
||||
/// and ensure the availability of TLS certificates.
|
||||
///
|
||||
/// Implementations may back this capability using different mechanisms,
|
||||
/// for example: a Kubernetes controller, an external PKI service, or
|
||||
/// platform-specific tooling
|
||||
///
|
||||
/// ## Concepts
|
||||
///
|
||||
/// ### Certificate Management System
|
||||
/// A certificate management system is responsible for issuing, renewing,
|
||||
/// and storing certificates. Before certificates can be created, this
|
||||
/// system must be installed and ready to serve requests.
|
||||
///
|
||||
/// ### Issuer
|
||||
/// An Issuer defines how certificates are issued and signed.
|
||||
/// It encapsulates trust configuration such as signing keys, certificate
|
||||
/// authorities, or external services. Issuers do not represent certificates
|
||||
/// themselves, but are referenced by certificate requests.
|
||||
///
|
||||
/// ### Certificate
|
||||
/// A Certificate represents a request for cryptographic identity
|
||||
/// material. It references an Issuer and defines the identities the certificate should be valid for,
|
||||
/// as well as where the resulting certificate material should be stored.
|
||||
///
|
||||
/// ## Responsibilities
|
||||
///
|
||||
/// Implementations of this trait are responsible for:
|
||||
///
|
||||
/// - Installing the underlying certificate management system
|
||||
/// - Ensuring the system is ready before certificates are requested
|
||||
/// - Creating Issuers
|
||||
/// - Creating Certificates
|
||||
///
|
||||
#[async_trait]
|
||||
pub trait CertificateManagement: Send + Sync {
|
||||
/// Installs the underlying certificate management system for the topology.
|
||||
///
|
||||
/// Abstracts away installation details
|
||||
/// (e.g., controllers, operators, external services).
|
||||
async fn install(&self) -> Result<PreparationOutcome, PreparationError>;
|
||||
|
||||
/// Ensures that the certificate management system is installed and ready.
|
||||
///
|
||||
/// May verify presence of required components, APIs, or controllers,
|
||||
/// and perform installation if necessary.
|
||||
async fn ensure_certificate_management_ready(
|
||||
&self,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError>;
|
||||
|
||||
/// Creates an issuer used to sign certificates.
|
||||
///
|
||||
/// Abstracts away issuer representation and storage
|
||||
/// (e.g., cluster-scoped resources, external PKI configuration).
|
||||
async fn create_issuer(
|
||||
&self,
|
||||
issuer_name: String,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError>;
|
||||
|
||||
/// Creates a certificate signed by a previously created issuer.
|
||||
///
|
||||
/// Abstracts away certificate request, issuance, and storage details
|
||||
/// (e.g., secrets, files, remote APIs).
|
||||
async fn create_certificate(
|
||||
&self,
|
||||
cert_name: String,
|
||||
issuer_name: String,
|
||||
config: &CertificateManagementConfig,
|
||||
) -> Result<PreparationOutcome, PreparationError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertificateManagementConfig {
|
||||
pub namespace: Option<String>,
|
||||
pub acme_issuer: Option<AcmeIssuer>,
|
||||
pub ca_issuer: Option<CaIssuer>,
|
||||
pub self_signed: bool,
|
||||
}
|
||||
112
harmony/src/modules/cert_manager/crd/certificate.rs
Normal file
112
harmony/src/modules/cert_manager/crd/certificate.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use kube::{CustomResource, api::ObjectMeta};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(CustomResource, Deserialize, Serialize, Clone, Debug)]
|
||||
#[kube(
|
||||
group = "cert-manager.io",
|
||||
version = "v1",
|
||||
kind = "Certificate",
|
||||
plural = "certificates",
|
||||
namespaced = true,
|
||||
schema = "disabled"
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CertificateSpec {
|
||||
/// Name of the Secret where the certificate will be stored
|
||||
pub secret_name: String,
|
||||
|
||||
/// Common Name (optional but often discouraged in favor of SANs)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub common_name: Option<String>,
|
||||
|
||||
/// DNS Subject Alternative Names
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dns_names: Option<Vec<String>>,
|
||||
|
||||
/// IP Subject Alternative Names
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ip_addresses: Option<Vec<String>>,
|
||||
|
||||
/// Certificate duration (e.g. "2160h")
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub duration: Option<String>,
|
||||
|
||||
/// How long before expiry cert-manager should renew
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub renew_before: Option<String>,
|
||||
|
||||
/// Reference to the Issuer or ClusterIssuer
|
||||
pub issuer_ref: IssuerRef,
|
||||
|
||||
/// Is this a CA certificate
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_ca: Option<bool>,
|
||||
|
||||
/// Private key configuration
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub private_key: Option<PrivateKey>,
|
||||
}
|
||||
|
||||
impl Default for Certificate {
|
||||
fn default() -> Self {
|
||||
Certificate {
|
||||
metadata: ObjectMeta::default(),
|
||||
spec: CertificateSpec::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CertificateSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
secret_name: String::new(),
|
||||
common_name: None,
|
||||
dns_names: None,
|
||||
ip_addresses: None,
|
||||
duration: None,
|
||||
renew_before: None,
|
||||
issuer_ref: IssuerRef::default(),
|
||||
is_ca: None,
|
||||
private_key: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IssuerRef {
|
||||
pub name: String,
|
||||
|
||||
/// Either "Issuer" or "ClusterIssuer"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub kind: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for IssuerRef {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
kind: None,
|
||||
group: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PrivateKey {
|
||||
/// RSA or ECDSA
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub algorithm: Option<String>,
|
||||
|
||||
/// Key size (e.g. 2048, 4096)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
|
||||
/// Rotation policy: "Never" or "Always"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub rotation_policy: Option<String>,
|
||||
}
|
||||
44
harmony/src/modules/cert_manager/crd/cluster_issuer.rs
Normal file
44
harmony/src/modules/cert_manager/crd/cluster_issuer.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use kube::{CustomResource, api::ObjectMeta};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::modules::cert_manager::crd::{AcmeIssuer, CaIssuer, SelfSignedIssuer};
|
||||
|
||||
#[derive(CustomResource, Deserialize, Serialize, Clone, Debug)]
|
||||
#[kube(
|
||||
group = "cert-manager.io",
|
||||
version = "v1",
|
||||
kind = "ClusterIssuer",
|
||||
plural = "clusterissuers",
|
||||
namespaced = false,
|
||||
schema = "disabled"
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClusterIssuerSpec {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub self_signed: Option<SelfSignedIssuer>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ca: Option<CaIssuer>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub acme: Option<AcmeIssuer>,
|
||||
}
|
||||
|
||||
impl Default for ClusterIssuer {
|
||||
fn default() -> Self {
|
||||
ClusterIssuer {
|
||||
metadata: ObjectMeta::default(),
|
||||
spec: ClusterIssuerSpec::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ClusterIssuerSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
self_signed: None,
|
||||
ca: None,
|
||||
acme: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
44
harmony/src/modules/cert_manager/crd/issuer.rs
Normal file
44
harmony/src/modules/cert_manager/crd/issuer.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use kube::{CustomResource, api::ObjectMeta};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::modules::cert_manager::crd::{AcmeIssuer, CaIssuer, SelfSignedIssuer};
|
||||
|
||||
#[derive(CustomResource, Deserialize, Serialize, Clone, Debug)]
|
||||
#[kube(
|
||||
group = "cert-manager.io",
|
||||
version = "v1",
|
||||
kind = "Issuer",
|
||||
plural = "issuers",
|
||||
namespaced = true,
|
||||
schema = "disabled"
|
||||
)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IssuerSpec {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub self_signed: Option<SelfSignedIssuer>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ca: Option<CaIssuer>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub acme: Option<AcmeIssuer>,
|
||||
}
|
||||
|
||||
impl Default for Issuer {
|
||||
fn default() -> Self {
|
||||
Issuer {
|
||||
metadata: ObjectMeta::default(),
|
||||
spec: IssuerSpec::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for IssuerSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
self_signed: None,
|
||||
ca: None,
|
||||
acme: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
65
harmony/src/modules/cert_manager/crd/mod.rs
Normal file
65
harmony/src/modules/cert_manager/crd/mod.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub mod certificate;
|
||||
pub mod cluster_issuer;
|
||||
pub mod issuer;
|
||||
//pub mod score_cluster_issuer;
|
||||
pub mod score_certificate;
|
||||
pub mod score_issuer;
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CaIssuer {
|
||||
/// Secret containing `tls.crt` and `tls.key`
|
||||
pub secret_name: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SelfSignedIssuer {}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AcmeIssuer {
|
||||
pub server: String,
|
||||
pub email: String,
|
||||
|
||||
/// Secret used to store the ACME account private key
|
||||
pub private_key_secret_ref: SecretKeySelector,
|
||||
|
||||
pub solvers: Vec<AcmeSolver>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SecretKeySelector {
|
||||
pub name: String,
|
||||
pub key: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AcmeSolver {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub http01: Option<Http01Solver>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dns01: Option<Dns01Solver>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Dns01Solver {}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Http01Solver {
|
||||
pub ingress: IngressSolver,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct IngressSolver {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class: Option<String>,
|
||||
}
|
||||
49
harmony/src/modules/cert_manager/crd/score_certificate.rs
Normal file
49
harmony/src/modules/cert_manager/crd/score_certificate.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use kube::api::ObjectMeta;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::{
|
||||
cert_manager::{
|
||||
capability::CertificateManagementConfig,
|
||||
crd::certificate::{Certificate, CertificateSpec, IssuerRef},
|
||||
},
|
||||
k8s::resource::K8sResourceScore,
|
||||
},
|
||||
score::Score,
|
||||
topology::{K8sclient, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertificateScore {
|
||||
pub cert_name: String,
|
||||
pub issuer_name: String,
|
||||
pub config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
impl<T: Topology + K8sclient> Score<T> for CertificateScore {
|
||||
fn name(&self) -> String {
|
||||
"CertificateScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
let cert = Certificate {
|
||||
metadata: ObjectMeta {
|
||||
name: Some(self.cert_name.clone()),
|
||||
namespace: self.config.namespace.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
spec: CertificateSpec {
|
||||
secret_name: format!("{}-tls", self.cert_name.clone()),
|
||||
issuer_ref: IssuerRef {
|
||||
name: self.issuer_name.clone(),
|
||||
kind: Some("Issuer".into()),
|
||||
group: Some("cert-manager.io".into()),
|
||||
},
|
||||
dns_names: Some(vec!["test.example.local".to_string()]),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
K8sResourceScore::single(cert, self.config.namespace.clone()).create_interpret()
|
||||
}
|
||||
}
|
||||
51
harmony/src/modules/cert_manager/crd/score_cluster_issuer.rs
Normal file
51
harmony/src/modules/cert_manager/crd/score_cluster_issuer.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use kube::api::ObjectMeta;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::{
|
||||
cert_manager::crd::{
|
||||
AcmeIssuer, CaIssuer, SelfSignedIssuer,
|
||||
cluster_issuer::{ClusterIssuer, ClusterIssuerSpec},
|
||||
},
|
||||
k8s::resource::K8sResourceScore,
|
||||
},
|
||||
score::Score,
|
||||
topology::{K8sclient, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ClusterIssuerScore {
|
||||
name: String,
|
||||
acme_issuer: Option<AcmeIssuer>,
|
||||
ca_issuer: Option<CaIssuer>,
|
||||
self_signed: bool,
|
||||
}
|
||||
|
||||
impl<T: Topology + K8sclient> Score<T> for ClusterIssuerScore {
|
||||
fn name(&self) -> String {
|
||||
"ClusterIssuerScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
let metadata = ObjectMeta {
|
||||
name: Some(self.name.clone()),
|
||||
namespace: None,
|
||||
..ObjectMeta::default()
|
||||
};
|
||||
|
||||
let spec = ClusterIssuerSpec {
|
||||
acme: self.acme_issuer.clone(),
|
||||
ca: self.ca_issuer.clone(),
|
||||
self_signed: if self.self_signed {
|
||||
Some(SelfSignedIssuer::default())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
|
||||
let cluster_issuer = ClusterIssuer { metadata, spec };
|
||||
|
||||
K8sResourceScore::single(cluster_issuer, None).create_interpret()
|
||||
}
|
||||
}
|
||||
52
harmony/src/modules/cert_manager/crd/score_issuer.rs
Normal file
52
harmony/src/modules/cert_manager/crd/score_issuer.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use kube::api::ObjectMeta;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::{
|
||||
cert_manager::{
|
||||
capability::CertificateManagementConfig,
|
||||
crd::{
|
||||
SelfSignedIssuer,
|
||||
issuer::{Issuer, IssuerSpec},
|
||||
},
|
||||
},
|
||||
k8s::resource::K8sResourceScore,
|
||||
},
|
||||
score::Score,
|
||||
topology::{K8sclient, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct IssuerScore {
|
||||
pub issuer_name: String,
|
||||
pub config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
impl<T: Topology + K8sclient> Score<T> for IssuerScore {
|
||||
fn name(&self) -> String {
|
||||
"IssuerScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
let metadata = ObjectMeta {
|
||||
name: Some(self.issuer_name.clone()),
|
||||
namespace: self.config.namespace.clone(),
|
||||
..ObjectMeta::default()
|
||||
};
|
||||
|
||||
let spec = IssuerSpec {
|
||||
acme: self.config.acme_issuer.clone(),
|
||||
ca: self.config.ca_issuer.clone(),
|
||||
self_signed: if self.config.self_signed {
|
||||
Some(SelfSignedIssuer::default())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
};
|
||||
|
||||
let issuer = Issuer { metadata, spec };
|
||||
|
||||
K8sResourceScore::single(issuer, self.config.namespace.clone()).create_interpret()
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
pub mod capability;
|
||||
pub mod cluster_issuer;
|
||||
pub mod crd;
|
||||
mod helm;
|
||||
pub mod operator;
|
||||
pub mod score_create_cert;
|
||||
pub mod score_create_issuer;
|
||||
pub mod score_operator;
|
||||
pub use helm::*;
|
||||
|
||||
64
harmony/src/modules/cert_manager/operator.rs
Normal file
64
harmony/src/modules/cert_manager/operator.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use kube::api::ObjectMeta;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::Interpret,
|
||||
modules::k8s::{
|
||||
apps::crd::{Subscription, SubscriptionSpec},
|
||||
resource::K8sResourceScore,
|
||||
},
|
||||
score::Score,
|
||||
topology::{K8sclient, Topology, k8s::K8sClient},
|
||||
};
|
||||
|
||||
/// Install the Cert-Manager Operator via RedHat Community Operators registry.redhat.io/redhat/community-operator-index:v4.19
|
||||
/// This Score creates a Subscription CR in the specified namespace
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertManagerOperatorScore {
|
||||
pub namespace: String,
|
||||
pub channel: String,
|
||||
pub install_plan_approval: String,
|
||||
pub source: String,
|
||||
pub source_namespace: String,
|
||||
}
|
||||
|
||||
impl Default for CertManagerOperatorScore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
namespace: "openshift-operators".to_string(),
|
||||
channel: "stable".to_string(),
|
||||
install_plan_approval: "Automatic".to_string(),
|
||||
source: "community-operators".to_string(),
|
||||
source_namespace: "openshift-marketplace".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology + K8sclient> Score<T> for CertManagerOperatorScore {
|
||||
fn name(&self) -> String {
|
||||
"CertManagerOperatorScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
let metadata = ObjectMeta {
|
||||
name: Some("cert-manager".to_string()),
|
||||
namespace: Some(self.namespace.clone()),
|
||||
..ObjectMeta::default()
|
||||
};
|
||||
|
||||
let spec = SubscriptionSpec {
|
||||
channel: Some(self.channel.clone()),
|
||||
config: None,
|
||||
install_plan_approval: Some(self.install_plan_approval.clone()),
|
||||
name: "cert-manager".to_string(),
|
||||
source: self.source.clone(),
|
||||
source_namespace: self.source_namespace.clone(),
|
||||
starting_csv: None,
|
||||
};
|
||||
|
||||
let subscription = Subscription { metadata, spec };
|
||||
|
||||
K8sResourceScore::single(subscription, Some(self.namespace.clone())).create_interpret()
|
||||
}
|
||||
}
|
||||
76
harmony/src/modules/cert_manager/score_create_cert.rs
Normal file
76
harmony/src/modules/cert_manager/score_create_cert.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_types::id::Id;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
modules::cert_manager::capability::{CertificateManagement, CertificateManagementConfig},
|
||||
score::Score,
|
||||
topology::Topology,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertificateCreationScore {
|
||||
pub cert_name: String,
|
||||
pub issuer_name: String,
|
||||
pub config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
impl<T: Topology + CertificateManagement> Score<T> for CertificateCreationScore {
|
||||
fn name(&self) -> String {
|
||||
"CertificateCreationScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(CertificateCreationInterpret {
|
||||
cert_name: self.cert_name.clone(),
|
||||
issuer_name: self.issuer_name.clone(),
|
||||
config: self.config.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CertificateCreationInterpret {
|
||||
cert_name: String,
|
||||
issuer_name: String,
|
||||
config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + CertificateManagement> Interpret<T> for CertificateCreationInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let _certificate = topology
|
||||
.create_certificate(
|
||||
self.cert_name.clone(),
|
||||
self.issuer_name.clone(),
|
||||
&self.config,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| InterpretError::new(e.to_string()))?;
|
||||
|
||||
Ok(Outcome::success(format!("Installed CertificateManagement")))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Custom("CertificateManagementInterpret")
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
71
harmony/src/modules/cert_manager/score_create_issuer.rs
Normal file
71
harmony/src/modules/cert_manager/score_create_issuer.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_types::id::Id;
|
||||
use log::debug;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
modules::cert_manager::capability::{CertificateManagement, CertificateManagementConfig},
|
||||
score::Score,
|
||||
topology::Topology,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertificateIssuerScore {
|
||||
pub issuer_name: String,
|
||||
pub config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
impl<T: Topology + CertificateManagement> Score<T> for CertificateIssuerScore {
|
||||
fn name(&self) -> String {
|
||||
"CertificateIssuerScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(CertificateIssuerInterpret {
|
||||
config: self.config.clone(),
|
||||
issuer_name: self.issuer_name.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CertificateIssuerInterpret {
|
||||
config: CertificateManagementConfig,
|
||||
issuer_name: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + CertificateManagement> Interpret<T> for CertificateIssuerInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
debug!("issuer name: {}", self.issuer_name.clone());
|
||||
let _cert_issuer = topology
|
||||
.create_issuer(self.issuer_name.clone(), &self.config)
|
||||
.await
|
||||
.map_err(|e| InterpretError::new(e.to_string()))?;
|
||||
|
||||
Ok(Outcome::success(format!("Installed CertificateManagement")))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Custom("CertificateManagementInterpret")
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
66
harmony/src/modules/cert_manager/score_operator.rs
Normal file
66
harmony/src/modules/cert_manager/score_operator.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_types::id::Id;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
modules::cert_manager::capability::{CertificateManagement, CertificateManagementConfig},
|
||||
score::Score,
|
||||
topology::Topology,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct CertificateManagementScore {
|
||||
pub config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
impl<T: Topology + CertificateManagement> Score<T> for CertificateManagementScore {
|
||||
fn name(&self) -> String {
|
||||
"CertificateManagementScore".to_string()
|
||||
}
|
||||
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(CertificateManagementInterpret {
|
||||
config: self.config.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CertificateManagementInterpret {
|
||||
config: CertificateManagementConfig,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + CertificateManagement> Interpret<T> for CertificateManagementInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
topology
|
||||
.ensure_certificate_management_ready(&self.config)
|
||||
.await
|
||||
.map_err(|e| InterpretError::new(e.to_string()))?;
|
||||
|
||||
Ok(Outcome::success(format!("CertificateManagement is ready")))
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Custom("CertificateManagementInterpret")
|
||||
}
|
||||
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::debug;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
config::HARMONY_DATA_DIR,
|
||||
data::Version,
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{Docker, Topology},
|
||||
};
|
||||
use harmony_types::id::Id;
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct DockerInstallationScore {
|
||||
pub installation_path: PathBuf,
|
||||
}
|
||||
|
||||
impl Default for DockerInstallationScore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
installation_path: HARMONY_DATA_DIR.join("docker"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology + Docker> Score<T> for DockerInstallationScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(DockerInstallationInterpret {
|
||||
score: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"DockerInstallationScore".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DockerInstallationInterpret {
|
||||
score: DockerInstallationScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + Docker> Interpret<T> for DockerInstallationInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
_topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let docker = harmony_tools::Docker::new(self.score.installation_path.clone());
|
||||
|
||||
match docker.ensure_installed().await {
|
||||
Ok(_) => {
|
||||
let msg = "Docker is installed and ready".to_string();
|
||||
debug!("{msg}");
|
||||
Ok(Outcome::success(msg))
|
||||
}
|
||||
Err(msg) => Err(InterpretError::new(format!(
|
||||
"failed to ensure docker is installed : {msg}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Custom("DockerInstallation")
|
||||
}
|
||||
fn get_version(&self) -> Version {
|
||||
todo!()
|
||||
}
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
todo!()
|
||||
}
|
||||
fn get_children(&self) -> Vec<Id> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use harmony_tools::K3d;
|
||||
use log::debug;
|
||||
use serde::Serialize;
|
||||
|
||||
@@ -11,7 +10,7 @@ use crate::{
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{Docker, Topology},
|
||||
topology::Topology,
|
||||
};
|
||||
use harmony_types::id::Id;
|
||||
|
||||
@@ -30,7 +29,7 @@ impl Default for K3DInstallationScore {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology + Docker> Score<T> for K3DInstallationScore {
|
||||
impl<T: Topology> Score<T> for K3DInstallationScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(K3dInstallationInterpret {
|
||||
score: self.clone(),
|
||||
@@ -48,25 +47,19 @@ pub struct K3dInstallationInterpret {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + Docker> Interpret<T> for K3dInstallationInterpret {
|
||||
impl<T: Topology> Interpret<T> for K3dInstallationInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &T,
|
||||
_topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let k3d = K3d::new(
|
||||
let k3d = k3d_rs::K3d::new(
|
||||
self.score.installation_path.clone(),
|
||||
Some(self.score.cluster_name.clone()),
|
||||
);
|
||||
|
||||
Docker::ensure_installed(topology)
|
||||
.await
|
||||
.map_err(|e| InterpretError::new(format!("Docker requirement for k3d failed: {e}")))?;
|
||||
|
||||
match k3d.ensure_installed().await {
|
||||
Ok(_client) => {
|
||||
// Ensure Docker is also ready as k3d depends on it
|
||||
|
||||
let msg = format!("k3d cluster '{}' installed ", self.score.cluster_name);
|
||||
debug!("{msg}");
|
||||
Ok(Outcome::success(msg))
|
||||
|
||||
@@ -4,7 +4,6 @@ pub mod brocade;
|
||||
pub mod cert_manager;
|
||||
pub mod dhcp;
|
||||
pub mod dns;
|
||||
pub mod docker;
|
||||
pub mod dummy;
|
||||
pub mod helm;
|
||||
pub mod http;
|
||||
|
||||
@@ -1,326 +0,0 @@
|
||||
use crate::downloadable_asset::DownloadableAsset;
|
||||
use inquire::Select;
|
||||
use log::{debug, error, info, trace, warn};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use url::Url;
|
||||
|
||||
pub struct Docker {
|
||||
base_dir: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum DockerVariant {
|
||||
Standard,
|
||||
Rootless,
|
||||
Manual,
|
||||
}
|
||||
|
||||
impl fmt::Display for DockerVariant {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
DockerVariant::Standard => write!(f, "Standard Docker (requires sudo)"),
|
||||
DockerVariant::Rootless => write!(f, "Rootless Docker (no sudo required)"),
|
||||
DockerVariant::Manual => {
|
||||
write!(f, "Exit and install manually (Docker or podman-docker)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Docker {
|
||||
pub fn new(base_dir: PathBuf) -> Self {
|
||||
Self { base_dir }
|
||||
}
|
||||
|
||||
/// Provides the DOCKER_HOST and DOCKER_SOCK env vars for local usage.
|
||||
///
|
||||
/// If a rootless Docker installation is detected in the user's home directory,
|
||||
/// it returns the appropriate `DOCKER_HOST` pointing to the user's Docker socket.
|
||||
/// Otherwise, it returns an empty HashMap, assuming the standard system-wide
|
||||
/// Docker installation is used.
|
||||
pub fn get_docker_env(&self) -> HashMap<String, String> {
|
||||
let mut env = HashMap::new();
|
||||
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
let rootless_sock = PathBuf::from(&home).join(".docker/run/docker.sock");
|
||||
let rootless_bin = PathBuf::from(&home).join("bin/docker");
|
||||
|
||||
if rootless_bin.exists() && rootless_sock.exists() {
|
||||
let docker_host = format!("unix://{}", rootless_sock.display());
|
||||
debug!(
|
||||
"Detected rootless Docker, setting DOCKER_HOST={}",
|
||||
docker_host
|
||||
);
|
||||
env.insert("DOCKER_HOST".to_string(), docker_host);
|
||||
}
|
||||
}
|
||||
|
||||
env
|
||||
}
|
||||
|
||||
/// Gets the path to the docker binary
|
||||
pub fn get_bin_path(&self) -> PathBuf {
|
||||
// Check standard PATH first
|
||||
if let Ok(path) = std::process::Command::new("which")
|
||||
.arg("docker")
|
||||
.output()
|
||||
.map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim()))
|
||||
{
|
||||
if path.exists() {
|
||||
debug!("Found Docker in PATH: {:?}", path);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
// Check common rootless location
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
let rootless_path = PathBuf::from(home).join("bin/docker");
|
||||
if rootless_path.exists() {
|
||||
debug!("Found rootless Docker at: {:?}", rootless_path);
|
||||
return rootless_path;
|
||||
}
|
||||
}
|
||||
|
||||
debug!("Docker not found in PATH or rootless location, using 'docker' from PATH");
|
||||
PathBuf::from("docker")
|
||||
}
|
||||
|
||||
/// Checks if Docker is installed and the daemon is responsive.
|
||||
pub fn is_installed(&self) -> bool {
|
||||
trace!("Checking if Docker is installed and responsive");
|
||||
|
||||
self.command()
|
||||
.arg("info")
|
||||
.output()
|
||||
.map(|output| {
|
||||
if output.status.success() {
|
||||
trace!("Docker daemon is responsive");
|
||||
true
|
||||
} else {
|
||||
trace!(
|
||||
"Docker daemon check failed with status: {:?}",
|
||||
output.status
|
||||
);
|
||||
false
|
||||
}
|
||||
})
|
||||
.map_err(|e| {
|
||||
trace!("Failed to execute Docker daemon check: {}", e);
|
||||
e
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Prompts the user to choose an installation method
|
||||
fn prompt_for_installation(&self) -> DockerVariant {
|
||||
let options = vec![
|
||||
DockerVariant::Standard,
|
||||
DockerVariant::Rootless,
|
||||
DockerVariant::Manual,
|
||||
];
|
||||
|
||||
Select::new(
|
||||
"Docker binary was not found. How would you like to proceed?",
|
||||
options,
|
||||
)
|
||||
.with_help_message("Standard requires sudo. Rootless runs in user space.")
|
||||
.prompt()
|
||||
.unwrap_or(DockerVariant::Manual)
|
||||
}
|
||||
|
||||
/// Installs docker using the official shell script
|
||||
pub async fn install(&self, variant: DockerVariant) -> Result<(), String> {
|
||||
let (script_url, script_name, use_sudo) = match variant {
|
||||
DockerVariant::Standard => ("https://get.docker.com", "get-docker.sh", true),
|
||||
DockerVariant::Rootless => (
|
||||
"https://get.docker.com/rootless",
|
||||
"get-docker-rootless.sh",
|
||||
false,
|
||||
),
|
||||
DockerVariant::Manual => return Err("Manual installation selected".to_string()),
|
||||
};
|
||||
|
||||
info!("Installing {}...", variant);
|
||||
debug!("Downloading installation script from: {}", script_url);
|
||||
|
||||
// Download the installation script
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(script_url).map_err(|e| {
|
||||
error!("Failed to parse installation script URL: {}", e);
|
||||
format!("Failed to parse installation script URL: {}", e)
|
||||
})?,
|
||||
file_name: script_name.to_string(),
|
||||
checksum: None,
|
||||
};
|
||||
|
||||
let downloaded_script = asset
|
||||
.download_to_path(self.base_dir.join("scripts"))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to download installation script: {}", e);
|
||||
format!("Failed to download installation script: {}", e)
|
||||
})?;
|
||||
|
||||
debug!("Installation script downloaded to: {:?}", downloaded_script);
|
||||
|
||||
// Execute the installation script
|
||||
let mut cmd = std::process::Command::new("sh");
|
||||
if use_sudo {
|
||||
cmd.arg("sudo").arg("sh");
|
||||
}
|
||||
cmd.arg(&downloaded_script);
|
||||
|
||||
debug!("Executing installation command: {:?}", cmd);
|
||||
|
||||
let status = cmd.status().map_err(|e| {
|
||||
error!("Failed to execute docker installation script: {}", e);
|
||||
format!("Failed to execute docker installation script: {}", e)
|
||||
})?;
|
||||
|
||||
if status.success() {
|
||||
info!("{} installed successfully", variant);
|
||||
if variant == DockerVariant::Rootless {
|
||||
info!("Running rootless setup tool to install dependencies and start service...");
|
||||
let mut setup_cmd = std::process::Command::new("sh");
|
||||
|
||||
// Set PATH to include ~/bin where the script was likely installed
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
let bin_path = format!("{}/bin", home);
|
||||
if let Ok(current_path) = std::env::var("PATH") {
|
||||
setup_cmd.env("PATH", format!("{}:{}", bin_path, current_path));
|
||||
}
|
||||
setup_cmd.arg(format!("{}/bin/dockerd-rootless-setuptool.sh", home));
|
||||
} else {
|
||||
setup_cmd.arg("dockerd-rootless-setuptool.sh");
|
||||
}
|
||||
|
||||
setup_cmd.arg("install");
|
||||
|
||||
debug!("Executing rootless setup command: {:?}", setup_cmd);
|
||||
let setup_status = setup_cmd.status().map_err(|e| {
|
||||
error!("Failed to execute rootless setup tool: {}", e);
|
||||
format!("Failed to execute rootless setup tool: {}", e)
|
||||
})?;
|
||||
|
||||
if !setup_status.success() {
|
||||
warn!("Rootless setup tool finished with non-zero exit code. You may need to install 'uidmap' or start the service manually.");
|
||||
}
|
||||
|
||||
warn!("Please follow the instructions above to finish rootless setup (environment variables).");
|
||||
}
|
||||
|
||||
// Validate the installation by running hello-world
|
||||
self.validate_installation()?;
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
error!(
|
||||
"{} installation script failed with exit code: {:?} \n\nOutput:\n{:?}",
|
||||
variant,
|
||||
status.code(),
|
||||
cmd.output(),
|
||||
);
|
||||
Err(format!("{} installation script failed", variant))
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates the Docker installation by running a test container.
|
||||
///
|
||||
/// This method runs `docker run --rm hello-world` to verify that Docker
|
||||
/// is properly installed and functional.
|
||||
fn validate_installation(&self) -> Result<(), String> {
|
||||
info!("Validating Docker installation by running hello-world container...");
|
||||
|
||||
let output = self
|
||||
.command()
|
||||
.args(["run", "--rm", "hello-world"])
|
||||
.output()
|
||||
.map_err(|e| {
|
||||
error!("Failed to execute hello-world validation: {}", e);
|
||||
format!("Failed to execute hello-world validation: {}", e)
|
||||
})?;
|
||||
|
||||
if output.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if stdout.contains("Hello from Docker!") {
|
||||
info!("Docker installation validated successfully");
|
||||
trace!("Validation output: {}", stdout);
|
||||
Ok(())
|
||||
} else {
|
||||
warn!("Hello-world container ran but expected output not found");
|
||||
debug!("Output was: {}", stdout);
|
||||
Err("Docker validation failed: unexpected output from hello-world".to_string())
|
||||
}
|
||||
} else {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
error!(
|
||||
"Hello-world validation failed with exit code: {:?}",
|
||||
output.status.code()
|
||||
);
|
||||
debug!("Validation stderr: {}", stderr);
|
||||
if !stderr.is_empty() {
|
||||
Err(format!("Docker validation failed: {}", stderr.trim()))
|
||||
} else {
|
||||
Err(
|
||||
"Docker validation failed: hello-world container did not run successfully"
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures docker is installed, prompting if necessary
|
||||
pub async fn ensure_installed(&self) -> Result<(), String> {
|
||||
if self.is_installed() {
|
||||
debug!("Docker is already installed at: {:?}", self.get_bin_path());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
debug!("Docker is not installed, prompting for installation method");
|
||||
match self.prompt_for_installation() {
|
||||
DockerVariant::Manual => {
|
||||
info!("User chose manual installation");
|
||||
Err("Docker installation cancelled by user. Please install docker or podman-docker manually.".to_string())
|
||||
}
|
||||
variant => self.install(variant).await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a pre-configured Command for running Docker commands.
|
||||
///
|
||||
/// The returned Command is set up with:
|
||||
/// - The correct Docker binary path (handles rootless installations)
|
||||
/// - Appropriate environment variables (e.g., DOCKER_HOST for rootless)
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use harmony_tools::Docker;
|
||||
/// # use std::path::PathBuf;
|
||||
/// # let docker = Docker::new(PathBuf::from("."));
|
||||
/// let mut cmd = docker.command();
|
||||
/// cmd.args(["ps", "-a"]);
|
||||
/// // Now cmd is ready to be executed
|
||||
/// ```
|
||||
pub fn command(&self) -> std::process::Command {
|
||||
let bin_path = self.get_bin_path();
|
||||
trace!("Creating Docker command with binary: {:?}", bin_path);
|
||||
|
||||
let mut cmd = std::process::Command::new(&bin_path);
|
||||
|
||||
// Add Docker-specific environment variables
|
||||
let env = self.get_docker_env();
|
||||
if !env.is_empty() {
|
||||
trace!("Setting Docker environment variables: {:?}", env);
|
||||
for (key, value) in env {
|
||||
cmd.env(key, value);
|
||||
}
|
||||
} else {
|
||||
trace!("No Docker-specific environment variables to set");
|
||||
}
|
||||
|
||||
cmd
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
mod docker;
|
||||
mod downloadable_asset;
|
||||
mod k3d;
|
||||
pub use docker::*;
|
||||
use downloadable_asset::*;
|
||||
pub use k3d::*;
|
||||
@@ -1,6 +1,5 @@
|
||||
[package]
|
||||
name = "harmony_tools"
|
||||
description = "Install tools such as k3d, docker and more"
|
||||
name = "k3d-rs"
|
||||
edition = "2021"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
@@ -17,7 +16,6 @@ url.workspace = true
|
||||
sha2 = "0.10.8"
|
||||
futures-util = "0.3.31"
|
||||
kube.workspace = true
|
||||
inquire.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = { workspace = true }
|
||||
@@ -39,20 +39,11 @@ const CHECKSUM_FAILED_MSG: &str = "Downloaded file failed checksum verification"
|
||||
pub(crate) struct DownloadableAsset {
|
||||
pub(crate) url: Url,
|
||||
pub(crate) file_name: String,
|
||||
pub(crate) checksum: Option<String>,
|
||||
pub(crate) checksum: String,
|
||||
}
|
||||
|
||||
impl DownloadableAsset {
|
||||
fn verify_checksum(&self, file: PathBuf) -> bool {
|
||||
// Skip verification if no checksum is provided
|
||||
let expected_checksum = match &self.checksum {
|
||||
Some(checksum) => checksum,
|
||||
None => {
|
||||
debug!("No checksum provided, skipping verification");
|
||||
return file.exists();
|
||||
}
|
||||
};
|
||||
|
||||
if !file.exists() {
|
||||
debug!("File does not exist: {:?}", file);
|
||||
return false;
|
||||
@@ -85,10 +76,10 @@ impl DownloadableAsset {
|
||||
let result = hasher.finalize();
|
||||
let calculated_hash = format!("{:x}", result);
|
||||
|
||||
debug!("Expected checksum: {}", expected_checksum);
|
||||
debug!("Expected checksum: {}", self.checksum);
|
||||
debug!("Calculated checksum: {}", calculated_hash);
|
||||
|
||||
calculated_hash == *expected_checksum
|
||||
calculated_hash == self.checksum
|
||||
}
|
||||
|
||||
/// Downloads the asset to the specified directory, verifying its checksum.
|
||||
@@ -160,8 +151,7 @@ impl DownloadableAsset {
|
||||
file.flush().await.expect("Failed to flush file");
|
||||
drop(file);
|
||||
|
||||
// Only verify checksum if one was provided
|
||||
if self.checksum.is_some() && !self.verify_checksum(target_file_path.clone()) {
|
||||
if !self.verify_checksum(target_file_path.clone()) {
|
||||
return Err(CHECKSUM_FAILED_MSG.to_string());
|
||||
}
|
||||
|
||||
@@ -212,7 +202,7 @@ mod tests {
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: Some(TEST_CONTENT_HASH.to_string()),
|
||||
checksum: TEST_CONTENT_HASH.to_string(),
|
||||
};
|
||||
|
||||
let result = asset
|
||||
@@ -236,7 +226,7 @@ mod tests {
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: Some(TEST_CONTENT_HASH.to_string()),
|
||||
checksum: TEST_CONTENT_HASH.to_string(),
|
||||
};
|
||||
|
||||
let target_file_path = folder.join(&asset.file_name);
|
||||
@@ -258,7 +248,7 @@ mod tests {
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: Some(TEST_CONTENT_HASH.to_string()),
|
||||
checksum: TEST_CONTENT_HASH.to_string(),
|
||||
};
|
||||
|
||||
let result = asset.download_to_path(folder.join("error")).await;
|
||||
@@ -279,7 +269,7 @@ mod tests {
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: Some(TEST_CONTENT_HASH.to_string()),
|
||||
checksum: TEST_CONTENT_HASH.to_string(),
|
||||
};
|
||||
|
||||
let join_handle =
|
||||
@@ -303,58 +293,11 @@ mod tests {
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/specific/path.txt").to_string()).unwrap(),
|
||||
file_name: "path.txt".to_string(),
|
||||
checksum: Some(TEST_CONTENT_HASH.to_string()),
|
||||
checksum: TEST_CONTENT_HASH.to_string(),
|
||||
};
|
||||
|
||||
let result = asset.download_to_path(folder).await.unwrap();
|
||||
let downloaded_content = std::fs::read_to_string(result).unwrap();
|
||||
assert_eq!(downloaded_content, TEST_CONTENT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_download_without_checksum() {
|
||||
let (folder, server) = setup_test();
|
||||
|
||||
server.expect(
|
||||
Expectation::matching(matchers::any())
|
||||
.respond_with(responders::status_code(200).body(TEST_CONTENT)),
|
||||
);
|
||||
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: None,
|
||||
};
|
||||
|
||||
let result = asset
|
||||
.download_to_path(folder.join("no_checksum"))
|
||||
.await
|
||||
.unwrap();
|
||||
let downloaded_content = std::fs::read_to_string(result).unwrap();
|
||||
assert_eq!(downloaded_content, TEST_CONTENT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_download_without_checksum_already_exists() {
|
||||
let (folder, server) = setup_test();
|
||||
|
||||
server.expect(
|
||||
Expectation::matching(matchers::any())
|
||||
.times(0)
|
||||
.respond_with(responders::status_code(200).body(TEST_CONTENT)),
|
||||
);
|
||||
|
||||
let asset = DownloadableAsset {
|
||||
url: Url::parse(&server.url("/test.txt").to_string()).unwrap(),
|
||||
file_name: "test.txt".to_string(),
|
||||
checksum: None,
|
||||
};
|
||||
|
||||
let target_file_path = folder.join(&asset.file_name);
|
||||
std::fs::write(&target_file_path, TEST_CONTENT).unwrap();
|
||||
|
||||
let result = asset.download_to_path(folder).await.unwrap();
|
||||
let content = std::fs::read_to_string(result).unwrap();
|
||||
assert_eq!(content, TEST_CONTENT);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
mod downloadable_asset;
|
||||
use downloadable_asset::*;
|
||||
|
||||
use kube::Client;
|
||||
use log::{debug, info};
|
||||
use std::{ffi::OsStr, path::PathBuf};
|
||||
|
||||
use crate::downloadable_asset::DownloadableAsset;
|
||||
|
||||
const K3D_BIN_FILE_NAME: &str = "k3d";
|
||||
|
||||
pub struct K3d {
|
||||
@@ -77,7 +78,6 @@ impl K3d {
|
||||
|
||||
debug!("Found binary at {} with checksum {}", binary_url, checksum);
|
||||
|
||||
let checksum = Some(checksum);
|
||||
DownloadableAsset {
|
||||
url: binary_url,
|
||||
file_name: K3D_BIN_FILE_NAME.to_string(),
|
||||
@@ -399,7 +399,7 @@ mod test {
|
||||
use regex::Regex;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::{k3d::K3D_BIN_FILE_NAME, K3d};
|
||||
use crate::{K3d, K3D_BIN_FILE_NAME};
|
||||
|
||||
#[tokio::test]
|
||||
async fn k3d_latest_release_should_get_latest() {
|
||||
Reference in New Issue
Block a user