forked from NationTech/harmony
Compare commits
1 Commits
better-cli
...
dev/postgr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b8525fe05 |
28
.gitignore
vendored
28
.gitignore
vendored
@@ -1,25 +1,3 @@
|
||||
### General ###
|
||||
private_repos/
|
||||
|
||||
### Harmony ###
|
||||
harmony.log
|
||||
|
||||
### Helm ###
|
||||
# Chart dependencies
|
||||
**/charts/*.tgz
|
||||
|
||||
### Rust ###
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
target
|
||||
private_repos
|
||||
log/
|
||||
|
||||
145
Cargo.lock
generated
145
Cargo.lock
generated
@@ -650,19 +650,6 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e09ced7ebbccb63b4c65413d821f2e00ce54c5ca4514ddc6b3c892fdbcbc69d"
|
||||
dependencies = [
|
||||
"encode_unicode",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"unicode-width 0.2.0",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.9.6"
|
||||
@@ -1150,12 +1137,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encode_unicode"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
@@ -1370,11 +1351,20 @@ dependencies = [
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "example-postgres"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"harmony",
|
||||
"serde",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "example-rust"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"env_logger",
|
||||
"harmony",
|
||||
"harmony_cli",
|
||||
@@ -1447,18 +1437,6 @@ version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||
|
||||
[[package]]
|
||||
name = "filetime"
|
||||
version = "0.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35c0522e981e68cbfa8c3f978441a5f34b30b96e146b33cd3359176b50fe8586"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"libredox",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.2"
|
||||
@@ -1758,8 +1736,6 @@ name = "harmony"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"bollard",
|
||||
"chrono",
|
||||
"cidr",
|
||||
"convert_case",
|
||||
@@ -1776,6 +1752,7 @@ dependencies = [
|
||||
"helm-wrapper-rs",
|
||||
"hex",
|
||||
"http 1.3.1",
|
||||
"inquire",
|
||||
"k3d-rs",
|
||||
"k8s-openapi",
|
||||
"kube",
|
||||
@@ -1783,10 +1760,8 @@ dependencies = [
|
||||
"libredfish",
|
||||
"log",
|
||||
"non-blank-string-rs",
|
||||
"once_cell",
|
||||
"opnsense-config",
|
||||
"opnsense-config-xml",
|
||||
"pretty_assertions",
|
||||
"rand 0.9.1",
|
||||
"reqwest 0.11.27",
|
||||
"russh",
|
||||
@@ -1795,14 +1770,11 @@ dependencies = [
|
||||
"serde",
|
||||
"serde-value",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"serde_yaml",
|
||||
"similar",
|
||||
"strum 0.27.1",
|
||||
"tar",
|
||||
"temp-dir",
|
||||
"temp-file",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"url",
|
||||
@@ -1815,15 +1787,10 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"assert_cmd",
|
||||
"clap",
|
||||
"console",
|
||||
"env_logger",
|
||||
"harmony",
|
||||
"harmony_tui",
|
||||
"indicatif",
|
||||
"indicatif-log-bridge",
|
||||
"inquire",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
@@ -1834,16 +1801,10 @@ dependencies = [
|
||||
"bollard",
|
||||
"cargo_metadata",
|
||||
"clap",
|
||||
"console",
|
||||
"current_platform",
|
||||
"env_logger",
|
||||
"futures-util",
|
||||
"harmony_cli",
|
||||
"indicatif",
|
||||
"indicatif-log-bridge",
|
||||
"lazy_static",
|
||||
"log",
|
||||
"once_cell",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
]
|
||||
@@ -2439,29 +2400,6 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indicatif"
|
||||
version = "0.18.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "70a646d946d06bedbbc4cac4c218acf4bbf2d87757a784857025f4d447e4e1cd"
|
||||
dependencies = [
|
||||
"console",
|
||||
"portable-atomic",
|
||||
"unicode-width 0.2.0",
|
||||
"unit-prefix",
|
||||
"web-time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indicatif-log-bridge"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63703cf9069b85dbe6fe26e1c5230d013dee99d3559cd3d02ba39e099ef7ab02"
|
||||
dependencies = [
|
||||
"indicatif",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indoc"
|
||||
version = "2.0.6"
|
||||
@@ -2797,7 +2735,6 @@ checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638"
|
||||
dependencies = [
|
||||
"bitflags 2.9.1",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4152,18 +4089,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "schemars"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1375ba8ef45a6f15d83fa8748f1079428295d403d6ea991d09ab100155fbc06d"
|
||||
dependencies = [
|
||||
"dyn-clone",
|
||||
"ref-cast",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
@@ -4364,36 +4289,22 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_with"
|
||||
version = "3.14.0"
|
||||
version = "3.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2c45cd61fefa9db6f254525d46e392b852e0e61d9a1fd36e5bd183450a556d5"
|
||||
checksum = "bf65a400f8f66fb7b0552869ad70157166676db75ed8181f8104ea91cf9d0b42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"hex",
|
||||
"indexmap 1.9.3",
|
||||
"indexmap 2.10.0",
|
||||
"schemars 0.9.0",
|
||||
"schemars 1.0.3",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
"serde_with_macros",
|
||||
"time",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_with_macros"
|
||||
version = "3.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de90945e6565ce0d9a25098082ed4ee4002e047cb59892c318d66821e14bb30f"
|
||||
dependencies = [
|
||||
"darling",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_yaml"
|
||||
version = "0.9.34+deprecated"
|
||||
@@ -4766,17 +4677,6 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
|
||||
|
||||
[[package]]
|
||||
name = "tar"
|
||||
version = "0.4.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
|
||||
dependencies = [
|
||||
"filetime",
|
||||
"libc",
|
||||
"xattr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "temp-dir"
|
||||
version = "0.1.16"
|
||||
@@ -4917,6 +4817,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio 1.0.4",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
@@ -5234,12 +5135,6 @@ version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
|
||||
|
||||
[[package]]
|
||||
name = "unit-prefix"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "323402cff2dd658f39ca17c789b502021b3f18707c91cdf22e3838e1b4023817"
|
||||
|
||||
[[package]]
|
||||
name = "universal-hash"
|
||||
version = "0.5.1"
|
||||
@@ -5828,16 +5723,6 @@ dependencies = [
|
||||
"tap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xattr"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af3a19837351dc82ba89f8a125e22a3c475f05aba604acc023d62b2739ae2909"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rustix 1.0.7",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xml-rs"
|
||||
version = "0.8.26"
|
||||
|
||||
@@ -52,7 +52,3 @@ convert_case = "0.8"
|
||||
chrono = "0.4"
|
||||
similar = "2"
|
||||
uuid = { version = "1.11", features = ["v4", "fast-rng", "macro-diagnostics"] }
|
||||
pretty_assertions = "1.4.1"
|
||||
bollard = "0.19.1"
|
||||
base64 = "0.22.1"
|
||||
tar = "0.4.44"
|
||||
|
||||
@@ -10,7 +10,7 @@ use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
http::StaticFilesHttpScore,
|
||||
http::HttpScore,
|
||||
ipxe::IpxeScore,
|
||||
okd::{
|
||||
bootstrap_dhcp::OKDBootstrapDhcpScore,
|
||||
@@ -126,7 +126,7 @@ async fn main() {
|
||||
harmony::modules::okd::load_balancer::OKDLoadBalancerScore::new(&topology);
|
||||
|
||||
let tftp_score = TftpScore::new(Url::LocalFolder("./data/watchguard/tftpboot".to_string()));
|
||||
let http_score = StaticFilesHttpScore::new(Url::LocalFolder(
|
||||
let http_score = HttpScore::new(Url::LocalFolder(
|
||||
"./data/watchguard/pxe-http-files".to_string(),
|
||||
));
|
||||
let ipxe_score = IpxeScore::new();
|
||||
|
||||
@@ -14,7 +14,6 @@ async fn main() {
|
||||
|
||||
maestro.register_all(vec![Box::new(NtfyScore {
|
||||
namespace: "monitoring".to_string(),
|
||||
host: "localhost".to_string(),
|
||||
})]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ use harmony::{
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
dummy::{ErrorScore, PanicScore, SuccessScore},
|
||||
http::StaticFilesHttpScore,
|
||||
http::HttpScore,
|
||||
okd::{dhcp::OKDDhcpScore, dns::OKDDnsScore, load_balancer::OKDLoadBalancerScore},
|
||||
opnsense::OPNsenseShellCommandScore,
|
||||
tftp::TftpScore,
|
||||
@@ -81,7 +81,7 @@ async fn main() {
|
||||
let load_balancer_score = OKDLoadBalancerScore::new(&topology);
|
||||
|
||||
let tftp_score = TftpScore::new(Url::LocalFolder("./data/watchguard/tftpboot".to_string()));
|
||||
let http_score = StaticFilesHttpScore::new(Url::LocalFolder(
|
||||
let http_score = HttpScore::new(Url::LocalFolder(
|
||||
"./data/watchguard/pxe-http-files".to_string(),
|
||||
));
|
||||
let mut maestro = Maestro::initialize(inventory, topology).await.unwrap();
|
||||
|
||||
10
examples/postgres/Cargo.toml
Normal file
10
examples/postgres/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "example-postgres"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
async-trait = "0.1.80"
|
||||
84
examples/postgres/src/main.rs
Normal file
84
examples/postgres/src/main.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony::{
|
||||
data::{PostgresDatabase, PostgresUser},
|
||||
interpret::InterpretError,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::postgres::PostgresScore,
|
||||
topology::{PostgresServer, Topology},
|
||||
};
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct MockTopology;
|
||||
|
||||
#[async_trait]
|
||||
impl Topology for MockTopology {
|
||||
fn name(&self) -> &str {
|
||||
"MockTopology"
|
||||
}
|
||||
|
||||
async fn ensure_ready(&self) -> Result<harmony::interpret::Outcome, InterpretError> {
|
||||
Ok(harmony::interpret::Outcome::new(
|
||||
harmony::interpret::InterpretStatus::SUCCESS,
|
||||
"Mock topology is always ready".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PostgresServer for MockTopology {
|
||||
async fn ensure_users_exist(&self, users: Vec<PostgresUser>) -> Result<(), InterpretError> {
|
||||
println!("Ensuring users exist:");
|
||||
for user in users {
|
||||
println!(" - {}: {}", user.name, user.password);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_databases_exist(
|
||||
&self,
|
||||
databases: Vec<PostgresDatabase>,
|
||||
) -> Result<(), InterpretError> {
|
||||
println!("Ensuring databases exist:");
|
||||
for db in databases {
|
||||
println!(" - {}: owner={}", db.name, db.owner);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let users = vec![
|
||||
PostgresUser {
|
||||
name: "admin".to_string(),
|
||||
password: "password".to_string(),
|
||||
},
|
||||
PostgresUser {
|
||||
name: "user".to_string(),
|
||||
password: "password".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let databases = vec![
|
||||
PostgresDatabase {
|
||||
name: "app_db".to_string(),
|
||||
owner: "admin".to_string(),
|
||||
},
|
||||
PostgresDatabase {
|
||||
name: "user_db".to_string(),
|
||||
owner: "user".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let postgres_score = PostgresScore::new(users, databases);
|
||||
|
||||
let inventory = Inventory::empty();
|
||||
let topology = MockTopology;
|
||||
let maestro = Maestro::new(inventory, topology);
|
||||
|
||||
maestro.interpret(Box::new(postgres_score)).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
3
examples/rust/.gitignore
vendored
3
examples/rust/.gitignore
vendored
@@ -1,3 +0,0 @@
|
||||
Dockerfile.harmony
|
||||
.harmony_generated
|
||||
harmony
|
||||
@@ -12,4 +12,3 @@ tokio = { workspace = true }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
base64.workspace = true
|
||||
|
||||
@@ -1,46 +1,20 @@
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::application::{
|
||||
ApplicationScore, RustWebFramework, RustWebapp,
|
||||
features::{ContinuousDelivery, Monitoring},
|
||||
},
|
||||
modules::application::{RustWebappScore, features::ContinuousDelivery},
|
||||
topology::{K8sAnywhereTopology, Url},
|
||||
};
|
||||
use harmony_cli::cli_logger;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let cli_logger_handle = cli_logger::init();
|
||||
|
||||
let topology = K8sAnywhereTopology::from_env();
|
||||
let mut maestro = Maestro::initialize(Inventory::autoload(), topology)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let application = Arc::new(RustWebapp {
|
||||
name: "harmony-example-rust-webapp".to_string(),
|
||||
let app = RustWebappScore {
|
||||
name: "Example Rust Webapp".to_string(),
|
||||
domain: Url::Url(url::Url::parse("https://rustapp.harmony.example.com").unwrap()),
|
||||
project_root: PathBuf::from("./webapp"), // Relative from 'harmony-path' param
|
||||
framework: Some(RustWebFramework::Leptos),
|
||||
});
|
||||
|
||||
let app = ApplicationScore {
|
||||
features: vec![
|
||||
Box::new(ContinuousDelivery {
|
||||
application: application.clone(),
|
||||
}),
|
||||
Box::new(Monitoring {
|
||||
application: application.clone(),
|
||||
}), // TODO: add backups, multisite ha, etc.
|
||||
],
|
||||
application,
|
||||
features: vec![Box::new(ContinuousDelivery {})],
|
||||
};
|
||||
|
||||
let topology = K8sAnywhereTopology::from_env();
|
||||
let mut maestro = Maestro::new(Inventory::autoload(), topology);
|
||||
maestro.register_all(vec![Box::new(app)]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
|
||||
let _ = tokio::try_join!(cli_logger_handle);
|
||||
}
|
||||
|
||||
14
examples/rust/webapp/.gitignore
vendored
14
examples/rust/webapp/.gitignore
vendored
@@ -1,14 +0,0 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
@@ -1,93 +0,0 @@
|
||||
[package]
|
||||
name = "harmony-example-rust-webapp"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
actix-files = { version = "0.6", optional = true }
|
||||
actix-web = { version = "4", optional = true, features = ["macros"] }
|
||||
console_error_panic_hook = "0.1"
|
||||
http = { version = "1.0.0", optional = true }
|
||||
leptos = { version = "0.7.0" }
|
||||
leptos_meta = { version = "0.7.0" }
|
||||
leptos_actix = { version = "0.7.0", optional = true }
|
||||
leptos_router = { version = "0.7.0" }
|
||||
wasm-bindgen = "=0.2.100"
|
||||
|
||||
[features]
|
||||
csr = ["leptos/csr"]
|
||||
hydrate = ["leptos/hydrate"]
|
||||
ssr = [
|
||||
"dep:actix-files",
|
||||
"dep:actix-web",
|
||||
"dep:leptos_actix",
|
||||
"leptos/ssr",
|
||||
"leptos_meta/ssr",
|
||||
"leptos_router/ssr",
|
||||
]
|
||||
|
||||
# Defines a size-optimized profile for the WASM bundle in release mode
|
||||
[profile.wasm-release]
|
||||
inherits = "release"
|
||||
opt-level = 'z'
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
panic = "abort"
|
||||
|
||||
[package.metadata.leptos]
|
||||
# The name used by wasm-bindgen/cargo-leptos for the JS/WASM bundle. Defaults to the crate name
|
||||
output-name = "harmony-example-rust-webapp"
|
||||
# The site root folder is where cargo-leptos generate all output. WARNING: all content of this folder will be erased on a rebuild. Use it in your server setup.
|
||||
site-root = "target/site"
|
||||
# The site-root relative folder where all compiled output (JS, WASM and CSS) is written
|
||||
# Defaults to pkg
|
||||
site-pkg-dir = "pkg"
|
||||
# [Optional] The source CSS file. If it ends with .sass or .scss then it will be compiled by dart-sass into CSS. The CSS is optimized by Lightning CSS before being written to <site-root>/<site-pkg>/app.css
|
||||
style-file = "style/main.scss"
|
||||
# Assets source dir. All files found here will be copied and synchronized to site-root.
|
||||
# The assets-dir cannot have a sub directory with the same name/path as site-pkg-dir.
|
||||
#
|
||||
# Optional. Env: LEPTOS_ASSETS_DIR.
|
||||
assets-dir = "assets"
|
||||
# The IP and port (ex: 127.0.0.1:3000) where the server serves the content. Use it in your server setup.
|
||||
site-addr = "0.0.0.0:3000"
|
||||
# The port to use for automatic reload monitoring
|
||||
reload-port = 3001
|
||||
# [Optional] Command to use when running end2end tests. It will run in the end2end dir.
|
||||
# [Windows] for non-WSL use "npx.cmd playwright test"
|
||||
# This binary name can be checked in Powershell with Get-Command npx
|
||||
end2end-cmd = "npx playwright test"
|
||||
end2end-dir = "end2end"
|
||||
# The browserlist query used for optimizing the CSS.
|
||||
browserquery = "defaults"
|
||||
# The environment Leptos will run in, usually either "DEV" or "PROD"
|
||||
env = "DEV"
|
||||
# The features to use when compiling the bin target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --bin-features
|
||||
bin-features = ["ssr"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the bin target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
bin-default-features = false
|
||||
|
||||
# The features to use when compiling the lib target
|
||||
#
|
||||
# Optional. Can be over-ridden with the command line parameter --lib-features
|
||||
lib-features = ["hydrate"]
|
||||
|
||||
# If the --no-default-features flag should be used when compiling the lib target
|
||||
#
|
||||
# Optional. Defaults to false.
|
||||
lib-default-features = false
|
||||
|
||||
# The profile to use for the lib target when compiling for release
|
||||
#
|
||||
# Optional. Defaults to "release".
|
||||
lib-profile-release = "wasm-release"
|
||||
@@ -1,24 +0,0 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <https://unlicense.org>
|
||||
@@ -1,72 +0,0 @@
|
||||
<picture>
|
||||
<source srcset="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_Solid_White.svg" media="(prefers-color-scheme: dark)">
|
||||
<img src="https://raw.githubusercontent.com/leptos-rs/leptos/main/docs/logos/Leptos_logo_RGB.svg" alt="Leptos Logo">
|
||||
</picture>
|
||||
|
||||
# Leptos Starter Template
|
||||
|
||||
This is a template for use with the [Leptos](https://github.com/leptos-rs/leptos) web framework and the [cargo-leptos](https://github.com/akesson/cargo-leptos) tool.
|
||||
|
||||
## Creating your template repo
|
||||
|
||||
If you don't have `cargo-leptos` installed you can install it with
|
||||
|
||||
`cargo install cargo-leptos --locked`
|
||||
|
||||
Then run
|
||||
|
||||
`cargo leptos new --git leptos-rs/start-actix`
|
||||
|
||||
to generate a new project template (you will be prompted to enter a project name).
|
||||
|
||||
`cd {projectname}`
|
||||
|
||||
to go to your newly created project.
|
||||
|
||||
Of course, you should explore around the project structure, but the best place to start with your application code is in `src/app.rs`.
|
||||
|
||||
## Running your project
|
||||
|
||||
`cargo leptos watch`
|
||||
By default, you can access your local project at `http://localhost:3000`
|
||||
|
||||
## Installing Additional Tools
|
||||
|
||||
By default, `cargo-leptos` uses `nightly` Rust, `cargo-generate`, and `sass`. If you run into any trouble, you may need to install one or more of these tools.
|
||||
|
||||
1. `rustup toolchain install nightly --allow-downgrade` - make sure you have Rust nightly
|
||||
2. `rustup target add wasm32-unknown-unknown` - add the ability to compile Rust to WebAssembly
|
||||
3. `cargo install cargo-generate` - install `cargo-generate` binary (should be installed automatically in future)
|
||||
4. `npm install -g sass` - install `dart-sass` (should be optional in future)
|
||||
|
||||
## Executing a Server on a Remote Machine Without the Toolchain
|
||||
After running a `cargo leptos build --release` the minimum files needed are:
|
||||
|
||||
1. The server binary located in `target/server/release`
|
||||
2. The `site` directory and all files within located in `target/site`
|
||||
|
||||
Copy these files to your remote server. The directory structure should be:
|
||||
```text
|
||||
leptos_start
|
||||
site/
|
||||
```
|
||||
Set the following environment variables (updating for your project as needed):
|
||||
```sh
|
||||
export LEPTOS_OUTPUT_NAME="leptos_start"
|
||||
export LEPTOS_SITE_ROOT="site"
|
||||
export LEPTOS_SITE_PKG_DIR="pkg"
|
||||
export LEPTOS_SITE_ADDR="127.0.0.1:3000"
|
||||
export LEPTOS_RELOAD_PORT="3001"
|
||||
```
|
||||
Finally, run the server binary.
|
||||
|
||||
## Notes about CSR and Trunk:
|
||||
Although it is not recommended, you can also run your project without server integration using the feature `csr` and `trunk serve`:
|
||||
|
||||
`trunk serve --open --features csr`
|
||||
|
||||
This may be useful for integrating external tools which require a static site, e.g. `tauri`.
|
||||
|
||||
## Licensing
|
||||
|
||||
This template itself is released under the Unlicense. You should replace the LICENSE for your own application with an appropriate license if you plan to release it publicly.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 15 KiB |
112
examples/rust/webapp/end2end/package-lock.json
generated
112
examples/rust/webapp/end2end/package-lock.json
generated
@@ -1,112 +0,0 @@
|
||||
{
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.44.1",
|
||||
"@types/node": "^20.12.12",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.44.1.tgz",
|
||||
"integrity": "sha512-1hZ4TNvD5z9VuhNJ/walIjvMVvYkZKf71axoF/uiAqpntQJXpG64dlXhoDXE3OczPuTuvjf/M5KWFg5VAVUS3Q==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.44.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.12.12",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.12.12.tgz",
|
||||
"integrity": "sha512-eWLDGF/FOSPtAvEqeRAQ4C8LSA7M1I7i0ky1I8U7kD1J5ITyW3AsRhQrKVoWf5pFKZ2kILsEGJhsI9r93PYnOw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~5.26.4"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.44.1.tgz",
|
||||
"integrity": "sha512-qr/0UJ5CFAtloI3avF95Y0L1xQo6r3LQArLIg/z/PoGJ6xa+EwzrwO5lpNr/09STxdHuUoP2mvuELJS+hLdtgg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.44.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.44.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.44.1.tgz",
|
||||
"integrity": "sha512-wh0JWtYTrhv1+OSsLPgFzGzt67Y7BE/ZS3jEqgGBlp2ppp1ZDj8c+9IARNW4dwf1poq5MgHreEM2KV/GuR4cFA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.4.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz",
|
||||
"integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "5.26.5",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
|
||||
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "end2end",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.44.1",
|
||||
"@types/node": "^20.12.12",
|
||||
"typescript": "^5.4.5"
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
import { devices, defineConfig } from "@playwright/test";
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// require('dotenv').config();
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
/* Maximum time one test can run for. */
|
||||
timeout: 30 * 1000,
|
||||
expect: {
|
||||
/**
|
||||
* Maximum time expect() should wait for the condition to be met.
|
||||
* For example in `await expect(locator).toHaveText();`
|
||||
*/
|
||||
timeout: 5000,
|
||||
},
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: "html",
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
|
||||
actionTimeout: 0,
|
||||
/* Base URL to use in actions like `await page.goto('/')`. */
|
||||
// baseURL: 'http://localhost:3000',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: "on-first-retry",
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: "chromium",
|
||||
use: {
|
||||
...devices["Desktop Chrome"],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "firefox",
|
||||
use: {
|
||||
...devices["Desktop Firefox"],
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "webkit",
|
||||
use: {
|
||||
...devices["Desktop Safari"],
|
||||
},
|
||||
},
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: {
|
||||
// ...devices['Pixel 5'],
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: {
|
||||
// ...devices['iPhone 12'],
|
||||
// },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: {
|
||||
// channel: 'msedge',
|
||||
// },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: {
|
||||
// channel: 'chrome',
|
||||
// },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Folder for test artifacts such as screenshots, videos, traces, etc. */
|
||||
// outputDir: 'test-results/',
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
// webServer: {
|
||||
// command: 'npm run start',
|
||||
// port: 3000,
|
||||
// },
|
||||
});
|
||||
@@ -1,9 +0,0 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
test("homepage has title and links to intro page", async ({ page }) => {
|
||||
await page.goto("http://localhost:3000/");
|
||||
|
||||
await expect(page).toHaveTitle("Welcome to Leptos");
|
||||
|
||||
await expect(page.locator("h1")).toHaveText("Welcome to Leptos!");
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||
|
||||
/* Projects */
|
||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||
|
||||
/* Language and Environment */
|
||||
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||
|
||||
/* Modules */
|
||||
"module": "commonjs", /* Specify what module code is generated. */
|
||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
||||
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||
|
||||
/* JavaScript Support */
|
||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||
|
||||
/* Emit */
|
||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
||||
// "removeComments": true, /* Disable emitting comments. */
|
||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||
|
||||
/* Interop Constraints */
|
||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||
|
||||
/* Type Checking */
|
||||
"strict": true, /* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||
|
||||
/* Completeness */
|
||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use leptos::prelude::*;
|
||||
use leptos_meta::{provide_meta_context, Stylesheet, Title};
|
||||
use leptos_router::{
|
||||
components::{Route, Router, Routes},
|
||||
StaticSegment, WildcardSegment,
|
||||
};
|
||||
|
||||
#[component]
|
||||
pub fn App() -> impl IntoView {
|
||||
// Provides context that manages stylesheets, titles, meta tags, etc.
|
||||
provide_meta_context();
|
||||
|
||||
view! {
|
||||
// injects a stylesheet into the document <head>
|
||||
// id=leptos means cargo-leptos will hot-reload this stylesheet
|
||||
<Stylesheet id="leptos" href="/pkg/harmony-example-rust-webapp.css"/>
|
||||
|
||||
// sets the document title
|
||||
<Title text="Welcome to Leptos"/>
|
||||
|
||||
// content for this welcome page
|
||||
<Router>
|
||||
<main>
|
||||
<Routes fallback=move || "Not found.">
|
||||
<Route path=StaticSegment("") view=HomePage/>
|
||||
<Route path=WildcardSegment("any") view=NotFound/>
|
||||
</Routes>
|
||||
</main>
|
||||
</Router>
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders the home page of your application.
|
||||
#[component]
|
||||
fn HomePage() -> impl IntoView {
|
||||
// Creates a reactive value to update the button
|
||||
let count = RwSignal::new(0);
|
||||
let on_click = move |_| *count.write() += 1;
|
||||
|
||||
view! {
|
||||
<h1>"Welcome to Leptos!"</h1>
|
||||
<button on:click=on_click>"Click Me: " {count}</button>
|
||||
}
|
||||
}
|
||||
|
||||
/// 404 - Not Found
|
||||
#[component]
|
||||
fn NotFound() -> impl IntoView {
|
||||
// set an HTTP status code 404
|
||||
// this is feature gated because it can only be done during
|
||||
// initial server-side rendering
|
||||
// if you navigate to the 404 page subsequently, the status
|
||||
// code will not be set because there is not a new HTTP request
|
||||
// to the server
|
||||
#[cfg(feature = "ssr")]
|
||||
{
|
||||
// this can be done inline because it's synchronous
|
||||
// if it were async, we'd use a server function
|
||||
let resp = expect_context::<leptos_actix::ResponseOptions>();
|
||||
resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
view! {
|
||||
<h1>"Not Found"</h1>
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
pub mod app;
|
||||
|
||||
#[cfg(feature = "hydrate")]
|
||||
#[wasm_bindgen::prelude::wasm_bindgen]
|
||||
pub fn hydrate() {
|
||||
use app::*;
|
||||
console_error_panic_hook::set_once();
|
||||
leptos::mount::hydrate_body(App);
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#[cfg(feature = "ssr")]
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
use actix_files::Files;
|
||||
use actix_web::*;
|
||||
use leptos::prelude::*;
|
||||
use leptos::config::get_configuration;
|
||||
use leptos_meta::MetaTags;
|
||||
use leptos_actix::{generate_route_list, LeptosRoutes};
|
||||
use harmony_example_rust_webapp::app::*;
|
||||
|
||||
let conf = get_configuration(None).unwrap();
|
||||
let addr = conf.leptos_options.site_addr;
|
||||
|
||||
HttpServer::new(move || {
|
||||
// Generate the list of routes in your Leptos App
|
||||
let routes = generate_route_list(App);
|
||||
let leptos_options = &conf.leptos_options;
|
||||
let site_root = leptos_options.site_root.clone().to_string();
|
||||
|
||||
println!("listening on http://{}", &addr);
|
||||
|
||||
App::new()
|
||||
// serve JS/WASM/CSS from `pkg`
|
||||
.service(Files::new("/pkg", format!("{site_root}/pkg")))
|
||||
// serve other assets from the `assets` directory
|
||||
.service(Files::new("/assets", &site_root))
|
||||
// serve the favicon from /favicon.ico
|
||||
.service(favicon)
|
||||
.leptos_routes(routes, {
|
||||
let leptos_options = leptos_options.clone();
|
||||
move || {
|
||||
view! {
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<AutoReload options=leptos_options.clone() />
|
||||
<HydrationScripts options=leptos_options.clone()/>
|
||||
<MetaTags/>
|
||||
</head>
|
||||
<body>
|
||||
<App/>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
}
|
||||
})
|
||||
.app_data(web::Data::new(leptos_options.to_owned()))
|
||||
//.wrap(middleware::Compress::default())
|
||||
})
|
||||
.bind(&addr)?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssr")]
|
||||
#[actix_web::get("favicon.ico")]
|
||||
async fn favicon(
|
||||
leptos_options: actix_web::web::Data<leptos::config::LeptosOptions>,
|
||||
) -> actix_web::Result<actix_files::NamedFile> {
|
||||
let leptos_options = leptos_options.into_inner();
|
||||
let site_root = &leptos_options.site_root;
|
||||
Ok(actix_files::NamedFile::open(format!(
|
||||
"{site_root}/favicon.ico"
|
||||
))?)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "ssr", feature = "csr")))]
|
||||
pub fn main() {
|
||||
// no client-side main function
|
||||
// unless we want this to work with e.g., Trunk for pure client-side testing
|
||||
// see lib.rs for hydration function instead
|
||||
// see optional feature `csr` instead
|
||||
}
|
||||
|
||||
#[cfg(all(not(feature = "ssr"), feature = "csr"))]
|
||||
pub fn main() {
|
||||
// a client-side main function is required for using `trunk serve`
|
||||
// prefer using `cargo leptos serve` instead
|
||||
// to run: `trunk serve --open --features csr`
|
||||
use harmony_example_rust_webapp::app::*;
|
||||
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
leptos::mount_to_body(App);
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
body {
|
||||
font-family: sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
@@ -13,7 +13,7 @@ reqwest = { version = "0.11", features = ["blocking", "json"] }
|
||||
russh = "0.45.0"
|
||||
rust-ipmi = "0.1.1"
|
||||
semver = "1.0.23"
|
||||
serde = { version = "1.0.209", features = ["derive", "rc"] }
|
||||
serde = { version = "1.0.209", features = ["derive"] }
|
||||
serde_json = "1.0.127"
|
||||
tokio.workspace = true
|
||||
derive-new.workspace = true
|
||||
@@ -32,6 +32,7 @@ k8s-openapi.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
http.workspace = true
|
||||
serde-value.workspace = true
|
||||
inquire.workspace = true
|
||||
helm-wrapper-rs = "0.4.0"
|
||||
non-blank-string-rs = "1.0.4"
|
||||
k3d-rs = { path = "../k3d" }
|
||||
@@ -56,12 +57,3 @@ similar.workspace = true
|
||||
futures-util = "0.3.31"
|
||||
tokio-util = "0.7.15"
|
||||
strum = { version = "0.27.1", features = ["derive"] }
|
||||
tempfile = "3.20.0"
|
||||
serde_with = "3.14.0"
|
||||
bollard.workspace = true
|
||||
tar.workspace = true
|
||||
base64.workspace = true
|
||||
once_cell = "1.21.3"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions.workspace = true
|
||||
|
||||
@@ -2,7 +2,7 @@ use lazy_static::lazy_static;
|
||||
use std::path::PathBuf;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref HARMONY_DATA_DIR: PathBuf = directories::BaseDirs::new()
|
||||
pub static ref HARMONY_CONFIG_DIR: PathBuf = directories::BaseDirs::new()
|
||||
.unwrap()
|
||||
.data_dir()
|
||||
.join("harmony");
|
||||
|
||||
@@ -2,3 +2,6 @@ mod id;
|
||||
mod version;
|
||||
pub use id::*;
|
||||
pub use version::*;
|
||||
|
||||
mod postgres;
|
||||
pub use postgres::*;
|
||||
|
||||
13
harmony/src/domain/data/postgres.rs
Normal file
13
harmony/src/domain/data/postgres.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PostgresUser {
|
||||
pub name: String,
|
||||
pub password: String, // In a real scenario, this should be a secret type
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PostgresDatabase {
|
||||
pub name: String,
|
||||
pub owner: String,
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
use log::debug;
|
||||
use once_cell::sync::Lazy;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use super::interpret::{InterpretError, Outcome};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum HarmonyEvent {
|
||||
HarmonyStarted,
|
||||
PrepareTopologyStarted {
|
||||
topology: String,
|
||||
},
|
||||
TopologyPrepared {
|
||||
topology: String,
|
||||
outcome: Outcome,
|
||||
},
|
||||
InterpretExecutionStarted {
|
||||
topology: String,
|
||||
interpret: String,
|
||||
message: String,
|
||||
},
|
||||
InterpretExecutionFinished {
|
||||
topology: String,
|
||||
interpret: String,
|
||||
outcome: Result<Outcome, InterpretError>,
|
||||
},
|
||||
}
|
||||
|
||||
static HARMONY_EVENT_BUS: Lazy<broadcast::Sender<HarmonyEvent>> = Lazy::new(|| {
|
||||
// TODO: Adjust channel capacity
|
||||
let (tx, _rx) = broadcast::channel(100);
|
||||
tx
|
||||
});
|
||||
|
||||
pub fn instrument(event: HarmonyEvent) -> Result<(), &'static str> {
|
||||
match HARMONY_EVENT_BUS.send(event) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("send error: no subscribers"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn subscribe<F, Fut>(name: &str, mut handler: F)
|
||||
where
|
||||
F: FnMut(HarmonyEvent) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = bool> + Send,
|
||||
{
|
||||
let mut rx = HARMONY_EVENT_BUS.subscribe();
|
||||
debug!("[{name}] Service started. Listening for events...");
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(event) => {
|
||||
if !handler(event).await {
|
||||
debug!("[{name}] Handler requested exit.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(n)) => {
|
||||
debug!("[{name}] Lagged behind by {n} messages.");
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ pub enum InterpretName {
|
||||
K3dInstallation,
|
||||
TenantInterpret,
|
||||
Application,
|
||||
ArgoCD,
|
||||
Postgres,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InterpretName {
|
||||
@@ -40,7 +40,7 @@ impl std::fmt::Display for InterpretName {
|
||||
InterpretName::K3dInstallation => f.write_str("K3dInstallation"),
|
||||
InterpretName::TenantInterpret => f.write_str("Tenant"),
|
||||
InterpretName::Application => f.write_str("Application"),
|
||||
InterpretName::ArgoCD => f.write_str("ArgoCD"),
|
||||
InterpretName::Postgres => f.write_str("Postgres"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use log::{debug, info, warn};
|
||||
|
||||
use crate::instrumentation::{self, HarmonyEvent};
|
||||
use log::{info, warn};
|
||||
|
||||
use super::{
|
||||
interpret::{InterpretError, InterpretStatus, Outcome},
|
||||
@@ -21,10 +19,7 @@ pub struct Maestro<T: Topology> {
|
||||
}
|
||||
|
||||
impl<T: Topology> Maestro<T> {
|
||||
/// Creates a bare maestro without initialization.
|
||||
///
|
||||
/// This should rarely be used. Most of the time Maestro::initialize should be used instead.
|
||||
pub fn new_without_initialization(inventory: Inventory, topology: T) -> Self {
|
||||
pub fn new(inventory: Inventory, topology: T) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
topology,
|
||||
@@ -34,7 +29,7 @@ impl<T: Topology> Maestro<T> {
|
||||
}
|
||||
|
||||
pub async fn initialize(inventory: Inventory, topology: T) -> Result<Self, InterpretError> {
|
||||
let instance = Self::new_without_initialization(inventory, topology);
|
||||
let instance = Self::new(inventory, topology);
|
||||
instance.prepare_topology().await?;
|
||||
Ok(instance)
|
||||
}
|
||||
@@ -42,18 +37,13 @@ impl<T: Topology> Maestro<T> {
|
||||
/// Ensures the associated Topology is ready for operations.
|
||||
/// Delegates the readiness check and potential setup actions to the Topology.
|
||||
pub async fn prepare_topology(&self) -> Result<Outcome, InterpretError> {
|
||||
instrumentation::instrument(HarmonyEvent::PrepareTopologyStarted {
|
||||
topology: self.topology.name().to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
info!("Ensuring topology '{}' is ready...", self.topology.name());
|
||||
let outcome = self.topology.ensure_ready().await?;
|
||||
|
||||
instrumentation::instrument(HarmonyEvent::TopologyPrepared {
|
||||
topology: self.topology.name().to_string(),
|
||||
outcome: outcome.clone(),
|
||||
})
|
||||
.unwrap();
|
||||
info!(
|
||||
"Topology '{}' readiness check complete: {}",
|
||||
self.topology.name(),
|
||||
outcome.status
|
||||
);
|
||||
|
||||
self.topology_preparation_result
|
||||
.lock()
|
||||
@@ -87,11 +77,11 @@ impl<T: Topology> Maestro<T> {
|
||||
self.topology.name(),
|
||||
);
|
||||
}
|
||||
debug!("Running score {score:?}");
|
||||
info!("Running score {score:?}");
|
||||
let interpret = score.create_interpret();
|
||||
debug!("Launching interpret {interpret:?}");
|
||||
info!("Launching interpret {interpret:?}");
|
||||
let result = interpret.execute(&self.inventory, &self.topology).await;
|
||||
debug!("Got result {result:?}");
|
||||
info!("Got result {result:?}");
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ pub mod data;
|
||||
pub mod executors;
|
||||
pub mod filter;
|
||||
pub mod hardware;
|
||||
pub mod instrumentation;
|
||||
pub mod interpret;
|
||||
pub mod inventory;
|
||||
pub mod maestro;
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
////////////////////
|
||||
/// Working idea
|
||||
///
|
||||
///
|
||||
trait ScoreWithDep<T> {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>>;
|
||||
fn name(&self) -> String;
|
||||
fn get_dependencies(&self) -> Vec<TypeId>; // Force T to impl Installer<TypeId> or something
|
||||
// like that
|
||||
}
|
||||
|
||||
struct PrometheusAlertScore;
|
||||
|
||||
impl <T> ScoreWithDep<T> for PrometheusAlertScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_dependencies(&self) -> Vec<TypeId> {
|
||||
// We have to find a way to constrait here so at compile time we are only allowed to return
|
||||
// TypeId for types which can be installed by T
|
||||
//
|
||||
// This means, for example that T must implement HelmCommand if the impl <T: HelmCommand> Installable<T> for
|
||||
// KubePrometheus calls for HelmCommand.
|
||||
vec![TypeId::of::<KubePrometheus>()]
|
||||
}
|
||||
}
|
||||
|
||||
trait Installable{}
|
||||
|
||||
struct KubePrometheus;
|
||||
|
||||
impl Installable for KubePrometheus;
|
||||
|
||||
|
||||
struct Maestro<T> {
|
||||
topology: T
|
||||
}
|
||||
|
||||
impl <T>Maestro<T> {
|
||||
fn execute_store(&self, score: ScoreWithDep<T>) {
|
||||
score.get_dependencies().iter().for_each(|dep| {
|
||||
self.topology.ensure_dependency_ready(dep);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct TopologyWithDep {
|
||||
}
|
||||
|
||||
impl TopologyWithDep {
|
||||
fn ensure_dependency_ready(&self, type_id: TypeId) -> Result<(), String> {
|
||||
self.installer
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,8 @@ use k8s_openapi::{
|
||||
ClusterResourceScope, NamespaceResourceScope,
|
||||
api::{apps::v1::Deployment, core::v1::Pod},
|
||||
};
|
||||
use kube::runtime::conditions;
|
||||
use kube::runtime::wait::await_condition;
|
||||
use kube::{
|
||||
Client, Config, Error, Resource,
|
||||
api::{Api, AttachParams, ListParams, Patch, PatchParams, ResourceExt},
|
||||
@@ -11,11 +13,6 @@ use kube::{
|
||||
core::ErrorResponse,
|
||||
runtime::reflector::Lookup,
|
||||
};
|
||||
use kube::{api::DynamicObject, runtime::conditions};
|
||||
use kube::{
|
||||
api::{ApiResource, GroupVersionKind},
|
||||
runtime::wait::await_condition,
|
||||
};
|
||||
use log::{debug, error, trace};
|
||||
use serde::de::DeserializeOwned;
|
||||
use similar::{DiffableStr, TextDiff};
|
||||
@@ -242,70 +239,6 @@ impl K8sClient {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn apply_yaml_many(
|
||||
&self,
|
||||
yaml: &Vec<serde_yaml::Value>,
|
||||
ns: Option<&str>,
|
||||
) -> Result<(), Error> {
|
||||
for y in yaml.iter() {
|
||||
self.apply_yaml(y, ns).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn apply_yaml(
|
||||
&self,
|
||||
yaml: &serde_yaml::Value,
|
||||
ns: Option<&str>,
|
||||
) -> Result<(), Error> {
|
||||
let obj: DynamicObject = serde_yaml::from_value(yaml.clone()).expect("TODO do not unwrap");
|
||||
let name = obj.metadata.name.as_ref().expect("YAML must have a name");
|
||||
|
||||
let api_version = yaml
|
||||
.get("apiVersion")
|
||||
.expect("couldn't get apiVersion from YAML")
|
||||
.as_str()
|
||||
.expect("couldn't get apiVersion as str");
|
||||
let kind = yaml
|
||||
.get("kind")
|
||||
.expect("couldn't get kind from YAML")
|
||||
.as_str()
|
||||
.expect("couldn't get kind as str");
|
||||
|
||||
let split: Vec<&str> = api_version.splitn(2, "/").collect();
|
||||
let g = split[0];
|
||||
let v = split[1];
|
||||
|
||||
let gvk = GroupVersionKind::gvk(g, v, kind);
|
||||
let api_resource = ApiResource::from_gvk(&gvk);
|
||||
|
||||
let namespace = match ns {
|
||||
Some(n) => n,
|
||||
None => obj
|
||||
.metadata
|
||||
.namespace
|
||||
.as_ref()
|
||||
.expect("YAML must have a namespace"),
|
||||
};
|
||||
|
||||
// 5. Create a dynamic API client for this resource type.
|
||||
let api: Api<DynamicObject> =
|
||||
Api::namespaced_with(self.client.clone(), namespace, &api_resource);
|
||||
|
||||
// 6. Apply the object to the cluster using Server-Side Apply.
|
||||
// This will create the resource if it doesn't exist, or update it if it does.
|
||||
println!(
|
||||
"Applying Argo Application '{}' in namespace '{}'...",
|
||||
name, namespace
|
||||
);
|
||||
let patch_params = PatchParams::apply("harmony"); // Use a unique field manager name
|
||||
let result = api.patch(name, &patch_params, &Patch::Apply(&obj)).await?;
|
||||
|
||||
println!("Successfully applied '{}'.", result.name_any());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn from_kubeconfig(path: &str) -> Option<K8sClient> {
|
||||
let k = match Kubeconfig::read_from(path) {
|
||||
Ok(k) => k,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use std::{process::Command, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use inquire::Confirm;
|
||||
use log::{debug, info, warn};
|
||||
use serde::Serialize;
|
||||
use tokio::sync::OnceCell;
|
||||
@@ -9,12 +10,13 @@ use crate::{
|
||||
executors::ExecutorError,
|
||||
interpret::{InterpretError, Outcome},
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::k3d::K3DInstallationScore,
|
||||
score::Score,
|
||||
topology::LocalhostTopology,
|
||||
};
|
||||
|
||||
use super::{
|
||||
DeploymentTarget, HelmCommand, K8sclient, MultiTargetTopology, Topology,
|
||||
HelmCommand, K8sclient, Topology,
|
||||
k8s::K8sClient,
|
||||
tenant::{TenantConfig, TenantManager, k8s::K8sTenantManager},
|
||||
};
|
||||
@@ -92,8 +94,9 @@ impl K8sAnywhereTopology {
|
||||
return Err("Failed to run 'helm -version'".to_string());
|
||||
}
|
||||
|
||||
// Print the version output
|
||||
let version_output = String::from_utf8_lossy(&version_result.stdout);
|
||||
debug!("Helm version: {}", version_output.trim());
|
||||
println!("Helm version: {}", version_output.trim());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -111,21 +114,15 @@ impl K8sAnywhereTopology {
|
||||
}
|
||||
|
||||
async fn try_install_k3d(&self) -> Result<(), InterpretError> {
|
||||
self.get_k3d_installation_score()
|
||||
.create_interpret()
|
||||
.execute(&Inventory::empty(), self)
|
||||
.await?;
|
||||
let maestro = Maestro::initialize(Inventory::autoload(), LocalhostTopology::new()).await?;
|
||||
let k3d_score = self.get_k3d_installation_score();
|
||||
maestro.interpret(Box::new(k3d_score)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn try_get_or_install_k8s_client(&self) -> Result<Option<K8sState>, InterpretError> {
|
||||
let k8s_anywhere_config = &self.config;
|
||||
|
||||
// TODO this deserves some refactoring, it is becoming a bit hard to figure out
|
||||
// be careful when making modifications here
|
||||
if k8s_anywhere_config.use_local_k3d {
|
||||
debug!("Using local k3d cluster because of use_local_k3d set to true");
|
||||
} else {
|
||||
if let Some(kubeconfig) = &k8s_anywhere_config.kubeconfig {
|
||||
debug!("Loading kubeconfig {kubeconfig}");
|
||||
match self.try_load_kubeconfig(&kubeconfig).await {
|
||||
@@ -153,16 +150,22 @@ impl K8sAnywhereTopology {
|
||||
}
|
||||
|
||||
info!("No kubernetes configuration found");
|
||||
}
|
||||
|
||||
if !k8s_anywhere_config.autoinstall {
|
||||
let confirmation = Confirm::new( "Harmony autoinstallation is not activated, do you wish to launch autoinstallation? : ")
|
||||
.with_default(false)
|
||||
.prompt()
|
||||
.expect("Unexpected prompt error");
|
||||
|
||||
if !confirmation {
|
||||
warn!(
|
||||
"Installation cancelled, K8sAnywhere could not initialize a valid Kubernetes client"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
debug!("Starting K8sAnywhere installation");
|
||||
info!("Starting K8sAnywhere installation");
|
||||
self.try_install_k3d().await?;
|
||||
let k3d_score = self.get_k3d_installation_score();
|
||||
// I feel like having to rely on the k3d_rs crate here is a smell
|
||||
@@ -175,7 +178,7 @@ impl K8sAnywhereTopology {
|
||||
Ok(client) => K8sState {
|
||||
client: Arc::new(K8sClient::new(client)),
|
||||
_source: K8sSource::LocalK3d,
|
||||
message: "K8s client ready".to_string(),
|
||||
message: "Successfully installed K3D cluster and acquired client".to_string(),
|
||||
},
|
||||
Err(_) => todo!(),
|
||||
};
|
||||
@@ -228,14 +231,6 @@ pub struct K8sAnywhereConfig {
|
||||
///
|
||||
/// Default: true
|
||||
pub autoinstall: bool,
|
||||
|
||||
/// Whether to use local k3d cluster.
|
||||
///
|
||||
/// Takes precedence over other options, useful to avoid messing up a remote cluster by mistake
|
||||
///
|
||||
/// default: true
|
||||
pub use_local_k3d: bool,
|
||||
pub harmony_profile: String,
|
||||
}
|
||||
|
||||
impl K8sAnywhereConfig {
|
||||
@@ -245,14 +240,7 @@ impl K8sAnywhereConfig {
|
||||
use_system_kubeconfig: std::env::var("HARMONY_USE_SYSTEM_KUBECONFIG")
|
||||
.map_or_else(|_| false, |v| v.parse().ok().unwrap_or(false)),
|
||||
autoinstall: std::env::var("HARMONY_AUTOINSTALL")
|
||||
.map_or_else(|_| true, |v| v.parse().ok().unwrap_or(false)),
|
||||
// TODO harmony_profile should be managed at a more core level than this
|
||||
harmony_profile: std::env::var("HARMONY_PROFILE").map_or_else(
|
||||
|_| "dev".to_string(),
|
||||
|v| v.parse().ok().unwrap_or("dev".to_string()),
|
||||
),
|
||||
use_local_k3d: std::env::var("HARMONY_USE_LOCAL_K3D")
|
||||
.map_or_else(|_| true, |v| v.parse().ok().unwrap_or(true)),
|
||||
.map_or_else(|_| false, |v| v.parse().ok().unwrap_or(false)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,20 +275,6 @@ impl Topology for K8sAnywhereTopology {
|
||||
}
|
||||
}
|
||||
|
||||
impl MultiTargetTopology for K8sAnywhereTopology {
|
||||
fn current_target(&self) -> DeploymentTarget {
|
||||
if self.config.use_local_k3d {
|
||||
return DeploymentTarget::LocalDev;
|
||||
}
|
||||
|
||||
match self.config.harmony_profile.to_lowercase().as_str() {
|
||||
"staging" => DeploymentTarget::Staging,
|
||||
"production" => DeploymentTarget::Production,
|
||||
_ => todo!("HARMONY_PROFILE must be set when use_local_k3d is not set"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HelmCommand for K8sAnywhereTopology {}
|
||||
|
||||
#[async_trait]
|
||||
|
||||
@@ -23,6 +23,9 @@ pub use network::*;
|
||||
use serde::Serialize;
|
||||
pub use tftp::*;
|
||||
|
||||
mod postgres;
|
||||
pub use postgres::*;
|
||||
|
||||
mod helm_command;
|
||||
pub use helm_command::*;
|
||||
|
||||
@@ -62,17 +65,6 @@ pub trait Topology: Send + Sync {
|
||||
async fn ensure_ready(&self) -> Result<Outcome, InterpretError>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DeploymentTarget {
|
||||
LocalDev,
|
||||
Staging,
|
||||
Production,
|
||||
}
|
||||
|
||||
pub trait MultiTargetTopology: Topology {
|
||||
fn current_target(&self) -> DeploymentTarget;
|
||||
}
|
||||
|
||||
pub type IpAddress = IpAddr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
|
||||
14
harmony/src/domain/topology/postgres.rs
Normal file
14
harmony/src/domain/topology/postgres.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use crate::{
|
||||
data::{PostgresDatabase, PostgresUser},
|
||||
interpret::InterpretError,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait PostgresServer {
|
||||
async fn ensure_users_exist(&self, users: Vec<PostgresUser>) -> Result<(), InterpretError>;
|
||||
async fn ensure_databases_exist(
|
||||
&self,
|
||||
databases: Vec<PostgresDatabase>,
|
||||
) -> Result<(), InterpretError>;
|
||||
}
|
||||
@@ -2,7 +2,6 @@ use async_trait::async_trait;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::topology::Topology;
|
||||
|
||||
/// An ApplicationFeature provided by harmony, such as Backups, Monitoring, MultisiteAvailability,
|
||||
/// ContinuousIntegration, ContinuousDelivery
|
||||
#[async_trait]
|
||||
|
||||
@@ -1,354 +0,0 @@
|
||||
use log::debug;
|
||||
use serde::Serialize;
|
||||
use serde_with::skip_serializing_none;
|
||||
use serde_yaml::Value;
|
||||
|
||||
use crate::modules::application::features::CDApplicationConfig;
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Helm {
|
||||
pub pass_credentials: Option<bool>,
|
||||
pub parameters: Vec<Value>,
|
||||
pub file_parameters: Vec<Value>,
|
||||
pub release_name: Option<String>,
|
||||
pub value_files: Vec<String>,
|
||||
pub ignore_missing_value_files: Option<bool>,
|
||||
pub values: Option<String>,
|
||||
pub values_object: Option<Value>,
|
||||
pub skip_crds: Option<bool>,
|
||||
pub skip_schema_validation: Option<bool>,
|
||||
pub version: Option<String>,
|
||||
pub kube_version: Option<String>,
|
||||
pub api_versions: Vec<String>,
|
||||
pub namespace: Option<String>,
|
||||
}
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Source {
|
||||
// Using string for this because URL enforces a URL scheme at the beginning but Helm, ArgoCD, etc do not, and it can be counterproductive,
|
||||
// as the only way I've found to get OCI working isn't by using oci:// but rather no scheme at all
|
||||
#[serde(rename = "repoURL")]
|
||||
pub repo_url: String,
|
||||
pub target_revision: Option<String>,
|
||||
pub chart: String,
|
||||
pub helm: Helm,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Automated {
|
||||
pub prune: bool,
|
||||
pub self_heal: bool,
|
||||
pub allow_empty: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Backoff {
|
||||
pub duration: String,
|
||||
pub factor: u32,
|
||||
pub max_duration: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Retry {
|
||||
pub limit: u32,
|
||||
pub backoff: Backoff,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SyncPolicy {
|
||||
pub automated: Automated,
|
||||
pub sync_options: Vec<String>,
|
||||
pub retry: Retry,
|
||||
}
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ArgoApplication {
|
||||
pub name: String,
|
||||
pub namespace: Option<String>,
|
||||
pub project: String,
|
||||
pub source: Source,
|
||||
pub sync_policy: SyncPolicy,
|
||||
pub revision_history_limit: u32,
|
||||
}
|
||||
|
||||
impl Default for ArgoApplication {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: Default::default(),
|
||||
namespace: Default::default(),
|
||||
project: Default::default(),
|
||||
source: Source {
|
||||
repo_url: "http://asdf".to_string(),
|
||||
target_revision: None,
|
||||
chart: "".to_string(),
|
||||
helm: Helm {
|
||||
pass_credentials: None,
|
||||
parameters: vec![],
|
||||
file_parameters: vec![],
|
||||
release_name: None,
|
||||
value_files: vec![],
|
||||
ignore_missing_value_files: None,
|
||||
values: None,
|
||||
values_object: None,
|
||||
skip_crds: None,
|
||||
skip_schema_validation: None,
|
||||
version: None,
|
||||
kube_version: None,
|
||||
api_versions: vec![],
|
||||
namespace: None,
|
||||
},
|
||||
path: "".to_string(),
|
||||
},
|
||||
sync_policy: SyncPolicy {
|
||||
automated: Automated {
|
||||
prune: false,
|
||||
self_heal: false,
|
||||
allow_empty: false,
|
||||
},
|
||||
sync_options: vec![],
|
||||
retry: Retry {
|
||||
limit: 5,
|
||||
backoff: Backoff {
|
||||
duration: "5s".to_string(),
|
||||
factor: 2,
|
||||
max_duration: "3m".to_string(),
|
||||
},
|
||||
},
|
||||
},
|
||||
revision_history_limit: 10,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CDApplicationConfig> for ArgoApplication {
|
||||
fn from(value: CDApplicationConfig) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
namespace: Some(value.namespace),
|
||||
project: "default".to_string(),
|
||||
source: Source {
|
||||
repo_url: value.helm_chart_repo_url,
|
||||
target_revision: Some(value.version.to_string()),
|
||||
chart: value.helm_chart_name.clone(),
|
||||
path: value.helm_chart_name,
|
||||
helm: Helm {
|
||||
pass_credentials: None,
|
||||
parameters: vec![],
|
||||
file_parameters: vec![],
|
||||
release_name: None,
|
||||
value_files: vec![],
|
||||
ignore_missing_value_files: None,
|
||||
values: None,
|
||||
values_object: value.values_overrides,
|
||||
skip_crds: None,
|
||||
skip_schema_validation: None,
|
||||
version: None,
|
||||
kube_version: None,
|
||||
api_versions: vec![],
|
||||
namespace: None,
|
||||
},
|
||||
},
|
||||
sync_policy: SyncPolicy {
|
||||
automated: Automated {
|
||||
prune: false,
|
||||
self_heal: false,
|
||||
allow_empty: true,
|
||||
},
|
||||
sync_options: vec![],
|
||||
retry: Retry {
|
||||
limit: 5,
|
||||
backoff: Backoff {
|
||||
duration: "5s".to_string(),
|
||||
factor: 2,
|
||||
max_duration: "3m".to_string(),
|
||||
},
|
||||
},
|
||||
},
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ArgoApplication {
|
||||
pub fn to_yaml(&self) -> serde_yaml::Value {
|
||||
let name = &self.name;
|
||||
let namespace = if let Some(ns) = self.namespace.as_ref() {
|
||||
&ns
|
||||
} else {
|
||||
"argocd"
|
||||
};
|
||||
let project = &self.project;
|
||||
let source = &self.source;
|
||||
|
||||
let yaml_str = format!(
|
||||
r#"
|
||||
apiVersion: argoproj.io/v1alpha1
|
||||
kind: Application
|
||||
metadata:
|
||||
name: {name}
|
||||
# You'll usually want to add your resources to the argocd namespace.
|
||||
namespace: {namespace}
|
||||
spec:
|
||||
# The project the application belongs to.
|
||||
project: {project}
|
||||
|
||||
# Destination cluster and namespace to deploy the application
|
||||
destination:
|
||||
# cluster API URL
|
||||
server: https://kubernetes.default.svc
|
||||
# or cluster name
|
||||
# name: in-cluster
|
||||
# The namespace will only be set for namespace-scoped resources that have not set a value for .metadata.namespace
|
||||
namespace: {namespace}
|
||||
|
||||
"#
|
||||
);
|
||||
|
||||
let mut yaml_value: Value =
|
||||
serde_yaml::from_str(yaml_str.as_str()).expect("couldn't parse string to YAML");
|
||||
|
||||
let spec = yaml_value
|
||||
.get_mut("spec")
|
||||
.expect("couldn't get spec from yaml")
|
||||
.as_mapping_mut()
|
||||
.expect("couldn't unwrap spec as mutable mapping");
|
||||
|
||||
let source =
|
||||
serde_yaml::to_value(&self.source).expect("couldn't serialize source to value");
|
||||
let sync_policy = serde_yaml::to_value(&self.sync_policy)
|
||||
.expect("couldn't serialize sync_policy to value");
|
||||
let revision_history_limit = serde_yaml::to_value(&self.revision_history_limit)
|
||||
.expect("couldn't serialize revision_history_limit to value");
|
||||
|
||||
spec.insert(
|
||||
serde_yaml::to_value("source").expect("string to value failed"),
|
||||
source,
|
||||
);
|
||||
spec.insert(
|
||||
serde_yaml::to_value("syncPolicy").expect("string to value failed"),
|
||||
sync_policy,
|
||||
);
|
||||
spec.insert(
|
||||
serde_yaml::to_value("revisionHistoryLimit")
|
||||
.expect("couldn't convert str to yaml value"),
|
||||
revision_history_limit,
|
||||
);
|
||||
|
||||
debug!("spec: {}", serde_yaml::to_string(spec).unwrap());
|
||||
debug!(
|
||||
"entire yaml_value: {}",
|
||||
serde_yaml::to_string(&yaml_value).unwrap()
|
||||
);
|
||||
|
||||
yaml_value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::modules::application::features::{
|
||||
ArgoApplication, Automated, Backoff, Helm, Retry, Source, SyncPolicy,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn test_argo_application_to_yaml_happy_path() {
|
||||
let app = ArgoApplication {
|
||||
name: "test".to_string(),
|
||||
namespace: Some("test-ns".to_string()),
|
||||
project: "test-project".to_string(),
|
||||
source: Source {
|
||||
repo_url: "http://test".to_string(),
|
||||
target_revision: None,
|
||||
chart: "test-chart".to_string(),
|
||||
helm: Helm {
|
||||
pass_credentials: None,
|
||||
parameters: vec![],
|
||||
file_parameters: vec![],
|
||||
release_name: Some("test-release-neame".to_string()),
|
||||
value_files: vec![],
|
||||
ignore_missing_value_files: None,
|
||||
values: None,
|
||||
values_object: None,
|
||||
skip_crds: None,
|
||||
skip_schema_validation: None,
|
||||
version: None,
|
||||
kube_version: None,
|
||||
api_versions: vec![],
|
||||
namespace: None,
|
||||
},
|
||||
path: "".to_string(),
|
||||
},
|
||||
sync_policy: SyncPolicy {
|
||||
automated: Automated {
|
||||
prune: false,
|
||||
self_heal: false,
|
||||
allow_empty: false,
|
||||
},
|
||||
sync_options: vec![],
|
||||
retry: Retry {
|
||||
limit: 5,
|
||||
backoff: Backoff {
|
||||
duration: "5s".to_string(),
|
||||
factor: 2,
|
||||
max_duration: "3m".to_string(),
|
||||
},
|
||||
},
|
||||
},
|
||||
revision_history_limit: 10,
|
||||
};
|
||||
|
||||
let expected_yaml_output = r#"apiVersion: argoproj.io/v1alpha1
|
||||
kind: Application
|
||||
metadata:
|
||||
name: test
|
||||
namespace: test-ns
|
||||
spec:
|
||||
project: test-project
|
||||
destination:
|
||||
server: https://kubernetes.default.svc
|
||||
namespace: test-ns
|
||||
source:
|
||||
repoURL: http://test
|
||||
chart: test-chart
|
||||
helm:
|
||||
parameters: []
|
||||
fileParameters: []
|
||||
releaseName: test-release-neame
|
||||
valueFiles: []
|
||||
apiVersions: []
|
||||
path: ''
|
||||
syncPolicy:
|
||||
automated:
|
||||
prune: false
|
||||
selfHeal: false
|
||||
allowEmpty: false
|
||||
syncOptions: []
|
||||
retry:
|
||||
limit: 5
|
||||
backoff:
|
||||
duration: 5s
|
||||
factor: 2
|
||||
maxDuration: 3m
|
||||
revisionHistoryLimit: 10"#;
|
||||
|
||||
assert_eq!(
|
||||
expected_yaml_output.trim(),
|
||||
serde_yaml::to_string(&app.clone().to_yaml())
|
||||
.unwrap()
|
||||
.trim()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,13 @@
|
||||
use std::{io::Write, process::Command, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, error};
|
||||
use serde_yaml::Value;
|
||||
use tempfile::NamedTempFile;
|
||||
use log::info;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::{
|
||||
config::HARMONY_DATA_DIR,
|
||||
data::Version,
|
||||
inventory::Inventory,
|
||||
modules::application::{
|
||||
Application, ApplicationFeature, HelmPackage, OCICompliant,
|
||||
features::{ArgoApplication, ArgoHelmScore},
|
||||
},
|
||||
modules::{application::ApplicationFeature, helm::chart::HelmChartScore},
|
||||
score::Score,
|
||||
topology::{DeploymentTarget, HelmCommand, K8sclient, MultiTargetTopology, Topology},
|
||||
topology::{HelmCommand, Topology, Url},
|
||||
};
|
||||
|
||||
/// ContinuousDelivery in Harmony provides this functionality :
|
||||
@@ -45,161 +38,33 @@ use crate::{
|
||||
/// - ArgoCD to install/upgrade/rollback/inspect k8s resources
|
||||
/// - Kubernetes for runtime orchestration
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ContinuousDelivery<A: OCICompliant + HelmPackage> {
|
||||
pub application: Arc<A>,
|
||||
}
|
||||
|
||||
impl<A: OCICompliant + HelmPackage> ContinuousDelivery<A> {
|
||||
async fn deploy_to_local_k3d(
|
||||
&self,
|
||||
app_name: String,
|
||||
chart_url: String,
|
||||
image_name: String,
|
||||
) -> Result<(), String> {
|
||||
error!(
|
||||
"FIXME This works only with local k3d installations, which is fine only for current demo purposes. We assume usage of K8sAnywhereTopology"
|
||||
);
|
||||
|
||||
error!("TODO hardcoded k3d bin path is wrong");
|
||||
let k3d_bin_path = (*HARMONY_DATA_DIR).join("k3d").join("k3d");
|
||||
// --- 1. Import the container image into the k3d cluster ---
|
||||
debug!(
|
||||
"Importing image '{}' into k3d cluster 'harmony'",
|
||||
image_name
|
||||
);
|
||||
let import_output = Command::new(&k3d_bin_path)
|
||||
.args(["image", "import", &image_name, "--cluster", "harmony"])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to execute k3d image import: {}", e))?;
|
||||
|
||||
if !import_output.status.success() {
|
||||
return Err(format!(
|
||||
"Failed to import image to k3d: {}",
|
||||
String::from_utf8_lossy(&import_output.stderr)
|
||||
));
|
||||
}
|
||||
|
||||
// --- 2. Get the kubeconfig for the k3d cluster and write it to a temp file ---
|
||||
debug!("Retrieving kubeconfig for k3d cluster 'harmony'");
|
||||
let kubeconfig_output = Command::new(&k3d_bin_path)
|
||||
.args(["kubeconfig", "get", "harmony"])
|
||||
.output()
|
||||
.map_err(|e| format!("Failed to execute k3d kubeconfig get: {}", e))?;
|
||||
|
||||
if !kubeconfig_output.status.success() {
|
||||
return Err(format!(
|
||||
"Failed to get kubeconfig from k3d: {}",
|
||||
String::from_utf8_lossy(&kubeconfig_output.stderr)
|
||||
));
|
||||
}
|
||||
|
||||
let mut temp_kubeconfig = NamedTempFile::new()
|
||||
.map_err(|e| format!("Failed to create temp file for kubeconfig: {}", e))?;
|
||||
temp_kubeconfig
|
||||
.write_all(&kubeconfig_output.stdout)
|
||||
.map_err(|e| format!("Failed to write to temp kubeconfig file: {}", e))?;
|
||||
let kubeconfig_path = temp_kubeconfig.path().to_str().unwrap();
|
||||
|
||||
// --- 3. Install or upgrade the Helm chart in the cluster ---
|
||||
debug!(
|
||||
"Deploying Helm chart '{}' to namespace '{}'",
|
||||
chart_url, app_name
|
||||
);
|
||||
let release_name = app_name.to_lowercase(); // Helm release names are often lowercase
|
||||
let helm_output = Command::new("helm")
|
||||
.args([
|
||||
"upgrade",
|
||||
"--install",
|
||||
&release_name,
|
||||
&chart_url,
|
||||
"--namespace",
|
||||
&app_name,
|
||||
"--create-namespace",
|
||||
"--wait", // Wait for the deployment to be ready
|
||||
"--kubeconfig",
|
||||
kubeconfig_path,
|
||||
])
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to execute helm upgrade: {}", e))?
|
||||
.wait_with_output()
|
||||
.map_err(|e| format!("Failed to execute helm upgrade: {}", e))?;
|
||||
|
||||
if !helm_output.status.success() {
|
||||
return Err(format!(
|
||||
"Failed to deploy Helm chart: {}",
|
||||
String::from_utf8_lossy(&helm_output.stderr)
|
||||
));
|
||||
}
|
||||
|
||||
debug!("Successfully deployed '{}' to local k3d cluster.", app_name);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub struct ContinuousDelivery {}
|
||||
|
||||
#[async_trait]
|
||||
impl<
|
||||
A: OCICompliant + HelmPackage + Clone + 'static,
|
||||
T: Topology + HelmCommand + MultiTargetTopology + K8sclient + 'static,
|
||||
> ApplicationFeature<T> for ContinuousDelivery<A>
|
||||
{
|
||||
impl<T: Topology + HelmCommand + 'static> ApplicationFeature<T> for ContinuousDelivery {
|
||||
async fn ensure_installed(&self, topology: &T) -> Result<(), String> {
|
||||
let image = self.application.image_name();
|
||||
|
||||
// TODO Write CI/CD workflow files
|
||||
// we can autotedect the CI type using the remote url (default to github action for github
|
||||
// url, etc..)
|
||||
// Or ask for it when unknown
|
||||
|
||||
let helm_chart = self.application.build_push_helm_package(&image).await?;
|
||||
debug!("Pushed new helm chart {helm_chart}");
|
||||
|
||||
error!("TODO Make building image configurable/skippable if image already exists (prompt)");
|
||||
let image = self.application.build_push_oci_image().await?;
|
||||
debug!("Pushed new docker image {image}");
|
||||
|
||||
debug!("Installing ContinuousDelivery feature");
|
||||
// TODO this is a temporary hack for demo purposes, the deployment target should be driven
|
||||
// by the topology only and we should not have to know how to perform tasks like this for
|
||||
// which the topology should be responsible.
|
||||
//
|
||||
// That said, this will require some careful architectural decisions, since the concept of
|
||||
// deployment targets / profiles is probably a layer of complexity that we won't be
|
||||
// completely able to avoid
|
||||
//
|
||||
// I'll try something for now that must be thought through after : att a deployment_profile
|
||||
// function to the topology trait that returns a profile, then anybody who needs it can
|
||||
// access it. This forces every Topology to understand the concept of targets though... So
|
||||
// instead I'll create a new Capability which is MultiTargetTopology and we'll see how it
|
||||
// goes. It still does not feel right though.
|
||||
match topology.current_target() {
|
||||
DeploymentTarget::LocalDev => {
|
||||
self.deploy_to_local_k3d(self.application.name(), helm_chart, image)
|
||||
.await?;
|
||||
}
|
||||
target => {
|
||||
debug!("Deploying to target {target:?}");
|
||||
let score = ArgoHelmScore {
|
||||
namespace: "harmonydemo-staging".to_string(),
|
||||
openshift: false,
|
||||
domain: "argo.harmonydemo.apps.st.mcd".to_string(),
|
||||
argo_apps: vec![ArgoApplication::from(CDApplicationConfig {
|
||||
// helm pull oci://hub.nationtech.io/harmony/harmony-example-rust-webapp-chart --version 0.1.0
|
||||
version: Version::from("0.1.0").unwrap(),
|
||||
helm_chart_repo_url: "hub.nationtech.io/harmony".to_string(),
|
||||
helm_chart_name: "harmony-example-rust-webapp-chart".to_string(),
|
||||
values_overrides: None,
|
||||
name: "harmony-demo-rust-webapp".to_string(),
|
||||
namespace: "harmonydemo-staging".to_string(),
|
||||
})],
|
||||
info!("Installing ContinuousDelivery feature");
|
||||
let cd_server = HelmChartScore {
|
||||
namespace: todo!(
|
||||
"ArgoCD Helm chart with proper understanding of Tenant, see how Will did it for Monitoring for now"
|
||||
),
|
||||
release_name: todo!("argocd helm chart whatever"),
|
||||
chart_name: todo!(),
|
||||
chart_version: todo!(),
|
||||
values_overrides: todo!(),
|
||||
values_yaml: todo!(),
|
||||
create_namespace: todo!(),
|
||||
install_only: todo!(),
|
||||
repository: todo!(),
|
||||
};
|
||||
score
|
||||
.create_interpret()
|
||||
.execute(&Inventory::empty(), topology)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
};
|
||||
Ok(())
|
||||
let interpret = cd_server.create_interpret();
|
||||
interpret.execute(&Inventory::empty(), topology);
|
||||
|
||||
todo!("1. Create ArgoCD score that installs argo using helm chart, see if Taha's already done it
|
||||
2. Package app (docker image, helm chart)
|
||||
3. Push to registry if staging or prod
|
||||
4. Poke Argo
|
||||
5. Ensure app is up")
|
||||
}
|
||||
fn name(&self) -> String {
|
||||
"ContinuousDelivery".to_string()
|
||||
@@ -209,12 +74,9 @@ impl<
|
||||
/// For now this is entirely bound to K8s / ArgoCD, will have to be revisited when we support
|
||||
/// more CD systems
|
||||
pub struct CDApplicationConfig {
|
||||
pub version: Version,
|
||||
pub helm_chart_repo_url: String,
|
||||
pub helm_chart_name: String,
|
||||
pub values_overrides: Option<Value>,
|
||||
pub name: String,
|
||||
pub namespace: String,
|
||||
version: Version,
|
||||
helm_chart_url: Url,
|
||||
values_overrides: Value,
|
||||
}
|
||||
|
||||
pub trait ContinuousDeliveryApplication {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,9 +6,3 @@ pub use monitoring::*;
|
||||
|
||||
mod continuous_delivery;
|
||||
pub use continuous_delivery::*;
|
||||
|
||||
mod helm_argocd_score;
|
||||
pub use helm_argocd_score::*;
|
||||
|
||||
mod argo_types;
|
||||
pub use argo_types::*;
|
||||
|
||||
@@ -1,109 +1,19 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use log::{debug, info};
|
||||
use log::info;
|
||||
|
||||
use crate::{
|
||||
inventory::Inventory,
|
||||
modules::{
|
||||
application::{ApplicationFeature, OCICompliant},
|
||||
monitoring::{
|
||||
alert_channel::webhook_receiver::WebhookReceiver,
|
||||
kube_prometheus::{
|
||||
helm_prometheus_alert_score::HelmPrometheusAlertingScore,
|
||||
types::{NamespaceSelector, ServiceMonitor},
|
||||
},
|
||||
ntfy::ntfy::NtfyScore,
|
||||
},
|
||||
},
|
||||
score::Score,
|
||||
topology::{HelmCommand, K8sclient, Topology, Url, tenant::TenantManager},
|
||||
modules::application::ApplicationFeature,
|
||||
topology::{HelmCommand, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Monitoring {
|
||||
pub application: Arc<dyn OCICompliant>,
|
||||
}
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Monitoring {}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + HelmCommand + K8sclient + 'static + TenantManager> ApplicationFeature<T>
|
||||
for Monitoring
|
||||
{
|
||||
async fn ensure_installed(&self, topology: &T) -> Result<(), String> {
|
||||
impl<T: Topology + HelmCommand + 'static> ApplicationFeature<T> for Monitoring {
|
||||
async fn ensure_installed(&self, _topology: &T) -> Result<(), String> {
|
||||
info!("Ensuring monitoring is available for application");
|
||||
|
||||
let ntfy = NtfyScore {
|
||||
// namespace: topology
|
||||
// .get_tenant_config()
|
||||
// .await
|
||||
// .expect("couldn't get tenant config")
|
||||
// .name,
|
||||
namespace: self.application.name(),
|
||||
host: "localhost".to_string(),
|
||||
};
|
||||
ntfy.create_interpret()
|
||||
.execute(&Inventory::empty(), topology)
|
||||
.await
|
||||
.expect("couldn't create interpret for ntfy");
|
||||
|
||||
let ntfy_default_auth_username = "harmony";
|
||||
let ntfy_default_auth_password = "harmony";
|
||||
let ntfy_default_auth_header = format!(
|
||||
"Basic {}",
|
||||
general_purpose::STANDARD.encode(format!(
|
||||
"{ntfy_default_auth_username}:{ntfy_default_auth_password}"
|
||||
))
|
||||
);
|
||||
|
||||
debug!("ntfy_default_auth_header: {ntfy_default_auth_header}");
|
||||
|
||||
let ntfy_default_auth_param = general_purpose::STANDARD
|
||||
.encode(ntfy_default_auth_header)
|
||||
.replace("=", "");
|
||||
|
||||
debug!("ntfy_default_auth_param: {ntfy_default_auth_param}");
|
||||
|
||||
let ntfy_receiver = WebhookReceiver {
|
||||
name: "ntfy-webhook".to_string(),
|
||||
url: Url::Url(
|
||||
url::Url::parse(
|
||||
format!(
|
||||
"http://ntfy.{}.svc.cluster.local/rust-web-app?auth={ntfy_default_auth_param}",
|
||||
self.application.name()
|
||||
)
|
||||
.as_str(),
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
};
|
||||
|
||||
let mut service_monitor = ServiceMonitor::default();
|
||||
service_monitor.namespace_selector = Some(NamespaceSelector {
|
||||
any: true,
|
||||
match_names: vec![],
|
||||
});
|
||||
|
||||
service_monitor.name = "rust-webapp".to_string();
|
||||
|
||||
// let alerting_score = ApplicationPrometheusMonitoringScore {
|
||||
// receivers: vec![Box::new(ntfy_receiver)],
|
||||
// rules: vec![],
|
||||
// service_monitors: vec![service_monitor],
|
||||
// };
|
||||
|
||||
let alerting_score = HelmPrometheusAlertingScore {
|
||||
receivers: vec![Box::new(ntfy_receiver)],
|
||||
rules: vec![],
|
||||
service_monitors: vec![service_monitor],
|
||||
};
|
||||
|
||||
alerting_score
|
||||
.create_interpret()
|
||||
.execute(&Inventory::empty(), topology)
|
||||
.await
|
||||
.unwrap();
|
||||
Ok(())
|
||||
todo!("create and execute k8s prometheus score, depends on Will's work")
|
||||
}
|
||||
fn name(&self) -> String {
|
||||
"Monitoring".to_string()
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
mod feature;
|
||||
pub mod features;
|
||||
pub mod oci;
|
||||
mod rust;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use feature::*;
|
||||
use log::debug;
|
||||
pub use oci::*;
|
||||
use log::info;
|
||||
pub use rust::*;
|
||||
|
||||
use async_trait::async_trait;
|
||||
@@ -23,20 +19,20 @@ pub trait Application: std::fmt::Debug + Send + Sync {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ApplicationInterpret<A: Application, T: Topology + std::fmt::Debug> {
|
||||
pub struct ApplicationInterpret<T: Topology + std::fmt::Debug> {
|
||||
features: Vec<Box<dyn ApplicationFeature<T>>>,
|
||||
application: Arc<A>,
|
||||
application: Box<dyn Application>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<A: Application, T: Topology + std::fmt::Debug> Interpret<T> for ApplicationInterpret<A, T> {
|
||||
impl<T: Topology + std::fmt::Debug> Interpret<T> for ApplicationInterpret<T> {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let app_name = self.application.name();
|
||||
debug!(
|
||||
info!(
|
||||
"Preparing {} features [{}] for application {app_name}",
|
||||
self.features.len(),
|
||||
self.features
|
||||
@@ -46,7 +42,7 @@ impl<A: Application, T: Topology + std::fmt::Debug> Interpret<T> for Application
|
||||
.join(", ")
|
||||
);
|
||||
for feature in self.features.iter() {
|
||||
debug!(
|
||||
info!(
|
||||
"Installing feature {} for application {app_name}",
|
||||
feature.name()
|
||||
);
|
||||
@@ -59,7 +55,9 @@ impl<A: Application, T: Topology + std::fmt::Debug> Interpret<T> for Application
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(Outcome::success("successfully created app".to_string()))
|
||||
todo!(
|
||||
"Do I need to do anything more than this here?? I feel like the Application trait itself should expose something like ensure_ready but its becoming redundant. We'll see as this evolves."
|
||||
)
|
||||
}
|
||||
|
||||
fn get_name(&self) -> InterpretName {
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::Application;
|
||||
|
||||
#[async_trait]
|
||||
pub trait OCICompliant: Application {
|
||||
async fn build_push_oci_image(&self) -> Result<String, String>; // TODO consider using oci-spec and friends crates here
|
||||
|
||||
fn image_name(&self) -> String;
|
||||
|
||||
fn local_image_name(&self) -> String;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait HelmPackage: Application {
|
||||
/// Generates, packages, and pushes a Helm chart for the web application to an OCI registry.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `image_url` - The full URL of the OCI container image to be used in the Deployment.
|
||||
async fn build_push_helm_package(&self, image_url: &str) -> Result<String, String>;
|
||||
}
|
||||
@@ -1,67 +1,37 @@
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::process;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bollard::query_parameters::PushImageOptionsBuilder;
|
||||
use bollard::{Docker, body_full};
|
||||
use dockerfile_builder::Dockerfile;
|
||||
use dockerfile_builder::instruction::{CMD, COPY, ENV, EXPOSE, FROM, RUN, USER, WORKDIR};
|
||||
use dockerfile_builder::instruction_builder::CopyBuilder;
|
||||
use futures_util::StreamExt;
|
||||
use log::{debug, error, log_enabled};
|
||||
use serde::Serialize;
|
||||
use tar::Archive;
|
||||
|
||||
use crate::config::{REGISTRY_PROJECT, REGISTRY_URL};
|
||||
use crate::{
|
||||
score::Score,
|
||||
topology::{Topology, Url},
|
||||
};
|
||||
|
||||
use super::{Application, ApplicationFeature, ApplicationInterpret, HelmPackage, OCICompliant};
|
||||
use super::{Application, ApplicationFeature, ApplicationInterpret};
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
pub struct ApplicationScore<A: Application + Serialize, T: Topology + Clone + Serialize>
|
||||
where
|
||||
Arc<A>: Serialize + Clone,
|
||||
{
|
||||
pub struct RustWebappScore<T: Topology + Clone + Serialize> {
|
||||
pub name: String,
|
||||
pub domain: Url,
|
||||
pub features: Vec<Box<dyn ApplicationFeature<T>>>,
|
||||
pub application: Arc<A>,
|
||||
}
|
||||
|
||||
impl<
|
||||
A: Application + Serialize + Clone + 'static,
|
||||
T: Topology + std::fmt::Debug + Clone + Serialize + 'static,
|
||||
> Score<T> for ApplicationScore<A, T>
|
||||
where
|
||||
Arc<A>: Serialize,
|
||||
{
|
||||
impl<T: Topology + std::fmt::Debug + Clone + Serialize + 'static> Score<T> for RustWebappScore<T> {
|
||||
fn create_interpret(&self) -> Box<dyn crate::interpret::Interpret<T>> {
|
||||
Box::new(ApplicationInterpret {
|
||||
features: self.features.clone(),
|
||||
application: self.application.clone(),
|
||||
application: Box::new(RustWebapp {
|
||||
name: self.name.clone(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
format!("Application: {}", self.application.name())
|
||||
format!("{}-RustWebapp", self.name)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum RustWebFramework {
|
||||
Leptos,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct RustWebapp {
|
||||
pub name: String,
|
||||
pub domain: Url,
|
||||
/// The path to the root of the Rust project to be containerized.
|
||||
pub project_root: PathBuf,
|
||||
pub framework: Option<RustWebFramework>,
|
||||
#[derive(Debug)]
|
||||
struct RustWebapp {
|
||||
name: String,
|
||||
}
|
||||
|
||||
impl Application for RustWebapp {
|
||||
@@ -69,533 +39,3 @@ impl Application for RustWebapp {
|
||||
self.name.clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HelmPackage for RustWebapp {
|
||||
async fn build_push_helm_package(&self, image_url: &str) -> Result<String, String> {
|
||||
debug!("Starting Helm chart build and push for '{}'", self.name);
|
||||
|
||||
// 1. Create the Helm chart files on disk.
|
||||
let chart_dir = self
|
||||
.create_helm_chart_files(image_url)
|
||||
.map_err(|e| format!("Failed to create Helm chart files: {}", e))?;
|
||||
debug!("Successfully created Helm chart files in {:?}", chart_dir);
|
||||
|
||||
// 2. Package the chart into a .tgz archive.
|
||||
let packaged_chart_path = self
|
||||
.package_helm_chart(&chart_dir)
|
||||
.map_err(|e| format!("Failed to package Helm chart: {}", e))?;
|
||||
debug!(
|
||||
"Successfully packaged Helm chart: {}",
|
||||
packaged_chart_path.to_string_lossy()
|
||||
);
|
||||
|
||||
// 3. Push the packaged chart to the OCI registry.
|
||||
let oci_chart_url = self
|
||||
.push_helm_chart(&packaged_chart_path)
|
||||
.map_err(|e| format!("Failed to push Helm chart: {}", e))?;
|
||||
debug!("Successfully pushed Helm chart to: {}", oci_chart_url);
|
||||
|
||||
Ok(oci_chart_url)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl OCICompliant for RustWebapp {
|
||||
/// Builds a Docker image for the Rust web application using a multi-stage build,
|
||||
/// pushes it to the configured OCI registry, and returns the full image tag.
|
||||
async fn build_push_oci_image(&self) -> Result<String, String> {
|
||||
// This function orchestrates the build and push process.
|
||||
// It's async to match the trait definition, though the underlying docker commands are blocking.
|
||||
debug!("Starting OCI image build and push for '{}'", self.name);
|
||||
|
||||
// 1. Build the image by calling the synchronous helper function.
|
||||
let image_tag = self.image_name();
|
||||
self.build_docker_image(&image_tag)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to build Docker image: {}", e))?;
|
||||
debug!("Successfully built Docker image: {}", image_tag);
|
||||
|
||||
// 2. Push the image to the registry.
|
||||
self.push_docker_image(&image_tag)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to push Docker image: {}", e))?;
|
||||
debug!("Successfully pushed Docker image to: {}", image_tag);
|
||||
|
||||
Ok(image_tag)
|
||||
}
|
||||
|
||||
fn local_image_name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
|
||||
fn image_name(&self) -> String {
|
||||
format!(
|
||||
"{}/{}/{}",
|
||||
*REGISTRY_URL,
|
||||
*REGISTRY_PROJECT,
|
||||
&self.local_image_name()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation of helper methods for building and pushing the Docker image.
|
||||
impl RustWebapp {
|
||||
/// Generates a multi-stage Dockerfile for a Rust application.
|
||||
fn build_dockerfile(&self) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let mut dockerfile = Dockerfile::new();
|
||||
|
||||
self.build_builder_image(&mut dockerfile);
|
||||
|
||||
// Save the Dockerfile to a uniquely named file in the project root to avoid conflicts.
|
||||
let dockerfile_path = self.project_root.join("Dockerfile.harmony");
|
||||
fs::write(&dockerfile_path, dockerfile.to_string())?;
|
||||
|
||||
Ok(dockerfile_path)
|
||||
}
|
||||
|
||||
/// Builds the Docker image using the generated Dockerfile.
|
||||
pub async fn build_docker_image(
|
||||
&self,
|
||||
image_name: &str,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
debug!("Generating Dockerfile for '{}'", self.name);
|
||||
let _dockerfile_path = self.build_dockerfile()?;
|
||||
|
||||
let docker = Docker::connect_with_socket_defaults().unwrap();
|
||||
|
||||
let quiet = !log_enabled!(log::Level::Debug);
|
||||
|
||||
let build_image_options = bollard::query_parameters::BuildImageOptionsBuilder::default()
|
||||
.dockerfile("Dockerfile.harmony")
|
||||
.t(image_name)
|
||||
.q(quiet)
|
||||
.version(bollard::query_parameters::BuilderVersion::BuilderV1)
|
||||
.platform("linux/x86_64");
|
||||
|
||||
let mut temp_tar_builder = tar::Builder::new(Vec::new());
|
||||
let _ = temp_tar_builder
|
||||
.append_dir_all("", self.project_root.clone())
|
||||
.unwrap();
|
||||
let archive = temp_tar_builder
|
||||
.into_inner()
|
||||
.expect("couldn't finish creating tar");
|
||||
let archived_files = Archive::new(archive.as_slice())
|
||||
.entries()
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().path().unwrap().into_owned())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
debug!("files in docker tar: {:#?}", archived_files);
|
||||
|
||||
let mut image_build_stream = docker.build_image(
|
||||
build_image_options.build(),
|
||||
None,
|
||||
Some(body_full(archive.into())),
|
||||
);
|
||||
|
||||
while let Some(msg) = image_build_stream.next().await {
|
||||
println!("Message: {msg:?}");
|
||||
}
|
||||
|
||||
Ok(image_name.to_string())
|
||||
}
|
||||
|
||||
/// Tags and pushes a Docker image to the configured remote registry.
|
||||
async fn push_docker_image(
|
||||
&self,
|
||||
image_tag: &str,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
debug!("Pushing docker image {image_tag}");
|
||||
|
||||
let docker = Docker::connect_with_socket_defaults().unwrap();
|
||||
|
||||
// let push_options = PushImageOptionsBuilder::new().tag(tag);
|
||||
|
||||
let mut push_image_stream = docker.push_image(
|
||||
image_tag,
|
||||
Some(PushImageOptionsBuilder::new().build()),
|
||||
None,
|
||||
);
|
||||
|
||||
while let Some(msg) = push_image_stream.next().await {
|
||||
println!("Message: {msg:?}");
|
||||
}
|
||||
|
||||
Ok(image_tag.to_string())
|
||||
}
|
||||
|
||||
/// Checks the output of a process command for success.
|
||||
fn check_output(
|
||||
&self,
|
||||
output: &process::Output,
|
||||
msg: &str,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if !output.status.success() {
|
||||
let error_message = format!("{}: {}", msg, String::from_utf8_lossy(&output.stderr));
|
||||
return Err(error_message.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_builder_image(&self, dockerfile: &mut Dockerfile) {
|
||||
match self.framework {
|
||||
Some(RustWebFramework::Leptos) => {
|
||||
// --- Stage 1: Builder for Leptos ---
|
||||
dockerfile.push(FROM::from("rust:bookworm as builder"));
|
||||
|
||||
// Install dependencies, cargo-binstall, and clean up in one layer
|
||||
dockerfile.push(RUN::from(
|
||||
"apt-get update && \
|
||||
apt-get install -y --no-install-recommends clang wget && \
|
||||
wget https://github.com/cargo-bins/cargo-binstall/releases/latest/download/cargo-binstall-x86_64-unknown-linux-musl.tgz && \
|
||||
tar -xvf cargo-binstall-x86_64-unknown-linux-musl.tgz && \
|
||||
cp cargo-binstall /usr/local/cargo/bin && \
|
||||
rm cargo-binstall-x86_64-unknown-linux-musl.tgz cargo-binstall && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/*"
|
||||
));
|
||||
|
||||
// Install cargo-leptos
|
||||
dockerfile.push(RUN::from("cargo binstall cargo-leptos -y"));
|
||||
|
||||
// Add the WASM target
|
||||
dockerfile.push(RUN::from("rustup target add wasm32-unknown-unknown"));
|
||||
|
||||
// Set up workdir, copy source, and build
|
||||
dockerfile.push(WORKDIR::from("/app"));
|
||||
dockerfile.push(COPY::from(". ."));
|
||||
dockerfile.push(RUN::from("cargo leptos build --release -vv"));
|
||||
// --- Stage 2: Final Image ---
|
||||
dockerfile.push(FROM::from("debian:bookworm-slim"));
|
||||
|
||||
// Create a non-root user for security.
|
||||
dockerfile.push(RUN::from(
|
||||
"groupadd -r appgroup && useradd -r -s /bin/false -g appgroup appuser",
|
||||
));
|
||||
|
||||
dockerfile.push(ENV::from("LEPTOS_SITE_ADDR=0.0.0.0:3000"));
|
||||
dockerfile.push(EXPOSE::from("3000/tcp"));
|
||||
dockerfile.push(WORKDIR::from("/home/appuser"));
|
||||
|
||||
// Copy static files
|
||||
dockerfile.push(
|
||||
CopyBuilder::builder()
|
||||
.from("builder")
|
||||
.src("/app/target/site/pkg")
|
||||
.dest("/home/appuser/pkg")
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
// Copy the compiled binary from the builder stage.
|
||||
error!(
|
||||
"FIXME Should not be using score name here, instead should use name from Cargo.toml"
|
||||
);
|
||||
let binary_path_in_builder = format!("/app/target/release/{}", self.name);
|
||||
let binary_path_in_final = format!("/home/appuser/{}", self.name);
|
||||
dockerfile.push(
|
||||
CopyBuilder::builder()
|
||||
.from("builder")
|
||||
.src(binary_path_in_builder)
|
||||
.dest(&binary_path_in_final)
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
// Run as the non-root user.
|
||||
dockerfile.push(USER::from("appuser"));
|
||||
|
||||
// Set the command to run the application.
|
||||
dockerfile.push(CMD::from(binary_path_in_final));
|
||||
}
|
||||
None => {
|
||||
// --- Stage 1: Builder for a generic Rust app ---
|
||||
dockerfile.push(FROM::from("rust:latest as builder"));
|
||||
|
||||
// Install the wasm32 target as required.
|
||||
dockerfile.push(RUN::from("rustup target add wasm32-unknown-unknown"));
|
||||
dockerfile.push(WORKDIR::from("/app"));
|
||||
|
||||
// Copy the source code and build the application.
|
||||
dockerfile.push(COPY::from(". ."));
|
||||
dockerfile.push(RUN::from("cargo build --release --locked"));
|
||||
// --- Stage 2: Final Image ---
|
||||
dockerfile.push(FROM::from("debian:bookworm-slim"));
|
||||
|
||||
// Create a non-root user for security.
|
||||
dockerfile.push(RUN::from(
|
||||
"groupadd -r appgroup && useradd -r -s /bin/false -g appgroup appuser",
|
||||
));
|
||||
|
||||
// Copy only the compiled binary from the builder stage.
|
||||
error!(
|
||||
"FIXME Should not be using score name here, instead should use name from Cargo.toml"
|
||||
);
|
||||
let binary_path_in_builder = format!("/app/target/release/{}", self.name);
|
||||
let binary_path_in_final = format!("/usr/local/bin/{}", self.name);
|
||||
dockerfile.push(
|
||||
CopyBuilder::builder()
|
||||
.from("builder")
|
||||
.src(binary_path_in_builder)
|
||||
.dest(&binary_path_in_final)
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
// Run as the non-root user.
|
||||
dockerfile.push(USER::from("appuser"));
|
||||
|
||||
// Set the command to run the application.
|
||||
dockerfile.push(CMD::from(binary_path_in_final));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates all necessary files for a basic Helm chart.
|
||||
fn create_helm_chart_files(
|
||||
&self,
|
||||
image_url: &str,
|
||||
) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let chart_name = format!("{}-chart", self.name);
|
||||
let chart_dir = self
|
||||
.project_root
|
||||
.join(".harmony_generated")
|
||||
.join("helm")
|
||||
.join(&chart_name);
|
||||
let templates_dir = chart_dir.join("templates");
|
||||
fs::create_dir_all(&templates_dir)?;
|
||||
|
||||
let (image_repo, image_tag) = image_url.rsplit_once(':').unwrap_or((image_url, "latest"));
|
||||
|
||||
// Create Chart.yaml
|
||||
let chart_yaml = format!(
|
||||
r#"
|
||||
apiVersion: v2
|
||||
name: {}
|
||||
description: A Helm chart for the {} web application.
|
||||
type: application
|
||||
version: 0.1.0
|
||||
appVersion: "{}"
|
||||
"#,
|
||||
chart_name, self.name, image_tag
|
||||
);
|
||||
fs::write(chart_dir.join("Chart.yaml"), chart_yaml)?;
|
||||
|
||||
// Create values.yaml
|
||||
let values_yaml = format!(
|
||||
r#"
|
||||
# Default values for {}.
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
replicaCount: 1
|
||||
|
||||
image:
|
||||
repository: {}
|
||||
pullPolicy: IfNotPresent
|
||||
# Overridden by the chart's appVersion
|
||||
tag: "{}"
|
||||
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 3000
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
# Annotations for cert-manager to handle SSL.
|
||||
annotations:
|
||||
cert-manager.io/cluster-issuer: "letsencrypt-prod"
|
||||
# Add other annotations like nginx ingress class if needed
|
||||
# kubernetes.io/ingress.class: nginx
|
||||
hosts:
|
||||
- host: chart-example.local
|
||||
paths:
|
||||
- path: /
|
||||
pathType: ImplementationSpecific
|
||||
tls:
|
||||
- secretName: {}-tls
|
||||
hosts:
|
||||
- chart-example.local
|
||||
|
||||
"#,
|
||||
chart_name, image_repo, image_tag, self.name
|
||||
);
|
||||
fs::write(chart_dir.join("values.yaml"), values_yaml)?;
|
||||
|
||||
// Create templates/_helpers.tpl
|
||||
let helpers_tpl = r#"
|
||||
{{/*
|
||||
Expand the name of the chart.
|
||||
*/}}
|
||||
{{- define "chart.name" -}}
|
||||
{{- default .Chart.Name $.Values.nameOverride | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
|
||||
{{/*
|
||||
Create a default fully qualified app name.
|
||||
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
|
||||
*/}}
|
||||
{{- define "chart.fullname" -}}
|
||||
{{- $name := default .Chart.Name $.Values.nameOverride }}
|
||||
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
|
||||
{{- end }}
|
||||
"#;
|
||||
fs::write(templates_dir.join("_helpers.tpl"), helpers_tpl)?;
|
||||
|
||||
// Create templates/service.yaml
|
||||
let service_yaml = r#"
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: {{ include "chart.fullname" . }}
|
||||
spec:
|
||||
type: {{ $.Values.service.type }}
|
||||
ports:
|
||||
- name: main
|
||||
port: {{ $.Values.service.port | default 3000 }}
|
||||
targetPort: {{ $.Values.service.port | default 3000 }}
|
||||
protocol: TCP
|
||||
selector:
|
||||
app: {{ include "chart.name" . }}
|
||||
"#;
|
||||
fs::write(templates_dir.join("service.yaml"), service_yaml)?;
|
||||
|
||||
// Create templates/deployment.yaml
|
||||
let deployment_yaml = r#"
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: {{ include "chart.fullname" . }}
|
||||
spec:
|
||||
replicas: {{ $.Values.replicaCount }}
|
||||
selector:
|
||||
matchLabels:
|
||||
app: {{ include "chart.name" . }}
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: {{ include "chart.name" . }}
|
||||
spec:
|
||||
containers:
|
||||
- name: {{ .Chart.Name }}
|
||||
image: "{{ $.Values.image.repository }}:{{ $.Values.image.tag | default .Chart.AppVersion }}"
|
||||
imagePullPolicy: {{ $.Values.image.pullPolicy }}
|
||||
ports:
|
||||
- name: main
|
||||
containerPort: {{ $.Values.service.port | default 3000 }}
|
||||
protocol: TCP
|
||||
"#;
|
||||
fs::write(templates_dir.join("deployment.yaml"), deployment_yaml)?;
|
||||
|
||||
// Create templates/ingress.yaml
|
||||
let ingress_yaml = r#"
|
||||
{{- if $.Values.ingress.enabled -}}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "chart.fullname" . }}
|
||||
annotations:
|
||||
{{- toYaml $.Values.ingress.annotations | nindent 4 }}
|
||||
spec:
|
||||
{{- if $.Values.ingress.tls }}
|
||||
tls:
|
||||
{{- range $.Values.ingress.tls }}
|
||||
- hosts:
|
||||
{{- range .hosts }}
|
||||
- {{ . | quote }}
|
||||
{{- end }}
|
||||
secretName: {{ .secretName }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
rules:
|
||||
{{- range $.Values.ingress.hosts }}
|
||||
- host: {{ .host | quote }}
|
||||
http:
|
||||
paths:
|
||||
{{- range .paths }}
|
||||
- path: {{ .path }}
|
||||
pathType: {{ .pathType }}
|
||||
backend:
|
||||
service:
|
||||
name: {{ include "chart.fullname" $ }}
|
||||
port:
|
||||
number: {{ $.Values.service.port | default 3000 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
"#;
|
||||
fs::write(templates_dir.join("ingress.yaml"), ingress_yaml)?;
|
||||
|
||||
Ok(chart_dir)
|
||||
}
|
||||
|
||||
/// Packages a Helm chart directory into a .tgz file.
|
||||
fn package_helm_chart(
|
||||
&self,
|
||||
chart_dir: &PathBuf,
|
||||
) -> Result<PathBuf, Box<dyn std::error::Error>> {
|
||||
let chart_dirname = chart_dir.file_name().expect("Should find a chart dirname");
|
||||
debug!(
|
||||
"Launching `helm package {}` cli with CWD {}",
|
||||
chart_dirname.to_string_lossy(),
|
||||
&self
|
||||
.project_root
|
||||
.join(".harmony_generated")
|
||||
.join("helm")
|
||||
.to_string_lossy()
|
||||
);
|
||||
let output = process::Command::new("helm")
|
||||
.args(["package", chart_dirname.to_str().unwrap()])
|
||||
.current_dir(&self.project_root.join(".harmony_generated").join("helm")) // Run package from the parent dir
|
||||
.output()?;
|
||||
|
||||
self.check_output(&output, "Failed to package Helm chart")?;
|
||||
|
||||
// Helm prints the path of the created chart to stdout.
|
||||
let tgz_name = String::from_utf8(output.stdout)?
|
||||
.trim()
|
||||
.split_whitespace()
|
||||
.last()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
if tgz_name.is_empty() {
|
||||
return Err("Could not determine packaged chart filename.".into());
|
||||
}
|
||||
|
||||
// The output from helm is relative, so we join it with the execution directory.
|
||||
Ok(self
|
||||
.project_root
|
||||
.join(".harmony_generated")
|
||||
.join("helm")
|
||||
.join(tgz_name))
|
||||
}
|
||||
|
||||
/// Pushes a packaged Helm chart to an OCI registry.
|
||||
fn push_helm_chart(
|
||||
&self,
|
||||
packaged_chart_path: &PathBuf,
|
||||
) -> Result<String, Box<dyn std::error::Error>> {
|
||||
// The chart name is the file stem of the .tgz file
|
||||
let chart_file_name = packaged_chart_path.file_stem().unwrap().to_str().unwrap();
|
||||
let oci_push_url = format!("oci://{}/{}", *REGISTRY_URL, *REGISTRY_PROJECT);
|
||||
let oci_pull_url = format!("{oci_push_url}/{}-chart", self.name);
|
||||
|
||||
debug!(
|
||||
"Pushing Helm chart {} to {}",
|
||||
packaged_chart_path.to_string_lossy(),
|
||||
oci_push_url
|
||||
);
|
||||
|
||||
let output = process::Command::new("helm")
|
||||
.args(["push", packaged_chart_path.to_str().unwrap(), &oci_push_url])
|
||||
.output()?;
|
||||
|
||||
self.check_output(&output, "Pushing Helm chart failed")?;
|
||||
|
||||
// The final URL includes the version tag, which is part of the file name
|
||||
let version = chart_file_name.rsplit_once('-').unwrap().1;
|
||||
debug!("pull url {oci_pull_url}");
|
||||
debug!("push url {oci_push_url}");
|
||||
Ok(format!("{}:{}", oci_pull_url, version))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,25 +10,14 @@ use crate::{
|
||||
topology::{HttpServer, Topology, Url},
|
||||
};
|
||||
|
||||
/// Configure an HTTP server that is provided by the Topology
|
||||
///
|
||||
/// This Score will let you easily specify a file path to be served by the HTTP server
|
||||
///
|
||||
/// For example, if you have a folder of assets at `/var/www/assets` simply do :
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// StaticFilesHttpScore {
|
||||
/// files_to_serve: url!("file:///var/www/assets"),
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Debug, new, Clone, Serialize)]
|
||||
pub struct StaticFilesHttpScore {
|
||||
pub struct HttpScore {
|
||||
files_to_serve: Url,
|
||||
}
|
||||
|
||||
impl<T: Topology + HttpServer> Score<T> for StaticFilesHttpScore {
|
||||
impl<T: Topology + HttpServer> Score<T> for HttpScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(StaticFilesHttpInterpret::new(self.clone()))
|
||||
Box::new(HttpInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
@@ -37,12 +26,12 @@ impl<T: Topology + HttpServer> Score<T> for StaticFilesHttpScore {
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
pub struct StaticFilesHttpInterpret {
|
||||
score: StaticFilesHttpScore,
|
||||
pub struct HttpInterpret {
|
||||
score: HttpScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + HttpServer> Interpret<T> for StaticFilesHttpInterpret {
|
||||
impl<T: Topology + HttpServer> Interpret<T> for HttpInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, info};
|
||||
use log::info;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
config::HARMONY_DATA_DIR,
|
||||
config::HARMONY_CONFIG_DIR,
|
||||
data::{Id, Version},
|
||||
instrumentation::{self, HarmonyEvent},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
@@ -23,7 +22,7 @@ pub struct K3DInstallationScore {
|
||||
impl Default for K3DInstallationScore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
installation_path: HARMONY_DATA_DIR.join("k3d"),
|
||||
installation_path: HARMONY_CONFIG_DIR.join("k3d"),
|
||||
cluster_name: "harmony".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -51,38 +50,22 @@ impl<T: Topology> Interpret<T> for K3dInstallationInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
_inventory: &Inventory,
|
||||
topology: &T,
|
||||
_topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
instrumentation::instrument(HarmonyEvent::InterpretExecutionStarted {
|
||||
topology: topology.name().into(),
|
||||
interpret: "k3d-installation".into(),
|
||||
message: "installing k3d...".into(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let k3d = k3d_rs::K3d::new(
|
||||
self.score.installation_path.clone(),
|
||||
Some(self.score.cluster_name.clone()),
|
||||
);
|
||||
let outcome = match k3d.ensure_installed().await {
|
||||
match k3d.ensure_installed().await {
|
||||
Ok(_client) => {
|
||||
let msg = format!("k3d cluster '{}' installed ", self.score.cluster_name);
|
||||
debug!("{msg}");
|
||||
let msg = format!("k3d cluster {} is installed ", self.score.cluster_name);
|
||||
info!("{msg}");
|
||||
Ok(Outcome::success(msg))
|
||||
}
|
||||
Err(msg) => Err(InterpretError::new(format!(
|
||||
"failed to ensure k3d is installed : {msg}"
|
||||
"K3dInstallationInterpret failed to ensure k3d is installed : {msg}"
|
||||
))),
|
||||
};
|
||||
|
||||
instrumentation::instrument(HarmonyEvent::InterpretExecutionFinished {
|
||||
topology: topology.name().into(),
|
||||
interpret: "k3d-installation".into(),
|
||||
outcome: outcome.clone(),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
outcome
|
||||
}
|
||||
}
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::K3dInstallation
|
||||
|
||||
@@ -16,3 +16,4 @@ pub mod opnsense;
|
||||
pub mod prometheus;
|
||||
pub mod tenant;
|
||||
pub mod tftp;
|
||||
pub mod postgres;
|
||||
|
||||
@@ -4,13 +4,10 @@ use serde_yaml::{Mapping, Value};
|
||||
|
||||
use crate::{
|
||||
interpret::{InterpretError, Outcome},
|
||||
modules::monitoring::{
|
||||
kube_prometheus::{
|
||||
prometheus::{KubePrometheus, KubePrometheusReceiver},
|
||||
modules::monitoring::kube_prometheus::{
|
||||
prometheus::{Prometheus, PrometheusReceiver},
|
||||
types::{AlertChannelConfig, AlertManagerChannelConfig},
|
||||
},
|
||||
prometheus::prometheus::{Prometheus, PrometheusReceiver},
|
||||
},
|
||||
topology::{Url, oberservability::monitoring::AlertReceiver},
|
||||
};
|
||||
|
||||
@@ -40,26 +37,6 @@ impl PrometheusReceiver for DiscordWebhook {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AlertReceiver<KubePrometheus> for DiscordWebhook {
|
||||
async fn install(&self, sender: &KubePrometheus) -> Result<Outcome, InterpretError> {
|
||||
sender.install_receiver(self).await
|
||||
}
|
||||
fn clone_box(&self) -> Box<dyn AlertReceiver<KubePrometheus>> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl KubePrometheusReceiver for DiscordWebhook {
|
||||
fn name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
async fn configure_receiver(&self) -> AlertManagerChannelConfig {
|
||||
self.get_config().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AlertChannelConfig for DiscordWebhook {
|
||||
async fn get_config(&self) -> AlertManagerChannelConfig {
|
||||
|
||||
@@ -4,13 +4,10 @@ use serde_yaml::{Mapping, Value};
|
||||
|
||||
use crate::{
|
||||
interpret::{InterpretError, Outcome},
|
||||
modules::monitoring::{
|
||||
kube_prometheus::{
|
||||
prometheus::{KubePrometheus, KubePrometheusReceiver},
|
||||
modules::monitoring::kube_prometheus::{
|
||||
prometheus::{Prometheus, PrometheusReceiver},
|
||||
types::{AlertChannelConfig, AlertManagerChannelConfig},
|
||||
},
|
||||
prometheus::prometheus::{Prometheus, PrometheusReceiver},
|
||||
},
|
||||
topology::{Url, oberservability::monitoring::AlertReceiver},
|
||||
};
|
||||
|
||||
@@ -39,25 +36,6 @@ impl PrometheusReceiver for WebhookReceiver {
|
||||
self.get_config().await
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl AlertReceiver<KubePrometheus> for WebhookReceiver {
|
||||
async fn install(&self, sender: &KubePrometheus) -> Result<Outcome, InterpretError> {
|
||||
sender.install_receiver(self).await
|
||||
}
|
||||
fn clone_box(&self) -> Box<dyn AlertReceiver<KubePrometheus>> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl KubePrometheusReceiver for WebhookReceiver {
|
||||
fn name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
async fn configure_receiver(&self) -> AlertManagerChannelConfig {
|
||||
self.get_config().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AlertChannelConfig for WebhookReceiver {
|
||||
|
||||
@@ -5,26 +5,13 @@ use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::{InterpretError, Outcome},
|
||||
modules::monitoring::{
|
||||
kube_prometheus::{
|
||||
prometheus::{KubePrometheus, KubePrometheusRule},
|
||||
modules::monitoring::kube_prometheus::{
|
||||
prometheus::{Prometheus, PrometheusRule},
|
||||
types::{AlertGroup, AlertManagerAdditionalPromRules},
|
||||
},
|
||||
prometheus::prometheus::{Prometheus, PrometheusRule},
|
||||
},
|
||||
topology::oberservability::monitoring::AlertRule,
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
impl AlertRule<KubePrometheus> for AlertManagerRuleGroup {
|
||||
async fn install(&self, sender: &KubePrometheus) -> Result<Outcome, InterpretError> {
|
||||
sender.install_rule(&self).await
|
||||
}
|
||||
fn clone_box(&self) -> Box<dyn AlertRule<KubePrometheus>> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AlertRule<Prometheus> for AlertManagerRuleGroup {
|
||||
async fn install(&self, sender: &Prometheus) -> Result<Outcome, InterpretError> {
|
||||
@@ -54,25 +41,6 @@ impl PrometheusRule for AlertManagerRuleGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl KubePrometheusRule for AlertManagerRuleGroup {
|
||||
fn name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
async fn configure_rule(&self) -> AlertManagerAdditionalPromRules {
|
||||
let mut additional_prom_rules = BTreeMap::new();
|
||||
|
||||
additional_prom_rules.insert(
|
||||
self.name.clone(),
|
||||
AlertGroup {
|
||||
groups: vec![self.clone()],
|
||||
},
|
||||
);
|
||||
AlertManagerAdditionalPromRules {
|
||||
rules: additional_prom_rules,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AlertManagerRuleGroup {
|
||||
pub fn new(name: &str, rules: Vec<PrometheusAlertRule>) -> AlertManagerRuleGroup {
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
modules::monitoring::{
|
||||
kube_prometheus::types::ServiceMonitor,
|
||||
prometheus::{prometheus::Prometheus, prometheus_config::PrometheusConfig},
|
||||
},
|
||||
score::Score,
|
||||
topology::{
|
||||
HelmCommand, Topology,
|
||||
oberservability::monitoring::{AlertReceiver, AlertRule, AlertingInterpret},
|
||||
tenant::TenantManager,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct ApplicationPrometheusMonitoringScore {
|
||||
pub receivers: Vec<Box<dyn AlertReceiver<Prometheus>>>,
|
||||
pub rules: Vec<Box<dyn AlertRule<Prometheus>>>,
|
||||
pub service_monitors: Vec<ServiceMonitor>,
|
||||
}
|
||||
|
||||
impl<T: Topology + HelmCommand + TenantManager> Score<T> for ApplicationPrometheusMonitoringScore {
|
||||
fn create_interpret(&self) -> Box<dyn crate::interpret::Interpret<T>> {
|
||||
let mut prom_config = PrometheusConfig::new();
|
||||
prom_config.alert_manager = true;
|
||||
|
||||
let config = Arc::new(Mutex::new(prom_config));
|
||||
config
|
||||
.try_lock()
|
||||
.expect("couldn't lock config")
|
||||
.additional_service_monitors = self.service_monitors.clone();
|
||||
Box::new(AlertingInterpret {
|
||||
sender: Prometheus::new(),
|
||||
receivers: self.receivers.clone(),
|
||||
rules: self.rules.clone(),
|
||||
})
|
||||
}
|
||||
fn name(&self) -> String {
|
||||
"ApplicationPrometheusMonitoringScore".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod k8s_application_monitoring_score;
|
||||
@@ -1,28 +0,0 @@
|
||||
use non_blank_string_rs::NonBlankString;
|
||||
use std::str::FromStr;
|
||||
|
||||
use crate::modules::helm::chart::HelmChartScore;
|
||||
|
||||
pub fn grafana_helm_chart_score(ns: &str) -> HelmChartScore {
|
||||
let values = format!(
|
||||
r#"
|
||||
rbac:
|
||||
namespaced: true
|
||||
sidecar:
|
||||
dashboards:
|
||||
enabled: true
|
||||
"#
|
||||
);
|
||||
|
||||
HelmChartScore {
|
||||
namespace: Some(NonBlankString::from_str(ns).unwrap()),
|
||||
release_name: NonBlankString::from_str("grafana").unwrap(),
|
||||
chart_name: NonBlankString::from_str("oci://ghcr.io/grafana/helm-charts/grafana").unwrap(),
|
||||
chart_version: None,
|
||||
values_overrides: None,
|
||||
values_yaml: Some(values.to_string()),
|
||||
create_namespace: true,
|
||||
install_only: true,
|
||||
repository: None,
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
pub mod helm_grafana;
|
||||
@@ -1 +0,0 @@
|
||||
pub mod helm;
|
||||
@@ -38,15 +38,15 @@ impl KubePrometheusConfig {
|
||||
node_exporter: false,
|
||||
prometheus: true,
|
||||
kubernetes_service_monitors: true,
|
||||
kubernetes_api_server: true,
|
||||
kubernetes_api_server: false,
|
||||
kubelet: true,
|
||||
kube_controller_manager: true,
|
||||
kube_etcd: true,
|
||||
kube_proxy: true,
|
||||
kube_controller_manager: false,
|
||||
kube_etcd: false,
|
||||
kube_proxy: false,
|
||||
kube_state_metrics: true,
|
||||
prometheus_operator: true,
|
||||
core_dns: true,
|
||||
kube_scheduler: true,
|
||||
core_dns: false,
|
||||
kube_scheduler: false,
|
||||
alert_receiver_configs: vec![],
|
||||
alert_rules: vec![],
|
||||
additional_service_monitors: vec![],
|
||||
|
||||
@@ -68,9 +68,6 @@ pub fn kube_prometheus_helm_chart_score(
|
||||
|
||||
let mut values = format!(
|
||||
r#"
|
||||
global:
|
||||
rbac:
|
||||
create: true
|
||||
prometheus:
|
||||
enabled: {prometheus}
|
||||
prometheusSpec:
|
||||
@@ -245,7 +242,7 @@ prometheus-node-exporter:
|
||||
cpu: 200m
|
||||
memory: 250Mi
|
||||
prometheusOperator:
|
||||
enabled: true
|
||||
enabled: {prometheus_operator}
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{helm::config::KubePrometheusConfig, prometheus::KubePrometheus};
|
||||
use super::{helm::config::KubePrometheusConfig, prometheus::Prometheus};
|
||||
use crate::{
|
||||
modules::monitoring::kube_prometheus::types::ServiceMonitor,
|
||||
score::Score,
|
||||
@@ -15,8 +15,8 @@ use crate::{
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct HelmPrometheusAlertingScore {
|
||||
pub receivers: Vec<Box<dyn AlertReceiver<KubePrometheus>>>,
|
||||
pub rules: Vec<Box<dyn AlertRule<KubePrometheus>>>,
|
||||
pub receivers: Vec<Box<dyn AlertReceiver<Prometheus>>>,
|
||||
pub rules: Vec<Box<dyn AlertRule<Prometheus>>>,
|
||||
pub service_monitors: Vec<ServiceMonitor>,
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ impl<T: Topology + HelmCommand + TenantManager> Score<T> for HelmPrometheusAlert
|
||||
.expect("couldn't lock config")
|
||||
.additional_service_monitors = self.service_monitors.clone();
|
||||
Box::new(AlertingInterpret {
|
||||
sender: KubePrometheus { config },
|
||||
sender: Prometheus::new(),
|
||||
receivers: self.receivers.clone(),
|
||||
rules: self.rules.clone(),
|
||||
})
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
modules::monitoring::alert_rule::prometheus_alert_rule::AlertManagerRuleGroup,
|
||||
score,
|
||||
topology::{
|
||||
HelmCommand, Topology,
|
||||
HelmCommand, K8sAnywhereTopology, Topology,
|
||||
installable::Installable,
|
||||
oberservability::monitoring::{AlertReceiver, AlertRule, AlertSender},
|
||||
tenant::TenantManager,
|
||||
@@ -27,14 +27,14 @@ use super::{
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
impl AlertSender for KubePrometheus {
|
||||
impl AlertSender for Prometheus {
|
||||
fn name(&self) -> String {
|
||||
"HelmKubePrometheus".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + HelmCommand + TenantManager> Installable<T> for KubePrometheus {
|
||||
impl<T: Topology + HelmCommand + TenantManager> Installable<T> for Prometheus {
|
||||
async fn configure(&self, _inventory: &Inventory, topology: &T) -> Result<(), InterpretError> {
|
||||
self.configure_with_topology(topology).await;
|
||||
Ok(())
|
||||
@@ -51,11 +51,11 @@ impl<T: Topology + HelmCommand + TenantManager> Installable<T> for KubePrometheu
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct KubePrometheus {
|
||||
pub struct Prometheus {
|
||||
pub config: Arc<Mutex<KubePrometheusConfig>>,
|
||||
}
|
||||
|
||||
impl KubePrometheus {
|
||||
impl Prometheus {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
config: Arc::new(Mutex::new(KubePrometheusConfig::new())),
|
||||
@@ -75,7 +75,7 @@ impl KubePrometheus {
|
||||
|
||||
pub async fn install_receiver(
|
||||
&self,
|
||||
prometheus_receiver: &dyn KubePrometheusReceiver,
|
||||
prometheus_receiver: &dyn PrometheusReceiver,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let prom_receiver = prometheus_receiver.configure_receiver().await;
|
||||
debug!(
|
||||
@@ -120,12 +120,12 @@ impl KubePrometheus {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait KubePrometheusReceiver: Send + Sync + std::fmt::Debug {
|
||||
pub trait PrometheusReceiver: Send + Sync + std::fmt::Debug {
|
||||
fn name(&self) -> String;
|
||||
async fn configure_receiver(&self) -> AlertManagerChannelConfig;
|
||||
}
|
||||
|
||||
impl Serialize for Box<dyn AlertReceiver<KubePrometheus>> {
|
||||
impl Serialize for Box<dyn AlertReceiver<Prometheus>> {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
@@ -134,19 +134,19 @@ impl Serialize for Box<dyn AlertReceiver<KubePrometheus>> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Box<dyn AlertReceiver<KubePrometheus>> {
|
||||
impl Clone for Box<dyn AlertReceiver<Prometheus>> {
|
||||
fn clone(&self) -> Self {
|
||||
self.clone_box()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait KubePrometheusRule: Send + Sync + std::fmt::Debug {
|
||||
pub trait PrometheusRule: Send + Sync + std::fmt::Debug {
|
||||
fn name(&self) -> String;
|
||||
async fn configure_rule(&self) -> AlertManagerAdditionalPromRules;
|
||||
}
|
||||
|
||||
impl Serialize for Box<dyn AlertRule<KubePrometheus>> {
|
||||
impl Serialize for Box<dyn AlertRule<Prometheus>> {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
@@ -155,7 +155,7 @@ impl Serialize for Box<dyn AlertRule<KubePrometheus>> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Box<dyn AlertRule<KubePrometheus>> {
|
||||
impl Clone for Box<dyn AlertRule<Prometheus>> {
|
||||
fn clone(&self) -> Self {
|
||||
self.clone_box()
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@ pub struct ServiceMonitor {
|
||||
pub name: String,
|
||||
|
||||
// # Additional labels to set used for the ServiceMonitorSelector. Together with standard labels from the chart
|
||||
pub additional_labels: Option<HashMap<String, String>>,
|
||||
pub additional_labels: Option<Mapping>,
|
||||
|
||||
// # Service label for use in assembling a job name of the form <label value>-<port>
|
||||
// # If no label is specified, the service name is used.
|
||||
@@ -240,7 +240,7 @@ pub struct ServiceMonitor {
|
||||
// any: bool,
|
||||
// # Explicit list of namespace names to select
|
||||
// matchNames: Vec,
|
||||
pub namespace_selector: Option<NamespaceSelector>,
|
||||
pub namespace_selector: Option<Mapping>,
|
||||
|
||||
// # Endpoints of the selected service to be monitored
|
||||
pub endpoints: Vec<ServiceMonitorEndpoint>,
|
||||
@@ -250,13 +250,6 @@ pub struct ServiceMonitor {
|
||||
pub fallback_scrape_protocol: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct NamespaceSelector {
|
||||
pub any: bool,
|
||||
pub match_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for ServiceMonitor {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
pub mod alert_channel;
|
||||
pub mod alert_rule;
|
||||
pub mod application_monitoring;
|
||||
pub mod grafana;
|
||||
pub mod kube_prometheus;
|
||||
pub mod ntfy;
|
||||
pub mod prometheus;
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::str::FromStr;
|
||||
|
||||
use crate::modules::helm::chart::{HelmChartScore, HelmRepository};
|
||||
|
||||
pub fn ntfy_helm_chart_score(namespace: String, host: String) -> HelmChartScore {
|
||||
pub fn ntfy_helm_chart_score(namespace: String) -> HelmChartScore {
|
||||
let values = format!(
|
||||
r#"
|
||||
replicaCount: 1
|
||||
@@ -28,12 +28,12 @@ service:
|
||||
port: 80
|
||||
|
||||
ingress:
|
||||
enabled: true
|
||||
enabled: false
|
||||
# annotations:
|
||||
# kubernetes.io/ingress.class: nginx
|
||||
# kubernetes.io/tls-acme: "true"
|
||||
hosts:
|
||||
- host: {host}
|
||||
- host: ntfy.host.com
|
||||
paths:
|
||||
- path: /
|
||||
pathType: ImplementationSpecific
|
||||
|
||||
@@ -17,7 +17,6 @@ use crate::{
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct NtfyScore {
|
||||
pub namespace: String,
|
||||
pub host: String,
|
||||
}
|
||||
|
||||
impl<T: Topology + HelmCommand + K8sclient> Score<T> for NtfyScore {
|
||||
@@ -127,7 +126,7 @@ impl<T: Topology + HelmCommand + K8sclient> Interpret<T> for NtfyInterpret {
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
ntfy_helm_chart_score(self.score.namespace.clone(), self.score.host.clone())
|
||||
ntfy_helm_chart_score(self.score.namespace.clone())
|
||||
.create_interpret()
|
||||
.execute(inventory, topology)
|
||||
.await?;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
pub mod prometheus_helm;
|
||||
@@ -1,47 +0,0 @@
|
||||
use std::str::FromStr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use non_blank_string_rs::NonBlankString;
|
||||
|
||||
use crate::modules::{
|
||||
helm::chart::HelmChartScore, monitoring::prometheus::prometheus_config::PrometheusConfig,
|
||||
};
|
||||
|
||||
pub fn prometheus_helm_chart_score(config: Arc<Mutex<PrometheusConfig>>) -> HelmChartScore {
|
||||
let config = config.lock().unwrap();
|
||||
let ns = config.namespace.clone().unwrap();
|
||||
let values = format!(
|
||||
r#"
|
||||
rbac:
|
||||
create: true
|
||||
kube-state-metrics:
|
||||
enabled: false
|
||||
nodeExporter:
|
||||
enabled: false
|
||||
alertmanager:
|
||||
enabled: false
|
||||
pushgateway:
|
||||
enabled: false
|
||||
server:
|
||||
serviceAccount:
|
||||
create: false
|
||||
rbac:
|
||||
create: true
|
||||
fullnameOverride: prometheus-{ns}
|
||||
"#
|
||||
);
|
||||
HelmChartScore {
|
||||
namespace: Some(NonBlankString::from_str(&config.namespace.clone().unwrap()).unwrap()),
|
||||
release_name: NonBlankString::from_str("prometheus").unwrap(),
|
||||
chart_name: NonBlankString::from_str(
|
||||
"oci://ghcr.io/prometheus-community/charts/prometheus",
|
||||
)
|
||||
.unwrap(),
|
||||
chart_version: None,
|
||||
values_overrides: None,
|
||||
values_yaml: Some(values.to_string()),
|
||||
create_namespace: true,
|
||||
install_only: true,
|
||||
repository: None,
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
pub mod helm;
|
||||
pub mod prometheus;
|
||||
pub mod prometheus_config;
|
||||
@@ -1,190 +0,0 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, error};
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
interpret::{InterpretError, Outcome},
|
||||
inventory::Inventory,
|
||||
modules::monitoring::{
|
||||
alert_rule::prometheus_alert_rule::AlertManagerRuleGroup,
|
||||
grafana::helm::helm_grafana::grafana_helm_chart_score,
|
||||
kube_prometheus::types::{AlertManagerAdditionalPromRules, AlertManagerChannelConfig},
|
||||
},
|
||||
score::Score,
|
||||
topology::{
|
||||
HelmCommand, Topology,
|
||||
installable::Installable,
|
||||
oberservability::monitoring::{AlertReceiver, AlertRule, AlertSender},
|
||||
tenant::TenantManager,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
helm::prometheus_helm::prometheus_helm_chart_score, prometheus_config::PrometheusConfig,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Prometheus {
|
||||
pub config: Arc<Mutex<PrometheusConfig>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl AlertSender for Prometheus {
|
||||
fn name(&self) -> String {
|
||||
"Prometheus".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Prometheus {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
config: Arc::new(Mutex::new(PrometheusConfig::new())),
|
||||
}
|
||||
}
|
||||
pub async fn configure_with_topology<T: TenantManager>(&self, topology: &T) {
|
||||
let ns = topology
|
||||
.get_tenant_config()
|
||||
.await
|
||||
.map(|cfg| cfg.name.clone())
|
||||
.unwrap_or_else(|| "monitoring".to_string());
|
||||
error!("This must be refactored, see comments in pr #74");
|
||||
debug!("NS: {}", ns);
|
||||
self.config.lock().unwrap().namespace = Some(ns);
|
||||
}
|
||||
|
||||
pub async fn install_receiver(
|
||||
&self,
|
||||
prometheus_receiver: &dyn PrometheusReceiver,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let prom_receiver = prometheus_receiver.configure_receiver().await;
|
||||
debug!(
|
||||
"adding alert receiver to prometheus config: {:#?}",
|
||||
&prom_receiver
|
||||
);
|
||||
let mut config = self.config.lock().unwrap();
|
||||
|
||||
config.alert_receiver_configs.push(prom_receiver);
|
||||
let prom_receiver_name = prometheus_receiver.name();
|
||||
debug!("installed alert receiver {}", &prom_receiver_name);
|
||||
Ok(Outcome::success(format!(
|
||||
"Sucessfully installed receiver {}",
|
||||
prom_receiver_name
|
||||
)))
|
||||
}
|
||||
|
||||
pub async fn install_rule(
|
||||
&self,
|
||||
prometheus_rule: &AlertManagerRuleGroup,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let prometheus_rule = prometheus_rule.configure_rule().await;
|
||||
let mut config = self.config.lock().unwrap();
|
||||
|
||||
config.alert_rules.push(prometheus_rule.clone());
|
||||
Ok(Outcome::success(format!(
|
||||
"Successfully installed alert rule: {:#?},",
|
||||
prometheus_rule
|
||||
)))
|
||||
}
|
||||
|
||||
pub async fn install_prometheus<T: Topology + HelmCommand + Send + Sync>(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
prometheus_helm_chart_score(self.config.clone())
|
||||
.create_interpret()
|
||||
.execute(inventory, topology)
|
||||
.await
|
||||
}
|
||||
pub async fn install_grafana<T: Topology + HelmCommand + Send + Sync>(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let namespace = {
|
||||
let config = self.config.lock().unwrap();
|
||||
config.namespace.clone()
|
||||
};
|
||||
|
||||
if let Some(ns) = namespace.as_deref() {
|
||||
grafana_helm_chart_score(ns)
|
||||
.create_interpret()
|
||||
.execute(inventory, topology)
|
||||
.await
|
||||
} else {
|
||||
Err(InterpretError::new(format!(
|
||||
"could not install grafana, missing namespace",
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
#[async_trait]
|
||||
impl<T: Topology + HelmCommand + TenantManager> Installable<T> for Prometheus {
|
||||
async fn configure(&self, _inventory: &Inventory, topology: &T) -> Result<(), InterpretError> {
|
||||
self.configure_with_topology(topology).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_installed(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<(), InterpretError> {
|
||||
self.install_prometheus(inventory, topology).await?;
|
||||
|
||||
let install_grafana = {
|
||||
let config = self.config.lock().unwrap();
|
||||
config.grafana
|
||||
};
|
||||
|
||||
if install_grafana {
|
||||
self.install_grafana(inventory, topology).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PrometheusReceiver: Send + Sync + std::fmt::Debug {
|
||||
fn name(&self) -> String;
|
||||
async fn configure_receiver(&self) -> AlertManagerChannelConfig;
|
||||
}
|
||||
|
||||
impl Serialize for Box<dyn AlertReceiver<Prometheus>> {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Box<dyn AlertReceiver<Prometheus>> {
|
||||
fn clone(&self) -> Self {
|
||||
self.clone_box()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PrometheusRule: Send + Sync + std::fmt::Debug {
|
||||
fn name(&self) -> String;
|
||||
async fn configure_rule(&self) -> AlertManagerAdditionalPromRules;
|
||||
}
|
||||
|
||||
impl Serialize for Box<dyn AlertRule<Prometheus>> {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Box<dyn AlertRule<Prometheus>> {
|
||||
fn clone(&self) -> Self {
|
||||
self.clone_box()
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
use crate::modules::monitoring::kube_prometheus::types::{
|
||||
AlertManagerAdditionalPromRules, AlertManagerChannelConfig, ServiceMonitor,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PrometheusConfig {
|
||||
pub namespace: Option<String>,
|
||||
pub default_rules: bool,
|
||||
pub alert_manager: bool,
|
||||
pub node_exporter: bool,
|
||||
pub kube_state_metrics: bool,
|
||||
pub grafana: bool,
|
||||
pub prometheus_pushgateway: bool,
|
||||
pub alert_receiver_configs: Vec<AlertManagerChannelConfig>,
|
||||
pub alert_rules: Vec<AlertManagerAdditionalPromRules>,
|
||||
pub additional_service_monitors: Vec<ServiceMonitor>,
|
||||
}
|
||||
|
||||
impl PrometheusConfig {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
namespace: None,
|
||||
default_rules: true,
|
||||
alert_manager: true,
|
||||
node_exporter: false,
|
||||
kube_state_metrics: false,
|
||||
grafana: true,
|
||||
prometheus_pushgateway: false,
|
||||
alert_receiver_configs: vec![],
|
||||
alert_rules: vec![],
|
||||
additional_service_monitors: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
119
harmony/src/modules/postgres.rs
Normal file
119
harmony/src/modules/postgres.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use async_trait::async_trait;
|
||||
use derive_new::new;
|
||||
use log::info;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
data::{PostgresDatabase, PostgresUser, Version},
|
||||
interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{PostgresServer, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, new, Clone, Serialize, Deserialize)]
|
||||
pub struct PostgresScore {
|
||||
users: Vec<PostgresUser>,
|
||||
databases: Vec<PostgresDatabase>,
|
||||
}
|
||||
|
||||
impl<T: Topology + PostgresServer> Score<T> for PostgresScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(PostgresInterpret::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"PostgresScore".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PostgresInterpret {
|
||||
score: PostgresScore,
|
||||
version: Version,
|
||||
status: InterpretStatus,
|
||||
}
|
||||
|
||||
impl PostgresInterpret {
|
||||
pub fn new(score: PostgresScore) -> Self {
|
||||
let version = Version::from("1.0.0").expect("Version should be valid");
|
||||
|
||||
Self {
|
||||
version,
|
||||
score,
|
||||
status: InterpretStatus::QUEUED,
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_users_exist<P: PostgresServer>(
|
||||
&self,
|
||||
postgres_server: &P,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let users = &self.score.users;
|
||||
postgres_server.ensure_users_exist(users.clone()).await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!(
|
||||
"PostgresInterpret ensured {} users exist successfully",
|
||||
users.len()
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
async fn ensure_databases_exist<P: PostgresServer>(
|
||||
&self,
|
||||
postgres_server: &P,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
let databases = &self.score.databases;
|
||||
postgres_server
|
||||
.ensure_databases_exist(databases.clone())
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
format!(
|
||||
"PostgresInterpret ensured {} databases exist successfully",
|
||||
databases.len()
|
||||
),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + PostgresServer> Interpret<T> for PostgresInterpret {
|
||||
fn get_name(&self) -> InterpretName {
|
||||
InterpretName::Postgres
|
||||
}
|
||||
|
||||
fn get_version(&self) -> crate::domain::data::Version {
|
||||
self.version.clone()
|
||||
}
|
||||
|
||||
fn get_status(&self) -> InterpretStatus {
|
||||
self.status.clone()
|
||||
}
|
||||
|
||||
fn get_children(&self) -> Vec<crate::domain::data::Id> {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
info!(
|
||||
"Executing {} on inventory {inventory:?})",
|
||||
<PostgresInterpret as Interpret<T>>::get_name(self)
|
||||
);
|
||||
|
||||
self.ensure_users_exist(topology).await?;
|
||||
self.ensure_databases_exist(topology).await?;
|
||||
|
||||
Ok(Outcome::new(
|
||||
InterpretStatus::SUCCESS,
|
||||
"Postgres Interpret execution successful".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,6 @@ harmony_tui = { path = "../harmony_tui", optional = true }
|
||||
inquire.workspace = true
|
||||
tokio.workspace = true
|
||||
env_logger.workspace = true
|
||||
console = "0.16.0"
|
||||
indicatif = "0.18.0"
|
||||
lazy_static = "1.5.0"
|
||||
log.workspace = true
|
||||
indicatif-log-bridge = "0.2.3"
|
||||
|
||||
|
||||
[features]
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
use harmony::instrumentation::{self, HarmonyEvent};
|
||||
use indicatif::{MultiProgress, ProgressBar};
|
||||
use indicatif_log_bridge::LogWrapper;
|
||||
use std::{
|
||||
collections::{HashMap, hash_map},
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::progress;
|
||||
|
||||
pub fn init() -> tokio::task::JoinHandle<()> {
|
||||
configure_logger();
|
||||
let handle = tokio::spawn(handle_events());
|
||||
|
||||
loop {
|
||||
if instrumentation::instrument(HarmonyEvent::HarmonyStarted).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
handle
|
||||
}
|
||||
|
||||
fn configure_logger() {
|
||||
let logger =
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).build();
|
||||
let level = logger.filter();
|
||||
let multi = MultiProgress::new();
|
||||
LogWrapper::new(multi.clone(), logger).try_init().unwrap();
|
||||
log::set_max_level(level);
|
||||
}
|
||||
|
||||
async fn handle_events() {
|
||||
instrumentation::subscribe("Harmony CLI Logger", {
|
||||
let sections: Arc<Mutex<HashMap<String, MultiProgress>>> =
|
||||
Arc::new(Mutex::new(HashMap::new()));
|
||||
let progress_bars: Arc<Mutex<HashMap<String, ProgressBar>>> =
|
||||
Arc::new(Mutex::new(HashMap::new()));
|
||||
|
||||
move |event| {
|
||||
let sections_clone = Arc::clone(§ions);
|
||||
let progress_bars_clone = Arc::clone(&progress_bars);
|
||||
|
||||
async move {
|
||||
let mut sections = sections_clone.lock().unwrap();
|
||||
let mut progress_bars = progress_bars_clone.lock().unwrap();
|
||||
|
||||
match event {
|
||||
HarmonyEvent::HarmonyStarted => {}
|
||||
HarmonyEvent::PrepareTopologyStarted { topology: name } => {
|
||||
let section = progress::new_section(format!(
|
||||
"{} Preparing environment: {name}...",
|
||||
crate::theme::EMOJI_TOPOLOGY,
|
||||
));
|
||||
(*sections).insert(name, section);
|
||||
}
|
||||
HarmonyEvent::TopologyPrepared {
|
||||
topology: name,
|
||||
outcome,
|
||||
} => {
|
||||
let section = (*sections).get(&name).unwrap();
|
||||
let progress = progress::add_spinner(section, "".into());
|
||||
|
||||
match outcome.status {
|
||||
harmony::interpret::InterpretStatus::SUCCESS => {
|
||||
progress::success(section, Some(progress), outcome.message);
|
||||
}
|
||||
harmony::interpret::InterpretStatus::FAILURE => {
|
||||
progress::error(section, Some(progress), outcome.message);
|
||||
}
|
||||
harmony::interpret::InterpretStatus::RUNNING => todo!(),
|
||||
harmony::interpret::InterpretStatus::QUEUED => todo!(),
|
||||
harmony::interpret::InterpretStatus::BLOCKED => todo!(),
|
||||
harmony::interpret::InterpretStatus::NOOP => {
|
||||
progress::skip(section, Some(progress), outcome.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
HarmonyEvent::InterpretExecutionStarted {
|
||||
interpret: name,
|
||||
topology,
|
||||
message,
|
||||
} => {
|
||||
let section = (*sections).get(&topology).unwrap();
|
||||
let progress_bar = progress::add_spinner(section, message);
|
||||
|
||||
(*progress_bars).insert(name, progress_bar);
|
||||
}
|
||||
HarmonyEvent::InterpretExecutionFinished {
|
||||
topology,
|
||||
interpret: name,
|
||||
outcome,
|
||||
} => {
|
||||
let section = (*sections).get(&topology).unwrap();
|
||||
let progress_bar = (*progress_bars).get(&name).cloned();
|
||||
|
||||
let _ = section.clear();
|
||||
|
||||
match outcome {
|
||||
Ok(outcome) => {
|
||||
progress::success(section, progress_bar, outcome.message);
|
||||
}
|
||||
Err(err) => {
|
||||
progress::error(section, progress_bar, err.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
(*progress_bars).remove(&name);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -4,13 +4,8 @@ use harmony;
|
||||
use harmony::{score::Score, topology::Topology};
|
||||
use inquire::Confirm;
|
||||
|
||||
pub mod cli_logger; // FIXME: Don't make me pub
|
||||
pub mod progress;
|
||||
pub mod theme;
|
||||
|
||||
#[cfg(feature = "tui")]
|
||||
use harmony_tui;
|
||||
use log::debug;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about, long_about = None)]
|
||||
@@ -139,7 +134,7 @@ pub async fn init<T: Topology + Send + Sync + 'static>(
|
||||
|
||||
// Run filtered scores
|
||||
for s in scores_vec {
|
||||
debug!("Running: {}", s.name());
|
||||
println!("Running: {}", s.name());
|
||||
maestro.interpret(s).await?;
|
||||
}
|
||||
|
||||
@@ -158,7 +153,7 @@ mod test {
|
||||
fn init_test_maestro() -> Maestro<HAClusterTopology> {
|
||||
let inventory = Inventory::autoload();
|
||||
let topology = HAClusterTopology::autoload();
|
||||
let mut maestro = Maestro::new_without_initialization(inventory, topology);
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
|
||||
maestro.register_all(vec![
|
||||
Box::new(SuccessScore {}),
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use indicatif::{MultiProgress, ProgressBar};
|
||||
|
||||
pub fn new_section(title: String) -> MultiProgress {
|
||||
let multi_progress = MultiProgress::new();
|
||||
let _ = multi_progress.println(title);
|
||||
|
||||
multi_progress
|
||||
}
|
||||
|
||||
pub fn add_spinner(multi_progress: &MultiProgress, message: String) -> ProgressBar {
|
||||
let progress = multi_progress.add(ProgressBar::new_spinner());
|
||||
|
||||
progress.set_style(crate::theme::SPINNER_STYLE.clone());
|
||||
progress.set_message(message);
|
||||
progress.enable_steady_tick(Duration::from_millis(100));
|
||||
|
||||
progress
|
||||
}
|
||||
|
||||
pub fn success(multi_progress: &MultiProgress, progress: Option<ProgressBar>, message: String) {
|
||||
if let Some(progress) = progress {
|
||||
multi_progress.remove(&progress)
|
||||
}
|
||||
|
||||
let progress = multi_progress.add(ProgressBar::new_spinner());
|
||||
progress.set_style(crate::theme::SUCCESS_SPINNER_STYLE.clone());
|
||||
progress.finish_with_message(message);
|
||||
}
|
||||
|
||||
pub fn error(multi_progress: &MultiProgress, progress: Option<ProgressBar>, message: String) {
|
||||
if let Some(progress) = progress {
|
||||
multi_progress.remove(&progress)
|
||||
}
|
||||
|
||||
let progress = multi_progress.add(ProgressBar::new_spinner());
|
||||
progress.set_style(crate::theme::ERROR_SPINNER_STYLE.clone());
|
||||
progress.finish_with_message(message);
|
||||
}
|
||||
|
||||
pub fn skip(multi_progress: &MultiProgress, progress: Option<ProgressBar>, message: String) {
|
||||
if let Some(progress) = progress {
|
||||
multi_progress.remove(&progress)
|
||||
}
|
||||
|
||||
let progress = multi_progress.add(ProgressBar::new_spinner());
|
||||
progress.set_style(crate::theme::SKIP_SPINNER_STYLE.clone());
|
||||
progress.finish_with_message(message);
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
use console::Emoji;
|
||||
use indicatif::ProgressStyle;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
pub static EMOJI_HARMONY: Emoji<'_, '_> = Emoji("🎼", "");
|
||||
pub static EMOJI_SUCCESS: Emoji<'_, '_> = Emoji("✅", "");
|
||||
pub static EMOJI_SKIP: Emoji<'_, '_> = Emoji("⏭️", "");
|
||||
pub static EMOJI_ERROR: Emoji<'_, '_> = Emoji("⚠️", "");
|
||||
pub static EMOJI_DEPLOY: Emoji<'_, '_> = Emoji("🚀", "");
|
||||
pub static EMOJI_TOPOLOGY: Emoji<'_, '_> = Emoji("📦", "");
|
||||
|
||||
lazy_static! {
|
||||
pub static ref SPINNER_STYLE: ProgressStyle = ProgressStyle::default_spinner()
|
||||
.template(" {spinner:.green} {msg}")
|
||||
.unwrap()
|
||||
.tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]);
|
||||
pub static ref SUCCESS_SPINNER_STYLE: ProgressStyle = SPINNER_STYLE
|
||||
.clone()
|
||||
.tick_strings(&[format!("{}", EMOJI_SUCCESS).as_str()]);
|
||||
pub static ref SKIP_SPINNER_STYLE: ProgressStyle = SPINNER_STYLE
|
||||
.clone()
|
||||
.tick_strings(&[format!("{}", EMOJI_SKIP).as_str()]);
|
||||
pub static ref ERROR_SPINNER_STYLE: ProgressStyle = SPINNER_STYLE
|
||||
.clone()
|
||||
.tick_strings(&[format!("{}", EMOJI_ERROR).as_str()]);
|
||||
}
|
||||
@@ -15,9 +15,3 @@ current_platform = "0.2.0"
|
||||
futures-util = "0.3.31"
|
||||
serde_json = "1.0.140"
|
||||
cargo_metadata = "0.20.0"
|
||||
indicatif = "0.18.0"
|
||||
console = "0.16.0"
|
||||
lazy_static = "1.5.0"
|
||||
once_cell = "1.21.3"
|
||||
harmony_cli = { path = "../harmony_cli" }
|
||||
indicatif-log-bridge = "0.2.3"
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
use indicatif::{MultiProgress, ProgressBar};
|
||||
use indicatif_log_bridge::LogWrapper;
|
||||
use log::error;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crate::instrumentation::{self, HarmonyComposerEvent};
|
||||
|
||||
pub fn init() -> tokio::task::JoinHandle<()> {
|
||||
configure_logger();
|
||||
let handle = tokio::spawn(handle_events());
|
||||
|
||||
loop {
|
||||
if instrumentation::instrument(HarmonyComposerEvent::HarmonyComposerStarted).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
handle
|
||||
}
|
||||
|
||||
fn configure_logger() {
|
||||
let logger =
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).build();
|
||||
let level = logger.filter();
|
||||
let multi = MultiProgress::new();
|
||||
LogWrapper::new(multi.clone(), logger).try_init().unwrap();
|
||||
log::set_max_level(level);
|
||||
}
|
||||
|
||||
pub async fn handle_events() {
|
||||
const PROGRESS_SETUP: &str = "project-initialization";
|
||||
const PROGRESS_DEPLOYMENT: &str = "deployment";
|
||||
|
||||
instrumentation::subscribe("Harmony Composer Logger", {
|
||||
let progresses: Arc<Mutex<HashMap<String, MultiProgress>>> =
|
||||
Arc::new(Mutex::new(HashMap::new()));
|
||||
let compilation_progress = Arc::new(Mutex::new(None::<ProgressBar>));
|
||||
|
||||
move |event| {
|
||||
let progresses_clone = Arc::clone(&progresses);
|
||||
let compilation_progress_clone = Arc::clone(&compilation_progress);
|
||||
|
||||
async move {
|
||||
let mut progresses_guard = progresses_clone.lock().unwrap();
|
||||
let mut compilation_progress_guard = compilation_progress_clone.lock().unwrap();
|
||||
|
||||
match event {
|
||||
HarmonyComposerEvent::HarmonyComposerStarted => {}
|
||||
HarmonyComposerEvent::ProjectInitializationStarted => {
|
||||
let multi_progress = harmony_cli::progress::new_section(format!(
|
||||
"{} Initializing Harmony project...",
|
||||
harmony_cli::theme::EMOJI_HARMONY,
|
||||
));
|
||||
(*progresses_guard).insert(PROGRESS_SETUP.to_string(), multi_progress);
|
||||
}
|
||||
HarmonyComposerEvent::ProjectInitialized => println!("\n"),
|
||||
HarmonyComposerEvent::ProjectCompilationStarted { details } => {
|
||||
let initialization_progress =
|
||||
(*progresses_guard).get(PROGRESS_SETUP).unwrap();
|
||||
let _ = initialization_progress.clear();
|
||||
|
||||
let progress =
|
||||
harmony_cli::progress::add_spinner(initialization_progress, details);
|
||||
*compilation_progress_guard = Some(progress);
|
||||
}
|
||||
HarmonyComposerEvent::ProjectCompiled => {
|
||||
let initialization_progress =
|
||||
(*progresses_guard).get(PROGRESS_SETUP).unwrap();
|
||||
|
||||
harmony_cli::progress::success(
|
||||
initialization_progress,
|
||||
(*compilation_progress_guard).take(),
|
||||
"project compiled".to_string(),
|
||||
);
|
||||
}
|
||||
HarmonyComposerEvent::ProjectCompilationFailed { details } => {
|
||||
let initialization_progress =
|
||||
(*progresses_guard).get(PROGRESS_SETUP).unwrap();
|
||||
|
||||
harmony_cli::progress::error(
|
||||
initialization_progress,
|
||||
(*compilation_progress_guard).take(),
|
||||
"failed to compile project".to_string(),
|
||||
);
|
||||
|
||||
error!("{details}");
|
||||
}
|
||||
HarmonyComposerEvent::DeploymentStarted { target } => {
|
||||
let multi_progress = harmony_cli::progress::new_section(format!(
|
||||
"{} Starting deployment to {target}...\n\n",
|
||||
harmony_cli::theme::EMOJI_DEPLOY
|
||||
));
|
||||
(*progresses_guard).insert(PROGRESS_DEPLOYMENT.to_string(), multi_progress);
|
||||
}
|
||||
HarmonyComposerEvent::DeploymentCompleted { details } => println!("\n"),
|
||||
HarmonyComposerEvent::Shutdown => {
|
||||
for (_, progresses) in (*progresses_guard).iter() {
|
||||
progresses.clear().unwrap();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use log::debug;
|
||||
use once_cell::sync::Lazy;
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum HarmonyComposerEvent {
|
||||
HarmonyComposerStarted,
|
||||
ProjectInitializationStarted,
|
||||
ProjectInitialized,
|
||||
ProjectCompilationStarted { details: String },
|
||||
ProjectCompiled,
|
||||
ProjectCompilationFailed { details: String },
|
||||
DeploymentStarted { target: String },
|
||||
DeploymentCompleted { details: String },
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
static HARMONY_COMPOSER_EVENT_BUS: Lazy<broadcast::Sender<HarmonyComposerEvent>> =
|
||||
Lazy::new(|| {
|
||||
// TODO: Adjust channel capacity
|
||||
let (tx, _rx) = broadcast::channel(16);
|
||||
tx
|
||||
});
|
||||
|
||||
pub fn instrument(event: HarmonyComposerEvent) -> Result<(), &'static str> {
|
||||
match HARMONY_COMPOSER_EVENT_BUS.send(event) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("send error: no subscribers"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn subscribe<F, Fut>(name: &str, mut handler: F)
|
||||
where
|
||||
F: FnMut(HarmonyComposerEvent) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = bool> + Send,
|
||||
{
|
||||
let mut rx = HARMONY_COMPOSER_EVENT_BUS.subscribe();
|
||||
debug!("[{name}] Service started. Listening for events...");
|
||||
loop {
|
||||
match rx.recv().await {
|
||||
Ok(event) => {
|
||||
if !handler(event).await {
|
||||
debug!("[{name}] Handler requested exit.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(n)) => {
|
||||
debug!("[{name}] Lagged behind by {n} messages.");
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,16 +7,12 @@ use bollard::secret::HostConfig;
|
||||
use cargo_metadata::{Artifact, Message, MetadataCommand};
|
||||
use clap::{Args, Parser, Subcommand};
|
||||
use futures_util::StreamExt;
|
||||
use instrumentation::HarmonyComposerEvent;
|
||||
use log::{debug, info, log_enabled};
|
||||
use log::info;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use tokio::fs;
|
||||
|
||||
mod harmony_composer_logger;
|
||||
mod instrumentation;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about, long_about = None, flatten_help = true, propagate_version = true)]
|
||||
struct GlobalArgs {
|
||||
@@ -70,15 +66,13 @@ struct AllArgs {
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let hc_logger_handle = harmony_composer_logger::init();
|
||||
env_logger::init();
|
||||
let cli_args = GlobalArgs::parse();
|
||||
|
||||
let harmony_path = Path::new(&cli_args.harmony_path)
|
||||
.try_exists()
|
||||
.expect("couldn't check if path exists");
|
||||
|
||||
instrumentation::instrument(HarmonyComposerEvent::ProjectInitializationStarted).unwrap();
|
||||
|
||||
let harmony_bin_path: PathBuf = match harmony_path {
|
||||
true => {
|
||||
compile_harmony(
|
||||
@@ -91,8 +85,6 @@ async fn main() {
|
||||
false => todo!("implement autodetect code"),
|
||||
};
|
||||
|
||||
instrumentation::instrument(HarmonyComposerEvent::ProjectInitialized).unwrap();
|
||||
|
||||
match cli_args.command {
|
||||
Some(command) => match command {
|
||||
Commands::Check(args) => {
|
||||
@@ -106,9 +98,7 @@ async fn main() {
|
||||
.expect("couldn't check if path exists")
|
||||
{
|
||||
true => (),
|
||||
false => todo!(
|
||||
"path {check_script_str} not found. Other paths currently unsupported."
|
||||
),
|
||||
false => todo!("implement couldn't find path logic"),
|
||||
};
|
||||
|
||||
let check_output = Command::new(check_script)
|
||||
@@ -124,31 +114,19 @@ async fn main() {
|
||||
}
|
||||
Commands::Deploy(args) => {
|
||||
let deploy = if args.staging {
|
||||
instrumentation::instrument(HarmonyComposerEvent::DeploymentStarted {
|
||||
target: "staging".to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
todo!("implement staging deployment")
|
||||
} else if args.prod {
|
||||
instrumentation::instrument(HarmonyComposerEvent::DeploymentStarted {
|
||||
target: "prod".to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
todo!("implement prod deployment")
|
||||
} else {
|
||||
instrumentation::instrument(HarmonyComposerEvent::DeploymentStarted {
|
||||
target: "dev".to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
Command::new(harmony_bin_path).arg("-y").arg("-a").spawn()
|
||||
}
|
||||
.expect("failed to run harmony deploy");
|
||||
|
||||
let deploy_output = deploy.wait_with_output().unwrap();
|
||||
instrumentation::instrument(HarmonyComposerEvent::DeploymentCompleted {
|
||||
details: String::from_utf8(deploy_output.stdout).unwrap(),
|
||||
})
|
||||
.unwrap();
|
||||
println!(
|
||||
"deploy output: {}",
|
||||
String::from_utf8(deploy_output.stdout).expect("couldn't parse from utf8")
|
||||
);
|
||||
}
|
||||
Commands::All(_args) => todo!(
|
||||
"take all previous match arms and turn them into separate functions, and call them all one after the other"
|
||||
@@ -157,10 +135,6 @@ async fn main() {
|
||||
},
|
||||
None => todo!("run interactively, ask for info on CLI"),
|
||||
}
|
||||
|
||||
instrumentation::instrument(HarmonyComposerEvent::Shutdown).unwrap();
|
||||
|
||||
let _ = tokio::try_join!(hc_logger_handle);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, clap::ValueEnum)]
|
||||
@@ -181,7 +155,6 @@ async fn compile_harmony(
|
||||
|
||||
let cargo_exists = Command::new("which")
|
||||
.arg("cargo")
|
||||
.stdout(Stdio::null())
|
||||
.status()
|
||||
.expect("couldn't get `which cargo` status")
|
||||
.success();
|
||||
@@ -190,32 +163,17 @@ async fn compile_harmony(
|
||||
Some(m) => m,
|
||||
None => {
|
||||
if cargo_exists {
|
||||
CompileMethod::LocalCargo
|
||||
return compile_cargo(platform, harmony_location).await;
|
||||
} else {
|
||||
CompileMethod::Docker
|
||||
return compile_docker(platform, harmony_location).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let path = match method {
|
||||
CompileMethod::LocalCargo => {
|
||||
instrumentation::instrument(HarmonyComposerEvent::ProjectCompilationStarted {
|
||||
details: "compiling project with cargo".to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
compile_cargo(platform, harmony_location).await
|
||||
}
|
||||
CompileMethod::Docker => {
|
||||
instrumentation::instrument(HarmonyComposerEvent::ProjectCompilationStarted {
|
||||
details: "compiling project with docker".to_string(),
|
||||
})
|
||||
.unwrap();
|
||||
compile_docker(platform, harmony_location).await
|
||||
}
|
||||
match method {
|
||||
CompileMethod::LocalCargo => return compile_cargo(platform, harmony_location).await,
|
||||
CompileMethod::Docker => return compile_docker(platform, harmony_location).await,
|
||||
};
|
||||
|
||||
instrumentation::instrument(HarmonyComposerEvent::ProjectCompiled).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
// TODO: make sure this works with cargo workspaces
|
||||
@@ -225,12 +183,6 @@ async fn compile_cargo(platform: String, harmony_location: String) -> PathBuf {
|
||||
.exec()
|
||||
.unwrap();
|
||||
|
||||
let stderr = if log_enabled!(log::Level::Debug) {
|
||||
Stdio::inherit()
|
||||
} else {
|
||||
Stdio::piped()
|
||||
};
|
||||
|
||||
let mut cargo_build = Command::new("cargo")
|
||||
.current_dir(&harmony_location)
|
||||
.args(vec![
|
||||
@@ -240,7 +192,6 @@ async fn compile_cargo(platform: String, harmony_location: String) -> PathBuf {
|
||||
"--message-format=json-render-diagnostics",
|
||||
])
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(stderr)
|
||||
.spawn()
|
||||
.expect("run cargo command failed");
|
||||
|
||||
@@ -256,20 +207,18 @@ async fn compile_cargo(platform: String, harmony_location: String) -> PathBuf {
|
||||
.expect("failed to get root package")
|
||||
.manifest_path
|
||||
{
|
||||
debug!("{:?}", artifact);
|
||||
println!("{:?}", artifact);
|
||||
artifacts.push(artifact);
|
||||
}
|
||||
}
|
||||
Message::BuildScriptExecuted(_script) => (),
|
||||
Message::BuildFinished(finished) => {
|
||||
debug!("{:?}", finished);
|
||||
println!("{:?}", finished);
|
||||
}
|
||||
_ => (), // Unknown message
|
||||
}
|
||||
}
|
||||
|
||||
cargo_build.wait().expect("run cargo command failed");
|
||||
|
||||
let bin = artifacts
|
||||
.last()
|
||||
.expect("no binaries built")
|
||||
@@ -285,8 +234,7 @@ async fn compile_cargo(platform: String, harmony_location: String) -> PathBuf {
|
||||
bin_out = PathBuf::from(format!("{}/harmony", harmony_location));
|
||||
let _copy_res = fs::copy(&bin, &bin_out).await;
|
||||
}
|
||||
|
||||
bin_out
|
||||
return bin_out;
|
||||
}
|
||||
|
||||
async fn compile_docker(platform: String, harmony_location: String) -> PathBuf {
|
||||
|
||||
@@ -41,7 +41,7 @@ pub mod tui {
|
||||
/// async fn main() {
|
||||
/// let inventory = Inventory::autoload();
|
||||
/// let topology = HAClusterTopology::autoload();
|
||||
/// let mut maestro = Maestro::new_without_initialization(inventory, topology);
|
||||
/// let mut maestro = Maestro::new(inventory, topology);
|
||||
///
|
||||
/// maestro.register_all(vec![
|
||||
/// Box::new(SuccessScore {}),
|
||||
|
||||
@@ -2,7 +2,7 @@ mod downloadable_asset;
|
||||
use downloadable_asset::*;
|
||||
|
||||
use kube::Client;
|
||||
use log::{debug, warn};
|
||||
use log::{debug, info, warn};
|
||||
use std::path::PathBuf;
|
||||
|
||||
const K3D_BIN_FILE_NAME: &str = "k3d";
|
||||
@@ -90,7 +90,7 @@ impl K3d {
|
||||
let latest_release = self.get_latest_release_tag().await.unwrap();
|
||||
|
||||
let release_binary = self.get_binary_for_current_platform(latest_release).await;
|
||||
debug!("Foudn K3d binary to install : {release_binary:#?}");
|
||||
info!("Foudn K3d binary to install : {release_binary:#?}");
|
||||
release_binary.download_to_path(self.base_dir.clone()).await
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ impl K3d {
|
||||
Err(_) => return Err("Could not get cluster_name, cannot initialize".to_string()),
|
||||
};
|
||||
|
||||
debug!("Initializing k3d cluster '{}'", cluster_name);
|
||||
info!("Initializing k3d cluster '{}'", cluster_name);
|
||||
|
||||
self.create_cluster(cluster_name)?;
|
||||
self.create_kubernetes_client().await
|
||||
@@ -205,7 +205,7 @@ impl K3d {
|
||||
/// - `Err(String)` - Error message if any step failed
|
||||
pub async fn ensure_installed(&self) -> Result<Client, String> {
|
||||
if !self.is_installed() {
|
||||
debug!("K3d is not installed, downloading latest release");
|
||||
info!("K3d is not installed, downloading latest release");
|
||||
self.download_latest_release()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to download k3d: {}", e))?;
|
||||
@@ -216,13 +216,13 @@ impl K3d {
|
||||
}
|
||||
|
||||
if !self.is_cluster_initialized() {
|
||||
debug!("Cluster is not initialized, initializing now");
|
||||
info!("Cluster is not initialized, initializing now");
|
||||
return self.initialize_cluster().await;
|
||||
}
|
||||
|
||||
self.start_cluster().await?;
|
||||
|
||||
debug!("K3d and cluster are already properly set up");
|
||||
info!("K3d and cluster are already properly set up");
|
||||
self.create_kubernetes_client().await
|
||||
}
|
||||
|
||||
@@ -325,12 +325,12 @@ impl K3d {
|
||||
return Err(format!("Failed to create cluster: {}", stderr));
|
||||
}
|
||||
|
||||
debug!("Successfully created k3d cluster '{}'", cluster_name);
|
||||
info!("Successfully created k3d cluster '{}'", cluster_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_kubernetes_client(&self) -> Result<Client, String> {
|
||||
// TODO: Connect the client to the right k3d cluster (see https://git.nationtech.io/NationTech/harmony/issues/92)
|
||||
warn!("TODO this method is way too dumb, it should make sure that the client is connected to the k3d cluster actually represented by this instance, not just any default client");
|
||||
Client::try_default()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to create Kubernetes client: {}", e))
|
||||
@@ -352,7 +352,7 @@ impl K3d {
|
||||
return Err(format!("Failed to start cluster: {}", stderr));
|
||||
}
|
||||
|
||||
debug!("Successfully started k3d cluster '{}'", cluster_name);
|
||||
info!("Successfully started k3d cluster '{}'", cluster_name);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,4 +22,4 @@ tokio-util = { version = "0.7.13", features = [ "codec" ] }
|
||||
tokio-stream = "0.1.17"
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions.workspace = true
|
||||
pretty_assertions = "1.4.1"
|
||||
|
||||
Reference in New Issue
Block a user