Compare commits
62 Commits
feat/zitad
...
feat/rustf
| Author | SHA1 | Date | |
|---|---|---|---|
| 3cf4fe4855 | |||
| ccc26e07eb | |||
| 9a67bcc96f | |||
| a377fc1404 | |||
| c9977fee12 | |||
| 64bf585e07 | |||
| 44e2c45435 | |||
| cdccbc8939 | |||
| 9830971d05 | |||
| e1183ef6de | |||
| 444fea81b8 | |||
| 907ae04195 | |||
| 64582caa64 | |||
| f5736fcc37 | |||
| 7a1e84fb68 | |||
| 8499f4d1b7 | |||
| 231d9b878e | |||
| ee2dade0be | |||
| aa07f4c8ad | |||
| 77bb138497 | |||
| a16879b1b6 | |||
| f57e6f5957 | |||
| 7605d05de3 | |||
| b244127843 | |||
| 67c3265286 | |||
| d10598d01e | |||
| 61ba7257d0 | |||
| b0e9594d92 | |||
| 2a7fa466cc | |||
| f463cd1e94 | |||
| e1da7949ec | |||
| d0a1a73710 | |||
| bc2b328296 | |||
| a93896707f | |||
| 0e9b23a320 | |||
| f532ba2b40 | |||
| fafca31798 | |||
| 5412c34957 | |||
| 787cc8feab | |||
| ce041f495b | |||
| bfb86f63ce | |||
| 55de206523 | |||
| 64893a84f5 | |||
| f941672662 | |||
| a98113dd40 | |||
| 5db1a31d33 | |||
| f5aac67af8 | |||
| d7e5bf11d5 | |||
| 2e1f1b8447 | |||
| 2b157ad7fd | |||
| d920de34cf | |||
| 4276b9137b | |||
| 6ab88ab8d9 | |||
| 53d0704a35 | |||
| de49e9ebcc | |||
| d8ab9d52a4 | |||
| 2cb7aeefc0 | |||
| 16016febcf | |||
| e709de531d | |||
| 6ab0f3a6ab | |||
| 724ab0b888 | |||
| 8b6ce8d069 |
@@ -15,4 +15,4 @@ jobs:
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run check script
|
||||
run: bash check.sh
|
||||
run: bash build/check.sh
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -29,3 +29,6 @@ Cargo.lock
|
||||
|
||||
# Useful to create ignore folders for temp files and notes
|
||||
ignore
|
||||
|
||||
# Generated book
|
||||
book
|
||||
|
||||
2978
Cargo.lock
generated
2978
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
15
Cargo.toml
15
Cargo.toml
@@ -1,8 +1,8 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"private_repos/*",
|
||||
"examples/*",
|
||||
"private_repos/*",
|
||||
"harmony",
|
||||
"harmony_types",
|
||||
"harmony_macros",
|
||||
@@ -16,10 +16,14 @@ members = [
|
||||
"harmony_inventory_agent",
|
||||
"harmony_secret_derive",
|
||||
"harmony_secret",
|
||||
"adr/agent_discovery/mdns",
|
||||
"harmony_config_derive",
|
||||
"harmony_config",
|
||||
"brocade",
|
||||
"harmony_agent",
|
||||
"harmony_agent/deploy", "harmony_node_readiness",
|
||||
"harmony_agent/deploy",
|
||||
"harmony_node_readiness",
|
||||
"harmony-k8s",
|
||||
"harmony_assets",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
@@ -34,10 +38,13 @@ derive-new = "0.7"
|
||||
async-trait = "0.1"
|
||||
tokio = { version = "1.40", features = [
|
||||
"io-std",
|
||||
"io-util",
|
||||
"fs",
|
||||
"macros",
|
||||
"rt-multi-thread",
|
||||
] }
|
||||
tokio-retry = "0.3.0"
|
||||
tokio-util = "0.7.15"
|
||||
cidr = { features = ["serde"], version = "0.2" }
|
||||
russh = "0.45"
|
||||
russh-keys = "0.45"
|
||||
@@ -68,6 +75,7 @@ base64 = "0.22.1"
|
||||
tar = "0.4.44"
|
||||
lazy_static = "1.5.0"
|
||||
directories = "6.0.0"
|
||||
futures-util = "0.3"
|
||||
thiserror = "2.0.14"
|
||||
serde = { version = "1.0.209", features = ["derive", "rc"] }
|
||||
serde_json = "1.0.127"
|
||||
@@ -81,3 +89,4 @@ reqwest = { version = "0.12", features = [
|
||||
"json",
|
||||
], default-features = false }
|
||||
assertor = "0.0.4"
|
||||
tokio-test = "0.4"
|
||||
|
||||
272
README.md
272
README.md
@@ -1,101 +1,121 @@
|
||||
# Harmony
|
||||
|
||||
Open-source infrastructure orchestration that treats your platform like first-class code.
|
||||
**Infrastructure orchestration that treats your platform like first-class code.**
|
||||
|
||||
In other words, Harmony is a **next-generation platform engineering framework**.
|
||||
Harmony is an open-source framework that brings the rigor of software engineering to infrastructure management. Write Rust code to define what you want, and Harmony handles the rest — from local development to production clusters.
|
||||
|
||||
_By [NationTech](https://nationtech.io)_
|
||||
|
||||
[](https://git.nationtech.io/nationtech/harmony)
|
||||
[](https://git.nationtech.io/NationTech/harmony)
|
||||
[](LICENSE)
|
||||
|
||||
### Unify
|
||||
---
|
||||
|
||||
- **Project Scaffolding**
|
||||
- **Infrastructure Provisioning**
|
||||
- **Application Deployment**
|
||||
- **Day-2 operations**
|
||||
## The Problem Harmony Solves
|
||||
|
||||
All in **one strongly-typed Rust codebase**.
|
||||
Modern infrastructure is messy. Your Kubernetes cluster needs monitoring. Your bare-metal servers need provisioning. Your applications need deployments. Each comes with its own tooling, its own configuration format, and its own failure modes.
|
||||
|
||||
### Deploy anywhere
|
||||
**What if you could describe your entire platform in one consistent language?**
|
||||
|
||||
From a **developer laptop** to a **global production cluster**, a single **source of truth** drives the **full software lifecycle.**
|
||||
That's Harmony. It unifies project scaffolding, infrastructure provisioning, application deployment, and day-2 operations into a single strongly-typed Rust codebase.
|
||||
|
||||
## The Harmony Philosophy
|
||||
---
|
||||
|
||||
Infrastructure is essential, but it shouldn’t be your core business. Harmony is built on three guiding principles that make modern platforms reliable, repeatable, and easy to reason about.
|
||||
## Three Principles That Make the Difference
|
||||
|
||||
| Principle | What it means for you |
|
||||
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Infrastructure as Resilient Code** | Replace sprawling YAML and bash scripts with type-safe Rust. Test, refactor, and version your platform just like application code. |
|
||||
| **Prove It Works — Before You Deploy** | Harmony uses the compiler to verify that your application’s needs match the target environment’s capabilities at **compile-time**, eliminating an entire class of runtime outages. |
|
||||
| **One Unified Model** | Software and infrastructure are a single system. Harmony models them together, enabling deep automation—from bare-metal servers to Kubernetes workloads—with zero context switching. |
|
||||
| Principle | What It Means |
|
||||
|-----------|---------------|
|
||||
| **Infrastructure as Resilient Code** | Stop fighting with YAML and bash. Write type-safe Rust that you can test, version, and refactor like any other code. |
|
||||
| **Prove It Works Before You Deploy** | Harmony verifies at _compile time_ that your application can actually run on your target infrastructure. No more "the config looks right but it doesn't work" surprises. |
|
||||
| **One Unified Model** | Software and infrastructure are one system. Deploy from laptop to production cluster without switching contexts or tools. |
|
||||
|
||||
These principles surface as simple, ergonomic Rust APIs that let teams focus on their product while trusting the platform underneath.
|
||||
---
|
||||
|
||||
## Where to Start
|
||||
## How It Works: The Core Concepts
|
||||
|
||||
We have a comprehensive set of documentation right here in the repository.
|
||||
Harmony is built around three concepts that work together:
|
||||
|
||||
| I want to... | Start Here |
|
||||
| ----------------- | ------------------------------------------------------------------ |
|
||||
| Get Started | [Getting Started Guide](./docs/guides/getting-started.md) |
|
||||
| See an Example | [Use Case: Deploy a Rust Web App](./docs/use-cases/rust-webapp.md) |
|
||||
| Explore | [Documentation Hub](./docs/README.md) |
|
||||
| See Core Concepts | [Core Concepts Explained](./docs/concepts.md) |
|
||||
### Score — "What You Want"
|
||||
|
||||
## Quick Look: Deploy a Rust Webapp
|
||||
A `Score` is a declarative description of desired state. Think of it as a "recipe" that says _what_ you want without specifying _how_ to get there.
|
||||
|
||||
The snippet below spins up a complete **production-grade Rust + Leptos Webapp** with monitoring. Swap it for your own scores to deploy anything from microservices to machine-learning pipelines.
|
||||
```rust
|
||||
// "I want a PostgreSQL cluster running with default settings"
|
||||
let postgres = PostgreSQLScore {
|
||||
config: PostgreSQLConfig {
|
||||
cluster_name: "harmony-postgres-example".to_string(),
|
||||
namespace: "harmony-postgres-example".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Topology — "Where It Goes"
|
||||
|
||||
A `Topology` represents your infrastructure environment and its capabilities. It answers the question: "What can this environment actually do?"
|
||||
|
||||
```rust
|
||||
// Deploy to a local K3D cluster, or any Kubernetes cluster via environment variables
|
||||
K8sAnywhereTopology::from_env()
|
||||
```
|
||||
|
||||
### Interpret — "How It Happens"
|
||||
|
||||
An `Interpret` is the execution logic that connects your `Score` to your `Topology`. It translates "what you want" into "what the infrastructure does."
|
||||
|
||||
**The Compile-Time Check:** Before your code ever runs, Harmony verifies that your `Score` is compatible with your `Topology`. If your application needs a feature your infrastructure doesn't provide, you get a compile error — not a runtime failure.
|
||||
|
||||
---
|
||||
|
||||
## What You Can Deploy
|
||||
|
||||
Harmony ships with ready-made Scores for:
|
||||
|
||||
**Data Services**
|
||||
- PostgreSQL clusters (via CloudNativePG operator)
|
||||
- Multi-site PostgreSQL with failover
|
||||
|
||||
**Kubernetes**
|
||||
- Namespaces, Deployments, Ingress
|
||||
- Helm charts
|
||||
- cert-manager for TLS
|
||||
- Monitoring (Prometheus, alerting, ntfy)
|
||||
|
||||
**Bare Metal / Infrastructure**
|
||||
- OKD clusters from scratch
|
||||
- OPNsense firewalls
|
||||
- Network services (DNS, DHCP, TFTP)
|
||||
- Brocade switch configuration
|
||||
|
||||
**And more:** Application deployment, tenant management, load balancing, and more.
|
||||
|
||||
---
|
||||
|
||||
## Quick Start: Deploy a PostgreSQL Cluster
|
||||
|
||||
This example provisions a local Kubernetes cluster (K3D) and deploys a PostgreSQL cluster on it — no external infrastructure required.
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::{
|
||||
application::{
|
||||
ApplicationScore, RustWebFramework, RustWebapp,
|
||||
features::{PackagingDeployment, rhob_monitoring::Monitoring},
|
||||
},
|
||||
monitoring::alert_channel::discord_alert_channel::DiscordWebhook,
|
||||
},
|
||||
modules::postgresql::{PostgreSQLScore, capability::PostgreSQLConfig},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
use harmony_macros::hurl;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let application = Arc::new(RustWebapp {
|
||||
name: "harmony-example-leptos".to_string(),
|
||||
project_root: PathBuf::from(".."), // <== Your project root, usually .. if you use the standard `/harmony` folder
|
||||
framework: Some(RustWebFramework::Leptos),
|
||||
service_port: 8080,
|
||||
});
|
||||
|
||||
// Define your Application deployment and the features you want
|
||||
let app = ApplicationScore {
|
||||
features: vec![
|
||||
Box::new(PackagingDeployment {
|
||||
application: application.clone(),
|
||||
}),
|
||||
Box::new(Monitoring {
|
||||
application: application.clone(),
|
||||
alert_receiver: vec![
|
||||
Box::new(DiscordWebhook {
|
||||
name: "test-discord".to_string(),
|
||||
url: hurl!("https://discord.doesnt.exist.com"), // <== Get your discord webhook url
|
||||
}),
|
||||
],
|
||||
}),
|
||||
],
|
||||
application,
|
||||
let postgres = PostgreSQLScore {
|
||||
config: PostgreSQLConfig {
|
||||
cluster_name: "harmony-postgres-example".to_string(),
|
||||
namespace: "harmony-postgres-example".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(), // <== Deploy to local automatically provisioned local k3d by default or connect to any kubernetes cluster
|
||||
vec![Box::new(app)],
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(postgres)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -103,40 +123,128 @@ async fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
To run this:
|
||||
### What this actually does
|
||||
|
||||
- Clone the repository: `git clone https://git.nationtech.io/nationtech/harmony`
|
||||
- Install dependencies: `cargo build --release`
|
||||
- Run the example: `cargo run --example try_rust_webapp`
|
||||
When you compile and run this program:
|
||||
|
||||
1. **Compiles** the Harmony Score into an executable
|
||||
2. **Connects** to `K8sAnywhereTopology` — which auto-provisions a local K3D cluster if none exists
|
||||
3. **Installs** the CloudNativePG operator into the cluster (one-time setup)
|
||||
4. **Creates** a PostgreSQL cluster with 1 instance and 1 GiB of storage
|
||||
5. **Exposes** the PostgreSQL instance as a Kubernetes Service
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- [Rust](https://rust-lang.org/tools/install) (edition 2024)
|
||||
- [Docker](https://docs.docker.com/get-docker/) (for the local K3D cluster)
|
||||
- [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) (optional, for inspecting the cluster)
|
||||
|
||||
### Run it
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://git.nationtech.io/nationtech/harmony
|
||||
cd harmony
|
||||
|
||||
# Build the project
|
||||
cargo build --release
|
||||
|
||||
# Run the example
|
||||
cargo run -p example-postgresql
|
||||
```
|
||||
|
||||
Harmony will print its progress as it sets up the cluster and deploys PostgreSQL. When complete, you can inspect the deployment:
|
||||
|
||||
```bash
|
||||
kubectl get pods -n harmony-postgres-example
|
||||
kubectl get secret -n harmony-postgres-example harmony-postgres-example-db-user -o jsonpath='{.data.password}' | base64 -d
|
||||
```
|
||||
|
||||
To connect to the database, forward the port:
|
||||
```bash
|
||||
kubectl port-forward -n harmony-postgres-example svc/harmony-postgres-example-rw 5432:5432
|
||||
psql -h localhost -p 5432 -U postgres
|
||||
```
|
||||
|
||||
To clean up, delete the K3D cluster:
|
||||
```bash
|
||||
k3d cluster delete harmony-postgres-example
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
`K8sAnywhereTopology::from_env()` reads the following environment variables to determine where and how to connect:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `KUBECONFIG` | `~/.kube/config` | Path to your kubeconfig file |
|
||||
| `HARMONY_AUTOINSTALL` | `true` | Auto-provision a local K3D cluster if none found |
|
||||
| `HARMONY_USE_LOCAL_K3D` | `true` | Always prefer local K3D over remote clusters |
|
||||
| `HARMONY_PROFILE` | `dev` | Deployment profile: `dev`, `staging`, or `prod` |
|
||||
| `HARMONY_K8S_CONTEXT` | _none_ | Use a specific kubeconfig context |
|
||||
| `HARMONY_PUBLIC_DOMAIN` | _none_ | Public domain for ingress endpoints |
|
||||
|
||||
To connect to an existing Kubernetes cluster instead of provisioning K3D:
|
||||
|
||||
```bash
|
||||
# Point to your kubeconfig
|
||||
export KUBECONFIG=/path/to/your/kubeconfig
|
||||
export HARMONY_USE_LOCAL_K3D=false
|
||||
export HARMONY_AUTOINSTALL=false
|
||||
|
||||
# Then run
|
||||
cargo run -p example-postgresql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
All documentation is in the `/docs` directory.
|
||||
| I want to... | Start here |
|
||||
|--------------|------------|
|
||||
| Understand the core concepts | [Core Concepts](./docs/concepts.md) |
|
||||
| Deploy my first application | [Getting Started Guide](./docs/guides/getting-started.md) |
|
||||
| Explore available components | [Scores Catalog](./docs/catalogs/scores.md) · [Topologies Catalog](./docs/catalogs/topologies.md) |
|
||||
| See a complete bare-metal deployment | [OKD on Bare Metal](./docs/use-cases/okd-on-bare-metal.md) |
|
||||
| Build my own Score or Topology | [Developer Guide](./docs/guides/developer-guide.md) |
|
||||
|
||||
- [Documentation Hub](./docs/README.md): The main entry point for all documentation.
|
||||
- [Core Concepts](./docs/concepts.md): A detailed look at Score, Topology, Capability, Inventory, and Interpret.
|
||||
- [Component Catalogs](./docs/catalogs/README.md): Discover all available Scores, Topologies, and Capabilities.
|
||||
- [Developer Guide](./docs/guides/developer-guide.md): Learn how to write your own Scores and Topologies.
|
||||
---
|
||||
|
||||
## Architectural Decision Records
|
||||
## Why Rust?
|
||||
|
||||
- [ADR-001 · Why Rust](adr/001-rust.md)
|
||||
- [ADR-003 · Infrastructure Abstractions](adr/003-infrastructure-abstractions.md)
|
||||
- [ADR-006 · Secret Management](adr/006-secret-management.md)
|
||||
- [ADR-011 · Multi-Tenant Cluster](adr/011-multi-tenant-cluster.md)
|
||||
We chose Rust for the same reason you might: **reliability through type safety**.
|
||||
|
||||
## Contribute
|
||||
Infrastructure code runs in production. It needs to be correct. Rust's ownership model and type system let us build a framework where:
|
||||
|
||||
Discussions and roadmap live in [Issues](https://git.nationtech.io/nationtech/harmony/-/issues). PRs, ideas, and feedback are welcome!
|
||||
- Invalid configurations fail at compile time, not at 3 AM
|
||||
- Refactoring infrastructure is as safe as refactoring application code
|
||||
- The compiler verifies that your platform can actually fulfill your requirements
|
||||
|
||||
See [ADR-001 · Why Rust](./adr/001-rust.md) for our full rationale.
|
||||
|
||||
---
|
||||
|
||||
## Architecture Decisions
|
||||
|
||||
Harmony's design is documented through Architecture Decision Records (ADRs):
|
||||
|
||||
- [ADR-001 · Why Rust](./adr/001-rust.md)
|
||||
- [ADR-003 · Infrastructure Abstractions](./adr/003-infrastructure-abstractions.md)
|
||||
- [ADR-006 · Secret Management](./adr/006-secret-management.md)
|
||||
- [ADR-011 · Multi-Tenant Cluster](./adr/011-multi-tenant-cluster.md)
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Harmony is released under the **GNU AGPL v3**.
|
||||
|
||||
> We choose a strong copyleft license to ensure the project—and every improvement to it—remains open and benefits the entire community. Fork it, enhance it, even out-innovate us; just keep it open.
|
||||
> We choose a strong copyleft license to ensure the project—and every improvement to it—remains open and benefits the entire community.
|
||||
|
||||
See [LICENSE](LICENSE) for the full text.
|
||||
|
||||
---
|
||||
|
||||
_Made with ❤️ & 🦀 by the NationTech and the Harmony community_
|
||||
_Made with ❤️ & 🦀 by NationTech and the Harmony community_
|
||||
|
||||
9
book.toml
Normal file
9
book.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[book]
|
||||
title = "Harmony"
|
||||
description = "Infrastructure orchestration that treats your platform like first-class code"
|
||||
src = "docs"
|
||||
build-dir = "book"
|
||||
authors = ["NationTech"]
|
||||
|
||||
[output.html]
|
||||
mathjax-support = false
|
||||
@@ -1,8 +1,7 @@
|
||||
use super::BrocadeClient;
|
||||
use crate::{
|
||||
BrocadeInfo, Error, ExecutionMode, InterSwitchLink, InterfaceInfo, MacAddressEntry,
|
||||
PortChannelId, PortOperatingMode, SecurityLevel, parse_brocade_mac_address,
|
||||
shell::BrocadeShell,
|
||||
PortChannelId, PortOperatingMode, parse_brocade_mac_address, shell::BrocadeShell,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -8,7 +8,7 @@ use regex::Regex;
|
||||
use crate::{
|
||||
BrocadeClient, BrocadeInfo, Error, ExecutionMode, InterSwitchLink, InterfaceInfo,
|
||||
InterfaceStatus, InterfaceType, MacAddressEntry, PortChannelId, PortOperatingMode,
|
||||
SecurityLevel, parse_brocade_mac_address, shell::BrocadeShell,
|
||||
parse_brocade_mac_address, shell::BrocadeShell,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
11
build/book.sh
Executable file
11
build/book.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
cargo install mdbook --locked
|
||||
mdbook build
|
||||
|
||||
test -f book/index.html || (echo "ERROR: book/index.html not found" && exit 1)
|
||||
test -f book/concepts.html || (echo "ERROR: book/concepts.html not found" && exit 1)
|
||||
test -f book/guides/getting-started.html || (echo "ERROR: book/guides/getting-started.html not found" && exit 1)
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
rustc --version
|
||||
cargo check --all-targets --all-features --keep-going
|
||||
cargo fmt --check
|
||||
16
build/ci.sh
Executable file
16
build/ci.sh
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
BRANCH="${1:-main}"
|
||||
|
||||
echo "=== Running CI for branch: $BRANCH ==="
|
||||
|
||||
echo "--- Checking code ---"
|
||||
./build/check.sh
|
||||
|
||||
echo "--- Building book ---"
|
||||
./build/book.sh
|
||||
|
||||
echo "=== CI passed ==="
|
||||
@@ -13,8 +13,9 @@ If you're new to Harmony, start here:
|
||||
|
||||
See how to use Harmony to solve real-world problems.
|
||||
|
||||
- [**PostgreSQL on Local K3D**](./use-cases/postgresql-on-local-k3d.md): Deploy a production-grade PostgreSQL cluster on a local K3D cluster. The fastest way to get started.
|
||||
- [**RustFS on Local K3D**](./use-cases/rustfs-on-local-k3d.md): Deploy a RustFS S3-compatible object store on a local K3D cluster.
|
||||
- [**OKD on Bare Metal**](./use-cases/okd-on-bare-metal.md): A detailed walkthrough of bootstrapping a high-availability OKD cluster from physical hardware.
|
||||
- [**Deploy a Rust Web App**](./use-cases/deploy-rust-webapp.md): A quick guide to deploying a monitored, containerized web application to a Kubernetes cluster.
|
||||
|
||||
## 3. Component Catalogs
|
||||
|
||||
@@ -31,3 +32,7 @@ Ready to build your own components? These guides show you how.
|
||||
- [**Writing a Score**](./guides/writing-a-score.md): Learn how to create your own `Score` and `Interpret` logic to define a new desired state.
|
||||
- [**Writing a Topology**](./guides/writing-a-topology.md): Learn how to model a new environment (like AWS, GCP, or custom hardware) as a `Topology`.
|
||||
- [**Adding Capabilities**](./guides/adding-capabilities.md): See how to add a `Capability` to your custom `Topology`.
|
||||
|
||||
## 5. Architecture Decision Records
|
||||
|
||||
Harmony's design is documented through Architecture Decision Records (ADRs). See the [ADR Overview](./adr/README.md) for a complete index of all decisions.
|
||||
|
||||
53
docs/SUMMARY.md
Normal file
53
docs/SUMMARY.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Summary
|
||||
|
||||
[Harmony Documentation](./README.md)
|
||||
|
||||
- [Core Concepts](./concepts.md)
|
||||
- [Getting Started Guide](./guides/getting-started.md)
|
||||
|
||||
## Use Cases
|
||||
|
||||
- [PostgreSQL on Local K3D](./use-cases/postgresql-on-local-k3d.md)
|
||||
- [OKD on Bare Metal](./use-cases/okd-on-bare-metal.md)
|
||||
|
||||
## Component Catalogs
|
||||
|
||||
- [Scores Catalog](./catalogs/scores.md)
|
||||
- [Topologies Catalog](./catalogs/topologies.md)
|
||||
- [Capabilities Catalog](./catalogs/capabilities.md)
|
||||
|
||||
## Developer Guides
|
||||
|
||||
- [Developer Guide](./guides/developer-guide.md)
|
||||
- [Writing a Score](./guides/writing-a-score.md)
|
||||
- [Writing a Topology](./guides/writing-a-topology.md)
|
||||
- [Adding Capabilities](./guides/adding-capabilities.md)
|
||||
|
||||
## Configuration
|
||||
|
||||
- [Configuration](./concepts/configuration.md)
|
||||
|
||||
## Architecture Decision Records
|
||||
|
||||
- [ADR Overview](./adr/README.md)
|
||||
- [000 · ADR Template](./adr/000-ADR-Template.md)
|
||||
- [001 · Why Rust](./adr/001-rust.md)
|
||||
- [002 · Hexagonal Architecture](./adr/002-hexagonal-architecture.md)
|
||||
- [003 · Infrastructure Abstractions](./adr/003-infrastructure-abstractions.md)
|
||||
- [004 · iPXE](./adr/004-ipxe.md)
|
||||
- [005 · Interactive Project](./adr/005-interactive-project.md)
|
||||
- [006 · Secret Management](./adr/006-secret-management.md)
|
||||
- [007 · Default Runtime](./adr/007-default-runtime.md)
|
||||
- [008 · Score Display Formatting](./adr/008-score-display-formatting.md)
|
||||
- [009 · Helm and Kustomize Handling](./adr/009-helm-and-kustomize-handling.md)
|
||||
- [010 · Monitoring and Alerting](./adr/010-monitoring-and-alerting.md)
|
||||
- [011 · Multi-Tenant Cluster](./adr/011-multi-tenant-cluster.md)
|
||||
- [012 · Project Delivery Automation](./adr/012-project-delivery-automation.md)
|
||||
- [013 · Monitoring Notifications](./adr/013-monitoring-notifications.md)
|
||||
- [015 · Higher Order Topologies](./adr/015-higher-order-topologies.md)
|
||||
- [016 · Harmony Agent and Global Mesh](./adr/016-Harmony-Agent-And-Global-Mesh-For-Decentralized-Workload-Management.md)
|
||||
- [017-1 · NATS Clusters Interconnection](./adr/017-1-Nats-Clusters-Interconnection-Topology.md)
|
||||
- [018 · Template Hydration for Workload Deployment](./adr/018-Template-Hydration-For-Workload-Deployment.md)
|
||||
- [019 · Network Bond Setup](./adr/019-Network-bond-setup.md)
|
||||
- [020 · Interactive Configuration Crate](./adr/020-interactive-configuration-crate.md)
|
||||
- [020-1 · Zitadel + OpenBao Secure Config Store](./adr/020-1-zitadel-openbao-secure-config-store.md)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
Rejected : See ADR 020 ./020-interactive-configuration-crate.md
|
||||
|
||||
### TODO [#3](https://git.nationtech.io/NationTech/harmony/issues/3):
|
||||
|
||||
233
docs/adr/020-1-zitadel-openbao-secure-config-store.md
Normal file
233
docs/adr/020-1-zitadel-openbao-secure-config-store.md
Normal file
@@ -0,0 +1,233 @@
|
||||
# ADR 020-1: Zitadel OIDC and OpenBao Integration for the Config Store
|
||||
|
||||
Author: Jean-Gabriel Gill-Couture
|
||||
|
||||
Date: 2026-03-18
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
ADR 020 defines a unified `harmony_config` crate with a `ConfigStore` trait. The default team-oriented backend is OpenBao, which provides encrypted storage, versioned KV, audit logging, and fine-grained access control.
|
||||
|
||||
OpenBao requires authentication. The question is how developers authenticate without introducing new credentials to manage.
|
||||
|
||||
The goals are:
|
||||
|
||||
- **Zero new credentials.** Developers log in with their existing corporate identity (Google Workspace, GitHub, or Microsoft Entra ID / Azure AD).
|
||||
- **Headless compatibility.** The flow must work over SSH, inside containers, and in CI — environments with no browser or localhost listener.
|
||||
- **Minimal friction.** After a one-time login, authentication should be invisible for weeks of active use.
|
||||
- **Centralized offboarding.** Revoking a user in the identity provider must immediately revoke their access to the config store.
|
||||
|
||||
## Decision
|
||||
|
||||
Developers authenticate to OpenBao through a two-step process: first, they obtain an OIDC token from Zitadel (`sso.nationtech.io`) using the OAuth 2.0 Device Authorization Grant (RFC 8628); then, they exchange that token for a short-lived OpenBao client token via OpenBao's JWT auth method.
|
||||
|
||||
### The authentication flow
|
||||
|
||||
#### Step 1: Trigger
|
||||
|
||||
The `ConfigManager` attempts to resolve a value via the `StoreSource`. The `StoreSource` checks for a cached OpenBao token in `~/.local/share/harmony/session.json`. If the token is missing or expired, authentication begins.
|
||||
|
||||
#### Step 2: Device Authorization Request
|
||||
|
||||
Harmony sends a `POST` to Zitadel's device authorization endpoint:
|
||||
|
||||
```
|
||||
POST https://sso.nationtech.io/oauth/v2/device_authorization
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
client_id=<harmony_client_id>&scope=openid email profile offline_access
|
||||
```
|
||||
|
||||
Zitadel responds with:
|
||||
|
||||
```json
|
||||
{
|
||||
"device_code": "dOcbPeysDhT26ZatRh9n7Q",
|
||||
"user_code": "GQWC-FWFK",
|
||||
"verification_uri": "https://sso.nationtech.io/device",
|
||||
"verification_uri_complete": "https://sso.nationtech.io/device?user_code=GQWC-FWFK",
|
||||
"expires_in": 300,
|
||||
"interval": 5
|
||||
}
|
||||
```
|
||||
|
||||
#### Step 3: User prompt
|
||||
|
||||
Harmony prints the code and URL to the terminal:
|
||||
|
||||
```
|
||||
[Harmony] To authenticate, open your browser to:
|
||||
https://sso.nationtech.io/device
|
||||
and enter code: GQWC-FWFK
|
||||
|
||||
Or visit: https://sso.nationtech.io/device?user_code=GQWC-FWFK
|
||||
```
|
||||
|
||||
If a desktop environment is detected, Harmony also calls `open` / `xdg-open` to launch the browser automatically. The `verification_uri_complete` URL pre-fills the code, so the user only needs to click "Confirm" after logging in.
|
||||
|
||||
There is no localhost HTTP listener. The CLI does not need to bind a port or receive a callback. This is what makes the device flow work over SSH, in containers, and through corporate firewalls — unlike the `oc login` approach which spins up a temporary web server to catch a redirect.
|
||||
|
||||
#### Step 4: User login
|
||||
|
||||
The developer logs in through Zitadel's web UI using one of the configured identity providers:
|
||||
|
||||
- **Google Workspace** — for teams using Google as their corporate identity.
|
||||
- **GitHub** — for open-source or GitHub-centric teams.
|
||||
- **Microsoft Entra ID (Azure AD)** — for enterprise clients, particularly common in Quebec and the broader Canadian public sector.
|
||||
|
||||
Zitadel federates the login to the chosen provider. The developer authenticates with their existing corporate credentials. No new password is created.
|
||||
|
||||
#### Step 5: Polling
|
||||
|
||||
While the user is authenticating in the browser, Harmony polls Zitadel's token endpoint at the interval specified in the device authorization response (typically 5 seconds):
|
||||
|
||||
```
|
||||
POST https://sso.nationtech.io/oauth/v2/token
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
grant_type=urn:ietf:params:oauth:grant-type:device_code
|
||||
&device_code=dOcbPeysDhT26ZatRh9n7Q
|
||||
&client_id=<harmony_client_id>
|
||||
```
|
||||
|
||||
Before the user completes login, Zitadel responds with `authorization_pending`. Once the user consents, Zitadel returns:
|
||||
|
||||
```json
|
||||
{
|
||||
"access_token": "...",
|
||||
"token_type": "Bearer",
|
||||
"expires_in": 3600,
|
||||
"refresh_token": "...",
|
||||
"id_token": "eyJhbGciOiJSUzI1NiIs..."
|
||||
}
|
||||
```
|
||||
|
||||
The `scope=offline_access` in the initial request is what causes Zitadel to issue a `refresh_token`.
|
||||
|
||||
#### Step 6: OpenBao JWT exchange
|
||||
|
||||
Harmony sends the `id_token` (a JWT signed by Zitadel) to OpenBao's JWT auth method:
|
||||
|
||||
```
|
||||
POST https://secrets.nationtech.io/v1/auth/jwt/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"role": "harmony-developer",
|
||||
"jwt": "eyJhbGciOiJSUzI1NiIs..."
|
||||
}
|
||||
```
|
||||
|
||||
OpenBao validates the JWT:
|
||||
|
||||
1. It fetches Zitadel's public keys from `https://sso.nationtech.io/oauth/v2/keys` (the JWKS endpoint).
|
||||
2. It verifies the JWT signature.
|
||||
3. It reads the claims (`email`, `groups`, and any custom claims mapped from the upstream identity provider, such as Azure AD tenant or Google Workspace org).
|
||||
4. It evaluates the claims against the `bound_claims` and `bound_audiences` configured on the `harmony-developer` role.
|
||||
5. If validation passes, OpenBao returns a client token:
|
||||
|
||||
```json
|
||||
{
|
||||
"auth": {
|
||||
"client_token": "hvs.CAES...",
|
||||
"policies": ["harmony-dev"],
|
||||
"metadata": { "role": "harmony-developer" },
|
||||
"lease_duration": 14400,
|
||||
"renewable": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Harmony caches the OpenBao token, the OIDC refresh token, and the token expiry timestamps to `~/.local/share/harmony/session.json` with `0600` file permissions.
|
||||
|
||||
### OpenBao storage structure
|
||||
|
||||
All configuration and secret state is stored in an OpenBao Versioned KV v2 engine.
|
||||
|
||||
Path taxonomy:
|
||||
|
||||
```
|
||||
harmony/<organization>/<project>/<environment>/<key>
|
||||
```
|
||||
|
||||
Examples:
|
||||
|
||||
```
|
||||
harmony/nationtech/my-app/staging/PostgresConfig
|
||||
harmony/nationtech/my-app/production/PostgresConfig
|
||||
harmony/nationtech/my-app/local-shared/PostgresConfig
|
||||
```
|
||||
|
||||
The `ConfigClass` (Standard vs. Secret) can influence OpenBao policy structure — for example, `Secret`-class paths could require stricter ACLs or additional audit backends — but the path taxonomy itself does not change. This is an operational concern configured in OpenBao policies, not a structural one enforced by path naming.
|
||||
|
||||
### Token lifecycle and silent refresh
|
||||
|
||||
The system manages three tokens with different lifetimes:
|
||||
|
||||
| Token | TTL | Max TTL | Purpose |
|
||||
|---|---|---|---|
|
||||
| OpenBao client token | 4 hours | 24 hours | Read/write config store |
|
||||
| OIDC ID token | 1 hour | — | Exchange for OpenBao token |
|
||||
| OIDC refresh token | 90 days absolute, 30 days inactivity | — | Obtain new ID tokens silently |
|
||||
|
||||
The refresh flow, from the developer's perspective:
|
||||
|
||||
1. **Same session (< 4 hours since last use).** The cached OpenBao token is still valid. No network call to Zitadel. Fastest path.
|
||||
2. **Next day (OpenBao token expired, refresh token valid).** Harmony uses the OIDC `refresh_token` to request a new `id_token` from Zitadel's token endpoint (`grant_type=refresh_token`). It then exchanges the new `id_token` for a fresh OpenBao token. This happens silently. The developer sees no prompt.
|
||||
3. **OpenBao token near max TTL (approaching 24 hours of cumulative renewals).** Instead of renewing, Harmony re-authenticates using the refresh token to get a completely fresh OpenBao token. Transparent to the user.
|
||||
4. **After 30 days of inactivity.** The OIDC refresh token expires. Harmony falls back to the device flow (Step 2 above) and prompts the user to re-authenticate in the browser. This is the only scenario where a returning developer sees a login prompt.
|
||||
5. **User offboarded.** An administrator revokes the user's account or group membership in Zitadel. The next time the refresh token is used, Zitadel rejects it. The device flow also fails because the user can no longer authenticate. Access is terminated without any action needed on the OpenBao side.
|
||||
|
||||
OpenBao token renewal uses the `/auth/token/renew-self` endpoint with the `X-Vault-Token` header. Harmony renews proactively at ~75% of the TTL to avoid race conditions.
|
||||
|
||||
### OpenBao role configuration
|
||||
|
||||
The OpenBao JWT auth role for Harmony developers:
|
||||
|
||||
```bash
|
||||
bao write auth/jwt/config \
|
||||
oidc_discovery_url="https://sso.nationtech.io" \
|
||||
bound_issuer="https://sso.nationtech.io"
|
||||
|
||||
bao write auth/jwt/role/harmony-developer \
|
||||
role_type="jwt" \
|
||||
bound_audiences="<harmony_client_id>" \
|
||||
user_claim="email" \
|
||||
groups_claim="urn:zitadel:iam:org:project:roles" \
|
||||
policies="harmony-dev" \
|
||||
ttl="4h" \
|
||||
max_ttl="24h" \
|
||||
token_type="service"
|
||||
```
|
||||
|
||||
The `bound_audiences` claim ties the role to the specific Harmony Zitadel application. The `groups_claim` allows mapping Zitadel project roles to OpenBao policies for per-team or per-project access control.
|
||||
|
||||
### Self-hosted deployments
|
||||
|
||||
For organizations running their own infrastructure, the same architecture applies. The operator deploys Zitadel and OpenBao using Harmony's existing `ZitadelScore` and `OpenbaoScore`. The only configuration needed is three environment variables (or their equivalents in the bootstrap config):
|
||||
|
||||
- `HARMONY_SSO_URL` — the Zitadel instance URL.
|
||||
- `HARMONY_SECRETS_URL` — the OpenBao instance URL.
|
||||
- `HARMONY_SSO_CLIENT_ID` — the Zitadel application client ID.
|
||||
|
||||
None of these are secrets. They can be committed to an infrastructure repository or distributed via any convenient channel.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- Developers authenticate with existing corporate credentials. No new passwords, no static tokens to distribute.
|
||||
- The device flow works in every environment: local terminal, SSH, containers, CI runners, corporate VPNs.
|
||||
- Silent token refresh keeps developers authenticated for weeks without any manual intervention.
|
||||
- User offboarding is a single action in Zitadel. No OpenBao token rotation or manual revocation required.
|
||||
- Azure AD / Microsoft Entra ID support addresses the enterprise and public sector market.
|
||||
|
||||
### Negative
|
||||
|
||||
- The OAuth state machine (device code polling, token refresh, error handling) adds implementation complexity compared to a static token approach.
|
||||
- Developers must have network access to `sso.nationtech.io` and `secrets.nationtech.io` to pull or push configuration state. True offline work falls back to the local file store, which does not sync with the team.
|
||||
- The first login per machine requires a browser interaction. Fully headless first-run scenarios (e.g., a fresh CI runner with no pre-seeded tokens) must use `EnvSource` overrides or a service account JWT.
|
||||
177
docs/adr/020-interactive-configuration-crate.md
Normal file
177
docs/adr/020-interactive-configuration-crate.md
Normal file
@@ -0,0 +1,177 @@
|
||||
# ADR 020: Unified Configuration and Secret Management
|
||||
|
||||
Author: Jean-Gabriel Gill-Couture
|
||||
|
||||
Date: 2026-03-18
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
Harmony's orchestration logic depends on runtime data that falls into two categories:
|
||||
|
||||
1. **Secrets** — credentials, tokens, private keys.
|
||||
2. **Operational configuration** — deployment targets, host selections, port assignments, reboot decisions, and similar contextual choices.
|
||||
|
||||
Both categories share the same fundamental lifecycle: a value must be acquired before execution can proceed, it may come from several backends (environment variable, remote store, interactive prompt), and it must be shareable across a team without polluting the Git repository.
|
||||
|
||||
Treating these categories as separate subsystems forces developers to choose between a "config API" and a "secret API" at every call site. The only meaningful difference between the two is how the storage backend handles the data (plaintext vs. encrypted, audited vs. unaudited) and how the CLI displays it (visible vs. masked). That difference belongs in the backend, not in the application code.
|
||||
|
||||
Three concrete problems drive this change:
|
||||
|
||||
- **Async terminal corruption.** `inquire` prompts assume exclusive terminal ownership. Background tokio tasks emitting log output during a prompt corrupt the terminal state. This is inherent to Harmony's concurrent orchestration model.
|
||||
- **Untestable code paths.** Any function containing an inline `inquire` call requires a real TTY to execute. Unit testing is impossible without ignoring the test entirely.
|
||||
- **No backend integration.** Inline prompts cannot be answered from a remote store, an environment variable, or a CI pipeline. Every automated deployment that passes through a prompting code path requires a human operator at a terminal.
|
||||
|
||||
## Decision
|
||||
|
||||
A single workspace crate, `harmony_config`, provides all configuration and secret acquisition for Harmony. It replaces both `harmony_secret` and all inline `inquire` usage.
|
||||
|
||||
### Schema in Git, state in the store
|
||||
|
||||
The Rust type system serves as the configuration schema. Developers declare what configuration is needed by defining structs:
|
||||
|
||||
```rust
|
||||
#[derive(Config, Serialize, Deserialize, JsonSchema, InteractiveParse)]
|
||||
struct PostgresConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
#[config(secret)]
|
||||
pub password: String,
|
||||
}
|
||||
```
|
||||
|
||||
These structs live in Git and evolve with the code. When a branch introduces a new field, Git tracks that schema change. The actual values live in an external store — OpenBao by default. No `.env` files, no JSON config files, no YAML in the repository.
|
||||
|
||||
### Data classification
|
||||
|
||||
```rust
|
||||
/// Tells the storage backend how to handle the data.
|
||||
pub enum ConfigClass {
|
||||
/// Plaintext storage is acceptable.
|
||||
Standard,
|
||||
/// Must be encrypted at rest, masked in UI, subject to audit logging.
|
||||
Secret,
|
||||
}
|
||||
```
|
||||
|
||||
Classification is determined at the struct level. A struct with no `#[config(secret)]` fields has `ConfigClass::Standard`. A struct with one or more `#[config(secret)]` fields is elevated to `ConfigClass::Secret`. The struct is always stored as a single cohesive JSON blob; field-level splitting across backends is not a concern of the trait.
|
||||
|
||||
The `#[config(secret)]` attribute also instructs the `PromptSource` to mask terminal input for that field during interactive prompting.
|
||||
|
||||
### The Config trait
|
||||
|
||||
```rust
|
||||
pub trait Config: Serialize + DeserializeOwned + JsonSchema + InteractiveParseObj + Sized {
|
||||
/// Stable lookup key. By default, the struct name.
|
||||
const KEY: &'static str;
|
||||
|
||||
/// How the backend should treat this data.
|
||||
const CLASS: ConfigClass;
|
||||
}
|
||||
```
|
||||
|
||||
A `#[derive(Config)]` proc macro generates the implementation. The macro inspects field attributes to determine `CLASS`.
|
||||
|
||||
### The ConfigStore trait
|
||||
|
||||
```rust
|
||||
#[async_trait]
|
||||
pub trait ConfigStore: Send + Sync {
|
||||
async fn get(
|
||||
&self,
|
||||
class: ConfigClass,
|
||||
namespace: &str,
|
||||
key: &str,
|
||||
) -> Result<Option<serde_json::Value>, ConfigError>;
|
||||
|
||||
async fn set(
|
||||
&self,
|
||||
class: ConfigClass,
|
||||
namespace: &str,
|
||||
key: &str,
|
||||
value: &serde_json::Value,
|
||||
) -> Result<(), ConfigError>;
|
||||
}
|
||||
```
|
||||
|
||||
The `class` parameter is a hint. The store implementation decides what to do with it. An OpenBao store may route `Secret` data to a different path prefix or apply stricter ACLs. A future store could split fields across backends — that is an implementation concern, not a trait concern.
|
||||
|
||||
### Resolution chain
|
||||
|
||||
The `ConfigManager` tries sources in priority order:
|
||||
|
||||
1. **`EnvSource`** — reads `HARMONY_CONFIG_{KEY}` as a JSON string. Override hatch for CI/CD pipelines and containerized environments.
|
||||
2. **`StoreSource`** — wraps a `ConfigStore` implementation. For teams, this is the OpenBao backend authenticated via Zitadel OIDC (see ADR 020-1).
|
||||
3. **`PromptSource`** — presents an `interactive-parse` prompt on the terminal. Acquires a process-wide async mutex before rendering to prevent log output corruption.
|
||||
|
||||
When `PromptSource` obtains a value, the `ConfigManager` persists it back to the `StoreSource` so that subsequent runs — by the same developer or any teammate — resolve without prompting.
|
||||
|
||||
Callers that do not include `PromptSource` in their source list never block on a TTY. Test code passes empty source lists and constructs config structs directly.
|
||||
|
||||
### Schema versioning
|
||||
|
||||
The Rust struct is the schema. When a developer renames a field, removes a field, or changes a type on a branch, the store may still contain data shaped for a previous version of the struct. If another team member who does not yet have that commit runs the code, `serde_json::from_value` will fail on the stale entry.
|
||||
|
||||
In the initial implementation, the resolution chain handles this gracefully: a deserialization failure is treated as a cache miss, and the `PromptSource` fires. The prompted value overwrites the stale entry in the store.
|
||||
|
||||
This is sufficient for small teams working on short-lived branches. It is not sufficient at scale, where silent re-prompting could mask real configuration drift.
|
||||
|
||||
A future iteration will introduce a compile-time schema migration mechanism, similar to how `sqlx` verifies queries against a live database at compile time. The mechanism will:
|
||||
|
||||
- Detect schema drift between the Rust struct and the stored JSON.
|
||||
- Apply named, ordered migration functions to transform stored data forward.
|
||||
- Reject ambiguous migrations at compile time rather than silently corrupting state.
|
||||
|
||||
Until that mechanism exists, teams should treat store entries as soft caches: the struct definition is always authoritative, and the store is best-effort.
|
||||
|
||||
## Rationale
|
||||
|
||||
**Why merge secrets and config into one crate?** Separate crates with nearly identical trait shapes (`Secret` vs `Config`, `SecretStore` vs `ConfigStore`) force developers to make a classification decision at every call site. A unified crate with a `ConfigClass` discriminator moves that decision to the struct definition, where it belongs.
|
||||
|
||||
**Why OpenBao as the default backend?** OpenBao is a fully open-source Vault fork under the Linux Foundation. It runs on-premises with no phone-home requirement — a hard constraint for private cloud and regulated environments. Harmony already deploys OpenBao for clients (`OpenbaoScore`), so no new infrastructure is introduced.
|
||||
|
||||
**Why not store values in Git (e.g., encrypted YAML)?** Git-tracked config files create merge conflicts, require re-encryption on team membership changes, and leak metadata (file names, key names) even when values are encrypted. Storing state in OpenBao avoids all of these issues and provides audit logging, access control, and versioned KV out of the box.
|
||||
|
||||
**Why keep `PromptSource`?** Removing interactive prompts entirely would break the zero-infrastructure bootstrapping path and eliminate human-confirmation safety gates for destructive operations (interface reconfiguration, node reboot). The problem was never that prompts exist — it is that they were unavoidable and untestable. Making `PromptSource` an explicit, opt-in entry in the source list restores control.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- A single API surface for all runtime data acquisition.
|
||||
- All currently-ignored tests become runnable without TTY access.
|
||||
- Async terminal corruption is eliminated by the process-wide prompt mutex.
|
||||
- The bootstrapping path requires no infrastructure for a first run; `PromptSource` alone is sufficient.
|
||||
- The team path (OpenBao + Zitadel) reuses infrastructure Harmony already deploys.
|
||||
- User offboarding is a single Zitadel action.
|
||||
|
||||
### Negative
|
||||
|
||||
- Migrating all inline `inquire` and `harmony_secret` call sites is a significant refactoring effort.
|
||||
- Until the schema migration mechanism is built, store entries for renamed or removed fields become stale and must be re-prompted.
|
||||
- The Zitadel device flow introduces a browser step on first login per machine.
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Trait design and crate restructure
|
||||
|
||||
Refactor `harmony_config` to define the final `Config`, `ConfigClass`, and `ConfigStore` traits. Update the derive macro to support `#[config(secret)]` and generate the correct `CLASS` constant. Implement `EnvSource` and `PromptSource` against the new traits. Write comprehensive unit tests using mock stores.
|
||||
|
||||
### Phase 2: Absorb `harmony_secret`
|
||||
|
||||
Migrate the `OpenbaoSecretStore`, `InfisicalSecretStore`, and `LocalFileSecretStore` implementations from `harmony_secret` into `harmony_config` as `ConfigStore` backends. Update all call sites that use `SecretManager::get`, `SecretManager::get_or_prompt`, or `SecretManager::set` to use `harmony_config` equivalents.
|
||||
|
||||
### Phase 3: Migrate inline prompts
|
||||
|
||||
Replace all inline `inquire` call sites in the `harmony` crate (`infra/brocade.rs`, `infra/network_manager.rs`, `modules/okd/host_network.rs`, and others) with `harmony_config` structs and `get_or_prompt` calls. Un-ignore the affected tests.
|
||||
|
||||
### Phase 4: Zitadel and OpenBao integration
|
||||
|
||||
Implement the authentication flow described in ADR 020-1. Wire `StoreSource` to use Zitadel OIDC tokens for OpenBao access. Implement token caching and silent refresh.
|
||||
|
||||
### Phase 5: Remove `harmony_secret`
|
||||
|
||||
Delete the `harmony_secret` and `harmony_secret_derive` crates from the workspace. All functionality now lives in `harmony_config`.
|
||||
63
docs/adr/README.md
Normal file
63
docs/adr/README.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Architecture Decision Records
|
||||
|
||||
An Architecture Decision Record (ADR) documents a significant architectural decision made during the development of Harmony — along with its context, rationale, and consequences.
|
||||
|
||||
## Why We Use ADRs
|
||||
|
||||
As a platform engineering framework used by a team, Harmony accumulates technical decisions over time. ADRs help us:
|
||||
|
||||
- **Track rationale** — understand _why_ a decision was made, not just _what_ was decided
|
||||
- ** onboard new contributors** — the "why" is preserved even when team membership changes
|
||||
- **Avoid repeating past mistakes** — previous decisions and their context are searchable
|
||||
- **Manage technical debt** — ADRs make it easier to revisit and revise past choices
|
||||
|
||||
An ADR captures a decision at a point in time. It is not a specification — it is a record of reasoning.
|
||||
|
||||
## ADR Format
|
||||
|
||||
Every ADR follows this structure:
|
||||
|
||||
| Section | Purpose |
|
||||
|---------|---------|
|
||||
| **Status** | Proposed / Pending / Accepted / Implemented / Deprecated |
|
||||
| **Context** | The problem or background — the "why" behind this decision |
|
||||
| **Decision** | The chosen solution or direction |
|
||||
| **Rationale** | Reasoning behind the decision |
|
||||
| **Consequences** | Both positive and negative outcomes |
|
||||
| **Alternatives considered** | Other options that were evaluated |
|
||||
| **Additional Notes** | Supplementary context, links, or open questions |
|
||||
|
||||
## ADR Index
|
||||
|
||||
| Number | Title | Status |
|
||||
|--------|-------|--------|
|
||||
| [000](./000-ADR-Template.md) | ADR Template | Reference |
|
||||
| [001](./001-rust.md) | Why Rust | Accepted |
|
||||
| [002](./002-hexagonal-architecture.md) | Hexagonal Architecture | Accepted |
|
||||
| [003](./003-infrastructure-abstractions.md) | Infrastructure Abstractions | Accepted |
|
||||
| [004](./004-ipxe.md) | iPXE | Accepted |
|
||||
| [005](./005-interactive-project.md) | Interactive Project | Proposed |
|
||||
| [006](./006-secret-management.md) | Secret Management | Accepted |
|
||||
| [007](./007-default-runtime.md) | Default Runtime | Accepted |
|
||||
| [008](./008-score-display-formatting.md) | Score Display Formatting | Proposed |
|
||||
| [009](./009-helm-and-kustomize-handling.md) | Helm and Kustomize Handling | Accepted |
|
||||
| [010](./010-monitoring-and-alerting.md) | Monitoring and Alerting | Accepted |
|
||||
| [011](./011-multi-tenant-cluster.md) | Multi-Tenant Cluster | Accepted |
|
||||
| [012](./012-project-delivery-automation.md) | Project Delivery Automation | Proposed |
|
||||
| [013](./013-monitoring-notifications.md) | Monitoring Notifications | Accepted |
|
||||
| [015](./015-higher-order-topologies.md) | Higher Order Topologies | Proposed |
|
||||
| [016](./016-Harmony-Agent-And-Global-Mesh-For-Decentralized-Workload-Management.md) | Harmony Agent and Global Mesh | Proposed |
|
||||
| [017-1](./017-1-Nats-Clusters-Interconnection-Topology.md) | NATS Clusters Interconnection Topology | Proposed |
|
||||
| [018](./018-Template-Hydration-For-Workload-Deployment.md) | Template Hydration for Workload Deployment | Proposed |
|
||||
| [019](./019-Network-bond-setup.md) | Network Bond Setup | Proposed |
|
||||
| [020-1](./020-1-zitadel-openbao-secure-config-store.md) | Zitadel + OpenBao Secure Config Store | Accepted |
|
||||
| [020](./020-interactive-configuration-crate.md) | Interactive Configuration Crate | Proposed |
|
||||
|
||||
## Contributing
|
||||
|
||||
When making a significant technical change:
|
||||
|
||||
1. **Check existing ADRs** — the decision may already be documented
|
||||
2. **Create a new ADR** using the [template](./000-ADR-Template.md) if the change warrants architectural discussion
|
||||
3. **Set status to Proposed** and open it for team review
|
||||
4. Once accepted and implemented, update the status accordingly
|
||||
@@ -84,7 +84,7 @@ Network services that run inside the cluster or as part of the topology.
|
||||
- **OKDLoadBalancerScore**: Configures the high-availability load balancers for the OKD API and ingress.
|
||||
- **OKDBootstrapLoadBalancerScore**: Configures the load balancer specifically for the bootstrap-time API endpoint.
|
||||
- **K8sIngressScore**: Configures an Ingress controller or resource.
|
||||
- [HighAvailabilityHostNetworkScore](../../harmony/src/modules/okd/host_network.rs): Configures network bonds on a host and the corresponding port-channels on the switch stack for high-availability.
|
||||
- **HighAvailabilityHostNetworkScore**: Configures network bonds on a host and the corresponding port-channels on the switch stack for high-availability.
|
||||
|
||||
## Tenant Management
|
||||
|
||||
|
||||
@@ -28,6 +28,11 @@ Harmony's design is based on a few key concepts. Understanding them is the key t
|
||||
- **What it is:** An **Inventory** is the physical material (the "what") used in a cluster. This is most relevant for bare-metal or on-premise topologies.
|
||||
- **Example:** A list of nodes with their roles (control plane, worker), CPU, RAM, and network interfaces. For the `K8sAnywhereTopology`, the inventory might be empty or autoloaded, as the infrastructure is more abstract.
|
||||
|
||||
### 6. Configuration & Secrets
|
||||
|
||||
- **What it is:** Configuration represents the runtime data required to deploy your `Scores`. This includes both non-sensitive state (like cluster hostnames, deployment profiles) and sensitive secrets (like API keys, database passwords).
|
||||
- **How it works:** See the [Configuration Concept Guide](./concepts/configuration.md) to understand Harmony's unified approach to managing schema in Git and state in OpenBao.
|
||||
|
||||
---
|
||||
|
||||
### How They Work Together (The Compile-Time Check)
|
||||
|
||||
107
docs/concepts/configuration.md
Normal file
107
docs/concepts/configuration.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Configuration and Secrets
|
||||
|
||||
Harmony treats configuration and secrets as a single concern. Developers use one crate, `harmony_config`, to declare, store, and retrieve all runtime data — whether it is a public hostname or a database password.
|
||||
|
||||
## The mental model: schema in Git, state in the store
|
||||
|
||||
### Schema
|
||||
|
||||
In Harmony, the Rust code is the configuration schema. You declare what your module needs by defining a struct:
|
||||
|
||||
```rust
|
||||
#[derive(Config, Serialize, Deserialize, JsonSchema, InteractiveParse)]
|
||||
struct PostgresConfig {
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
#[config(secret)]
|
||||
pub password: String,
|
||||
}
|
||||
```
|
||||
|
||||
This struct is tracked in Git. When a branch adds a new field, Git tracks that the branch requires a new value. When a branch removes a field, the old value in the store becomes irrelevant. The struct is always authoritative.
|
||||
|
||||
### State
|
||||
|
||||
The actual values live in a config store — by default, OpenBao. No `.env` files, no JSON, no YAML in the repository.
|
||||
|
||||
When you run your code, Harmony reads the struct (schema) and resolves values from the store (state):
|
||||
|
||||
- If the store has the value, it is injected seamlessly.
|
||||
- If the store does not have it, Harmony prompts you in the terminal. Your answer is pushed back to the store automatically.
|
||||
- When a teammate runs the same code, they are not prompted — you already provided the value.
|
||||
|
||||
### How branch switching works
|
||||
|
||||
Because the schema is just Rust code tracked in Git, branch switching works naturally:
|
||||
|
||||
1. You check out `feat/redis`. The code now requires `RedisConfig`.
|
||||
2. You run `cargo run`. Harmony detects that `RedisConfig` has no value in the store. It prompts you.
|
||||
3. You provide the values. Harmony pushes them to OpenBao.
|
||||
4. Your teammate checks out `feat/redis` and runs `cargo run`. No prompt — the values are already in the store.
|
||||
5. You switch back to `main`. `RedisConfig` does not exist in that branch's code. The store entry is ignored.
|
||||
|
||||
## Secrets vs. standard configuration
|
||||
|
||||
From your application code, there is no difference. You always call `harmony_config::get_or_prompt::<T>()`.
|
||||
|
||||
The difference is in the struct definition:
|
||||
|
||||
```rust
|
||||
// Standard config — stored in plaintext, displayed during prompting.
|
||||
#[derive(Config)]
|
||||
struct ClusterConfig {
|
||||
pub api_url: String,
|
||||
pub namespace: String,
|
||||
}
|
||||
|
||||
// Contains a secret field — the entire struct is stored encrypted,
|
||||
// and the password field is masked during terminal prompting.
|
||||
#[derive(Config)]
|
||||
struct DatabaseConfig {
|
||||
pub host: String,
|
||||
#[config(secret)]
|
||||
pub password: String,
|
||||
}
|
||||
```
|
||||
|
||||
If a struct contains any `#[config(secret)]` field, Harmony elevates the entire struct to `ConfigClass::Secret`. The storage backend decides what that means in practice — in the case of OpenBao, it may route the data to a path with stricter ACLs or audit policies.
|
||||
|
||||
## Authentication and team sharing
|
||||
|
||||
Harmony uses Zitadel (hosted at `sso.nationtech.io`) for identity and OpenBao (hosted at `secrets.nationtech.io`) for storage.
|
||||
|
||||
**First run on a new machine:**
|
||||
|
||||
1. Harmony detects that you are not logged in.
|
||||
2. It prints a short code and URL to your terminal, and opens your browser if possible.
|
||||
3. You log in with your corporate identity (Google, GitHub, or Microsoft Entra ID / Azure AD).
|
||||
4. Harmony receives an OIDC token, exchanges it for an OpenBao token, and caches the session locally.
|
||||
|
||||
**Subsequent runs:**
|
||||
|
||||
- Harmony silently refreshes your tokens in the background. You do not need to log in again for up to 90 days of active use.
|
||||
- If you are inactive for 30 days, or if an administrator revokes your access in Zitadel, you will be prompted to re-authenticate.
|
||||
|
||||
**Offboarding:**
|
||||
|
||||
Revoking a user in Zitadel immediately invalidates their ability to refresh tokens or obtain new ones. No manual secret rotation is required.
|
||||
|
||||
## Resolution chain
|
||||
|
||||
When Harmony resolves a config value, it tries sources in order:
|
||||
|
||||
1. **Environment variable** (`HARMONY_CONFIG_{KEY}`) — highest priority. Use this in CI/CD to override any value without touching the store.
|
||||
2. **Config store** (OpenBao for teams, local file for solo/offline use) — the primary source for shared team state.
|
||||
3. **Interactive prompt** — last resort. Prompts the developer and persists the answer back to the store.
|
||||
|
||||
## Schema versioning
|
||||
|
||||
The Rust struct is the single source of truth for what configuration looks like. If a developer renames or removes a field on a branch, the store may still contain data shaped for the old version of the struct. When another developer who does not have that change runs the code, deserialization will fail.
|
||||
|
||||
In the current implementation, this is handled gracefully: a deserialization failure is treated as a miss, and Harmony re-prompts. The new answer overwrites the stale entry.
|
||||
|
||||
A compile-time migration mechanism is planned for a future release to handle this more rigorously at scale.
|
||||
|
||||
## Offline and local development
|
||||
|
||||
If you are working offline or evaluating Harmony without a team OpenBao instance, the `StoreSource` falls back to a local file store at `~/.local/share/harmony/config/`. The developer experience is identical — prompting, caching, and resolution all work the same way. The only difference is that the state is local to your machine and not shared with teammates.
|
||||
135
docs/guides/adding-capabilities.md
Normal file
135
docs/guides/adding-capabilities.md
Normal file
@@ -0,0 +1,135 @@
|
||||
# Adding Capabilities
|
||||
|
||||
`Capabilities` are trait methods that a `Topology` exposes to Scores. They are the "how" — the specific APIs and features that let a Score translate intent into infrastructure actions.
|
||||
|
||||
## How Capabilities Work
|
||||
|
||||
When a Score declares it needs certain Capabilities:
|
||||
|
||||
```rust
|
||||
impl<T: Topology + K8sclient + HelmCommand> Score<T> for MyScore {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
The compiler verifies that the target `Topology` implements both `K8sclient` and `HelmCommand`. If it doesn't, compilation fails. This is the compile-time safety check that prevents invalid configurations from reaching production.
|
||||
|
||||
## Built-in Capabilities
|
||||
|
||||
Harmony provides a set of standard Capabilities:
|
||||
|
||||
| Capability | What it provides |
|
||||
|------------|------------------|
|
||||
| `K8sclient` | A Kubernetes API client |
|
||||
| `HelmCommand` | A configured `helm` CLI invocation |
|
||||
| `TlsRouter` | TLS certificate management |
|
||||
| `NetworkManager` | Host network configuration |
|
||||
| `SwitchClient` | Network switch configuration |
|
||||
| `CertificateManagement` | Certificate issuance via cert-manager |
|
||||
|
||||
## Implementing a Capability
|
||||
|
||||
Capabilities are implemented as trait methods on your Topology:
|
||||
|
||||
```rust
|
||||
use std::sync::Arc;
|
||||
use harmony_k8s::K8sClient;
|
||||
use harmony::topology::K8sclient;
|
||||
|
||||
pub struct MyTopology {
|
||||
kubeconfig: Option<String>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl K8sclient for MyTopology {
|
||||
async fn k8s_client(&self) -> Result<Arc<K8sClient>, String> {
|
||||
let client = match &self.kubeconfig {
|
||||
Some(path) => K8sClient::from_kubeconfig(path).await?,
|
||||
None => K8sClient::try_default().await?,
|
||||
};
|
||||
Ok(Arc::new(client))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Adding a Custom Capability
|
||||
|
||||
For specialized infrastructure needs, add your own Capability as a trait:
|
||||
|
||||
```rust
|
||||
use async_trait::async_trait;
|
||||
use crate::executors::ExecutorError;
|
||||
|
||||
/// A capability for configuring network switches
|
||||
#[async_trait]
|
||||
pub trait SwitchClient: Send + Sync {
|
||||
async fn configure_port(
|
||||
&self,
|
||||
switch: &str,
|
||||
port: &str,
|
||||
vlan: u16,
|
||||
) -> Result<(), ExecutorError>;
|
||||
|
||||
async fn configure_port_channel(
|
||||
&self,
|
||||
switch: &str,
|
||||
name: &str,
|
||||
ports: &[&str],
|
||||
) -> Result<(), ExecutorError>;
|
||||
}
|
||||
```
|
||||
|
||||
Then implement it on your Topology:
|
||||
|
||||
```rust
|
||||
use harmony_infra::brocade::BrocadeClient;
|
||||
|
||||
pub struct MyTopology {
|
||||
switch_client: Arc<dyn SwitchClient>,
|
||||
}
|
||||
|
||||
impl SwitchClient for MyTopology {
|
||||
async fn configure_port(&self, switch: &str, port: &str, vlan: u16) -> Result<(), ExecutorError> {
|
||||
self.switch_client.configure_port(switch, port, vlan).await
|
||||
}
|
||||
|
||||
async fn configure_port_channel(&self, switch: &str, name: &str, ports: &[&str]) -> Result<(), ExecutorError> {
|
||||
self.switch_client.configure_port_channel(switch, name, ports).await
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Now Scores that need `SwitchClient` can run on `MyTopology`.
|
||||
|
||||
## Capability Composition
|
||||
|
||||
Topologies often compose multiple Capabilities to support complex Scores:
|
||||
|
||||
```rust
|
||||
pub struct HAClusterTopology {
|
||||
pub kubeconfig: Option<String>,
|
||||
pub router: Arc<dyn Router>,
|
||||
pub load_balancer: Arc<dyn LoadBalancer>,
|
||||
pub switch_client: Arc<dyn SwitchClient>,
|
||||
pub dhcp_server: Arc<dyn DhcpServer>,
|
||||
pub dns_server: Arc<dyn DnsServer>,
|
||||
// ...
|
||||
}
|
||||
|
||||
impl K8sclient for HAClusterTopology { ... }
|
||||
impl HelmCommand for HAClusterTopology { ... }
|
||||
impl SwitchClient for HAClusterTopology { ... }
|
||||
impl DhcpServer for HAClusterTopology { ... }
|
||||
impl DnsServer for HAClusterTopology { ... }
|
||||
impl Router for HAClusterTopology { ... }
|
||||
impl LoadBalancer for HAClusterTopology { ... }
|
||||
```
|
||||
|
||||
A Score that needs all of these can run on `HAClusterTopology` because the Topology provides all of them.
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Keep Capabilities focused** — one Capability per concern (Kubernetes client, Helm, switch config)
|
||||
- **Return meaningful errors** — use specific error types so Scores can handle failures appropriately
|
||||
- **Make Capabilities optional where sensible** — not every Topology needs every Capability; use `Option<T>` or a separate trait for optional features
|
||||
- **Document preconditions** — if a Capability requires the infrastructure to be in a specific state, document it in the trait doc comments
|
||||
40
docs/guides/developer-guide.md
Normal file
40
docs/guides/developer-guide.md
Normal file
@@ -0,0 +1,40 @@
|
||||
# Developer Guide
|
||||
|
||||
This section covers how to extend Harmony by building your own `Score`, `Topology`, and `Capability` implementations.
|
||||
|
||||
## Writing a Score
|
||||
|
||||
A `Score` is a declarative description of desired state. To create your own:
|
||||
|
||||
1. Define a struct that represents your desired state
|
||||
2. Implement the `Score<T>` trait, where `T` is your target `Topology`
|
||||
3. Implement the `Interpret<T>` trait to define how the Score translates to infrastructure actions
|
||||
|
||||
See the [Writing a Score](./writing-a-score.md) guide for a step-by-step walkthrough.
|
||||
|
||||
## Writing a Topology
|
||||
|
||||
A `Topology` models your infrastructure environment. To create your own:
|
||||
|
||||
1. Define a struct that holds your infrastructure configuration
|
||||
2. Implement the `Topology` trait
|
||||
3. Implement the `Capability` traits your Score needs
|
||||
|
||||
See the [Writing a Topology](./writing-a-topology.md) guide for details.
|
||||
|
||||
## Adding Capabilities
|
||||
|
||||
`Capabilities` are the specific APIs or features a `Topology` exposes. They are the bridge between Scores and the actual infrastructure.
|
||||
|
||||
See the [Adding Capabilities](./adding-capabilities.md) guide for details on implementing and exposing Capabilities.
|
||||
|
||||
## Core Traits Reference
|
||||
|
||||
| Trait | Purpose |
|
||||
|-------|---------|
|
||||
| `Score<T>` | Declares desired state ("what") |
|
||||
| `Topology` | Represents infrastructure ("where") |
|
||||
| `Interpret<T>` | Execution logic ("how") |
|
||||
| `Capability` | A feature exposed by a Topology |
|
||||
|
||||
See [Core Concepts](../concepts.md) for the conceptual foundation.
|
||||
@@ -1,42 +1,230 @@
|
||||
# Getting Started Guide
|
||||
|
||||
Welcome to Harmony! This guide will walk you through installing the Harmony framework, setting up a new project, and deploying your first application.
|
||||
This guide walks you through deploying your first application with Harmony — a PostgreSQL cluster on a local Kubernetes cluster (K3D). By the end, you'll understand the core workflow: compile a Score, run it through the Harmony CLI, and verify the result.
|
||||
|
||||
We will build and deploy the "Rust Web App" example, which automatically:
|
||||
## What you'll deploy
|
||||
|
||||
1. Provisions a local K3D (Kubernetes in Docker) cluster.
|
||||
2. Deploys a sample Rust web application.
|
||||
3. Sets up monitoring for the application.
|
||||
A fully functional PostgreSQL cluster running in a local K3D cluster, managed by the CloudNativePG operator. This demonstrates the full Harmony pattern:
|
||||
|
||||
1. Provision a local Kubernetes cluster (K3D)
|
||||
2. Install the required operator (CloudNativePG)
|
||||
3. Create a PostgreSQL cluster
|
||||
4. Expose it as a Kubernetes Service
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, you'll need a few tools installed on your system:
|
||||
Before you begin, install the following tools:
|
||||
|
||||
- **Rust & Cargo:** [Install Rust](https://www.rust-lang.org/tools/install)
|
||||
- **Docker:** [Install Docker](https://docs.docker.com/get-docker/) (Required for the K3D local cluster)
|
||||
- **kubectl:** [Install kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) (For inspecting the cluster)
|
||||
- **Rust & Cargo:** [Install Rust](https://rust-lang.org/tools/install) (edition 2024)
|
||||
- **Docker:** [Install Docker](https://docs.docker.com/get-docker/) (required for the local K3D cluster)
|
||||
- **kubectl:** [Install kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) (optional, for inspecting the cluster)
|
||||
|
||||
## 1. Install Harmony
|
||||
|
||||
First, clone the Harmony repository and build the project. This gives you the `harmony` CLI and all the core libraries.
|
||||
## Step 1: Clone and build
|
||||
|
||||
```bash
|
||||
# Clone the main repository
|
||||
# Clone the repository
|
||||
git clone https://git.nationtech.io/nationtech/harmony
|
||||
cd harmony
|
||||
|
||||
# Build the project (this may take a few minutes)
|
||||
# Build the project (this may take a few minutes on first run)
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
...
|
||||
## Step 2: Run the PostgreSQL example
|
||||
|
||||
## Next Steps
|
||||
```bash
|
||||
cargo run -p example-postgresql
|
||||
```
|
||||
|
||||
Congratulations, you've just deployed an application using true infrastructure-as-code!
|
||||
Harmony will output its progress as it:
|
||||
|
||||
From here, you can:
|
||||
1. **Creates a K3D cluster** named `harmony-postgres-example` (first run only)
|
||||
2. **Installs the CloudNativePG operator** into the cluster
|
||||
3. **Creates a PostgreSQL cluster** with 1 instance and 1 GiB of storage
|
||||
4. **Prints connection details** for your new database
|
||||
|
||||
- [Explore the Catalogs](../catalogs/README.md): See what other [Scores](../catalogs/scores.md) and [Topologies](../catalogs/topologies.md) are available.
|
||||
- [Read the Use Cases](../use-cases/README.md): Check out the [OKD on Bare Metal](./use-cases/okd-on-bare-metal.md) guide for a more advanced scenario.
|
||||
- [Write your own Score](../guides/writing-a-score.md): Dive into the [Developer Guide](./guides/developer-guide.md) to start building your own components.
|
||||
Expected output (abbreviated):
|
||||
|
||||
```
|
||||
[+] Cluster created
|
||||
[+] Installing CloudNativePG operator
|
||||
[+] Creating PostgreSQL cluster
|
||||
[+] PostgreSQL cluster is ready
|
||||
Namespace: harmony-postgres-example
|
||||
Service: harmony-postgres-example-rw
|
||||
Username: postgres
|
||||
Password: <stored in secret harmony-postgres-example-db-user>
|
||||
```
|
||||
|
||||
## Step 3: Verify the deployment
|
||||
|
||||
Check that the PostgreSQL pods are running:
|
||||
|
||||
```bash
|
||||
kubectl get pods -n harmony-postgres-example
|
||||
```
|
||||
|
||||
You should see something like:
|
||||
|
||||
```
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
harmony-postgres-example-1 1/1 Running 0 2m
|
||||
```
|
||||
|
||||
Get the database password:
|
||||
|
||||
```bash
|
||||
kubectl get secret -n harmony-postgres-example harmony-postgres-example-db-user -o jsonpath='{.data.password}' | base64 -d
|
||||
```
|
||||
|
||||
## Step 4: Connect to the database
|
||||
|
||||
Forward the PostgreSQL port to your local machine:
|
||||
|
||||
```bash
|
||||
kubectl port-forward -n harmony-postgres-example svc/harmony-postgres-example-rw 5432:5432
|
||||
```
|
||||
|
||||
In another terminal, connect with `psql`:
|
||||
|
||||
```bash
|
||||
psql -h localhost -p 5432 -U postgres
|
||||
# Enter the password from Step 4 when prompted
|
||||
```
|
||||
|
||||
Try a simple query:
|
||||
|
||||
```sql
|
||||
SELECT version();
|
||||
```
|
||||
|
||||
## Step 5: Clean up
|
||||
|
||||
To delete the PostgreSQL cluster and the local K3D cluster:
|
||||
|
||||
```bash
|
||||
k3d cluster delete harmony-postgres-example
|
||||
```
|
||||
|
||||
Alternatively, just delete the PostgreSQL cluster without removing K3D:
|
||||
|
||||
```bash
|
||||
kubectl delete namespace harmony-postgres-example
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
The example code (`examples/postgresql/src/main.rs`) is straightforward:
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::postgresql::{PostgreSQLScore, capability::PostgreSQLConfig},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let postgres = PostgreSQLScore {
|
||||
config: PostgreSQLConfig {
|
||||
cluster_name: "harmony-postgres-example".to_string(),
|
||||
namespace: "harmony-postgres-example".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(postgres)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
- **`Inventory::autoload()`** discovers the local environment (or uses an existing inventory)
|
||||
- **`K8sAnywhereTopology::from_env()`** connects to K3D if `HARMONY_AUTOINSTALL=true` (the default), or to any Kubernetes cluster via `KUBECONFIG`
|
||||
- **`harmony_cli::run(...)`** executes the Score against the Topology, managing the full lifecycle
|
||||
|
||||
## Connecting to an existing cluster
|
||||
|
||||
By default, Harmony provisions a local K3D cluster. To use an existing Kubernetes cluster instead:
|
||||
|
||||
```bash
|
||||
export KUBECONFIG=/path/to/your/kubeconfig
|
||||
export HARMONY_USE_LOCAL_K3D=false
|
||||
export HARMONY_AUTOINSTALL=false
|
||||
|
||||
cargo run -p example-postgresql
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Docker is not running
|
||||
|
||||
```
|
||||
Error: could not create cluster: docker is not running
|
||||
```
|
||||
|
||||
Start Docker and try again.
|
||||
|
||||
### K3D cluster creation fails
|
||||
|
||||
```
|
||||
Error: failed to create k3d cluster
|
||||
```
|
||||
|
||||
Ensure you have at least 2 CPU cores and 4 GiB of RAM available for Docker.
|
||||
|
||||
### `kubectl` cannot connect to the cluster
|
||||
|
||||
```
|
||||
error: unable to connect to a kubernetes cluster
|
||||
```
|
||||
|
||||
After Harmony creates the cluster, it writes the kubeconfig to `~/.kube/config` or to the path in `KUBECONFIG`. Verify:
|
||||
|
||||
```bash
|
||||
kubectl cluster-info --context k3d-harmony-postgres-example
|
||||
```
|
||||
|
||||
### Port forward fails
|
||||
|
||||
```
|
||||
error: unable to forward port
|
||||
```
|
||||
|
||||
Make sure no other process is using port 5432, or use a different local port:
|
||||
|
||||
```bash
|
||||
kubectl port-forward -n harmony-postgres-example svc/harmony-postgres-example-rw 15432:5432
|
||||
psql -h localhost -p 15432 -U postgres
|
||||
```
|
||||
|
||||
## Next steps
|
||||
|
||||
- [Explore the Scores Catalog](../catalogs/scores.md): See what other Scores are available
|
||||
- [Explore the Topologies Catalog](../catalogs/topologies.md): See what infrastructure Topologies are supported
|
||||
- [Read the Core Concepts](../concepts.md): Understand the Score / Topology / Interpret pattern in depth
|
||||
- [OKD on Bare Metal](../use-cases/okd-on-bare-metal.md): See a complete bare-metal deployment example
|
||||
|
||||
## Advanced examples
|
||||
|
||||
Once you're comfortable with the basics, these examples demonstrate more advanced use cases. Note that some require specific infrastructure (existing Kubernetes clusters, bare-metal hardware, or multi-cluster environments):
|
||||
|
||||
| Example | Description | Prerequisites |
|
||||
|---------|-------------|---------------|
|
||||
| `monitoring` | Deploy Prometheus alerting with Discord webhooks | Existing K8s cluster |
|
||||
| `ntfy` | Deploy ntfy notification server | Existing K8s cluster |
|
||||
| `tenant` | Create a multi-tenant namespace with quotas | Existing K8s cluster |
|
||||
| `cert_manager` | Provision TLS certificates | Existing K8s cluster |
|
||||
| `validate_ceph_cluster_health` | Check Ceph cluster health | Existing Rook/Ceph cluster |
|
||||
| `okd_pxe` / `okd_installation` | Provision OKD on bare metal | HAClusterTopology, bare-metal hardware |
|
||||
|
||||
To run any example:
|
||||
|
||||
```bash
|
||||
cargo run -p example-<example_name>
|
||||
```
|
||||
|
||||
164
docs/guides/writing-a-score.md
Normal file
164
docs/guides/writing-a-score.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# Writing a Score
|
||||
|
||||
A `Score` declares _what_ you want to achieve. It is decoupled from _how_ it is achieved — that logic lives in an `Interpret`.
|
||||
|
||||
## The Pattern
|
||||
|
||||
A Score consists of two parts:
|
||||
|
||||
1. **A struct** — holds the configuration for your desired state
|
||||
2. **A `Score<T>` implementation** — returns an `Interpret` that knows how to execute
|
||||
|
||||
An `Interpret` contains the actual execution logic and connects your Score to the capabilities exposed by a `Topology`.
|
||||
|
||||
## Example: A Simple Score
|
||||
|
||||
Here's a simplified version of `NtfyScore` from the `ntfy` module:
|
||||
|
||||
```rust
|
||||
use async_trait::async_trait;
|
||||
use harmony::{
|
||||
interpret::{Interpret, InterpretError, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::{HelmCommand, K8sclient, Topology},
|
||||
};
|
||||
|
||||
/// MyScore declares "I want to install the ntfy server"
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MyScore {
|
||||
pub namespace: String,
|
||||
pub host: String,
|
||||
}
|
||||
|
||||
impl<T: Topology + HelmCommand + K8sclient> Score<T> for MyScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(MyInterpret { score: self.clone() })
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
"ntfy [MyScore]".into()
|
||||
}
|
||||
}
|
||||
|
||||
/// MyInterpret knows _how_ to install ntfy using the Topology's capabilities
|
||||
#[derive(Debug)]
|
||||
pub struct MyInterpret {
|
||||
pub score: MyScore,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Topology + HelmCommand + K8sclient> Interpret<T> for MyInterpret {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &T,
|
||||
) -> Result<Outcome, InterpretError> {
|
||||
// 1. Get a Kubernetes client from the Topology
|
||||
let client = topology.k8s_client().await?;
|
||||
|
||||
// 2. Use Helm to install the ntfy chart
|
||||
// (via topology's HelmCommand capability)
|
||||
|
||||
// 3. Wait for the deployment to be ready
|
||||
client
|
||||
.wait_until_deployment_ready("ntfy", Some(&self.score.namespace), None)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::success("ntfy installed".to_string()))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## The Compile-Time Safety Check
|
||||
|
||||
The generic `Score<T>` trait is bounded by `T: Topology`. This means the compiler enforces that your Score only runs on Topologies that expose the capabilities your Interpret needs:
|
||||
|
||||
```rust
|
||||
// This only compiles if K8sAnywhereTopology (or any T)
|
||||
// implements HelmCommand and K8sclient
|
||||
impl<T: Topology + HelmCommand + K8sclient> Score<T> for MyScore { ... }
|
||||
```
|
||||
|
||||
If you try to run this Score against a Topology that doesn't expose `HelmCommand`, you get a compile error — before any code runs.
|
||||
|
||||
## Using Your Score
|
||||
|
||||
Once defined, your Score integrates with the Harmony CLI:
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let my_score = MyScore {
|
||||
namespace: "monitoring".to_string(),
|
||||
host: "ntfy.example.com".to_string(),
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(my_score)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Composing Scores
|
||||
|
||||
Scores can include other Scores via features:
|
||||
|
||||
```rust
|
||||
let app = ApplicationScore {
|
||||
features: vec![
|
||||
Box::new(PackagingDeployment { application: app.clone() }),
|
||||
Box::new(Monitoring { application: app.clone(), alert_receiver: vec![] }),
|
||||
],
|
||||
application: app,
|
||||
};
|
||||
```
|
||||
|
||||
### Reusing Interpret Logic
|
||||
|
||||
Many Scores delegate to shared `Interpret` implementations. For example, `HelmChartScore` provides a reusable Interpret for any Helm-based deployment. Your Score can wrap it:
|
||||
|
||||
```rust
|
||||
impl<T: Topology + HelmCommand> Score<T> for MyScore {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>> {
|
||||
Box::new(HelmChartInterpret { /* your config */ })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Accessing Topology Capabilities
|
||||
|
||||
Your Interpret accesses infrastructure through Capabilities exposed by the Topology:
|
||||
|
||||
```rust
|
||||
// Via the Topology trait directly
|
||||
let k8s_client = topology.k8s_client().await?;
|
||||
let helm = topology.get_helm_command();
|
||||
|
||||
// Or via Capability traits
|
||||
impl<T: Topology + K8sclient> Interpret<T> for MyInterpret {
|
||||
async fn execute(...) {
|
||||
let client = topology.k8s_client().await?;
|
||||
// use client...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Keep Scores focused** — one Score per concern (deployment, monitoring, networking)
|
||||
- **Use `..Default::default()`** for optional fields so callers only need to specify what they care about
|
||||
- **Return `Outcome`** — use `Outcome::success`, `Outcome::failure`, or `Outcome::success_with_details` to communicate results clearly
|
||||
- **Handle errors gracefully** — return meaningful `InterpretError` messages that help operators debug issues
|
||||
176
docs/guides/writing-a-topology.md
Normal file
176
docs/guides/writing-a-topology.md
Normal file
@@ -0,0 +1,176 @@
|
||||
# Writing a Topology
|
||||
|
||||
A `Topology` models your infrastructure environment and exposes `Capability` traits that Scores use to interact with it. Where a Score declares _what_ you want, a Topology exposes _what_ it can do.
|
||||
|
||||
## The Minimum Implementation
|
||||
|
||||
At minimum, a Topology needs:
|
||||
|
||||
```rust
|
||||
use async_trait::async_trait;
|
||||
use harmony::{
|
||||
topology::{PreparationError, PreparationOutcome, Topology},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MyTopology {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Topology for MyTopology {
|
||||
fn name(&self) -> &str {
|
||||
"MyTopology"
|
||||
}
|
||||
|
||||
async fn ensure_ready(&self) -> Result<PreparationOutcome, PreparationError> {
|
||||
// Verify the infrastructure is accessible and ready
|
||||
Ok(PreparationOutcome::Success { details: "ready".to_string() })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Implementing Capabilities
|
||||
|
||||
Scores express dependencies on Capabilities through trait bounds. For example, if your Topology should support Scores that deploy Helm charts, implement `HelmCommand`:
|
||||
|
||||
```rust
|
||||
use std::process::Command;
|
||||
use harmony::topology::HelmCommand;
|
||||
|
||||
impl HelmCommand for MyTopology {
|
||||
fn get_helm_command(&self) -> Command {
|
||||
let mut cmd = Command::new("helm");
|
||||
if let Some(kubeconfig) = &self.kubeconfig {
|
||||
cmd.arg("--kubeconfig").arg(kubeconfig);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For Scores that need a Kubernetes client, implement `K8sclient`:
|
||||
|
||||
```rust
|
||||
use std::sync::Arc;
|
||||
use harmony_k8s::K8sClient;
|
||||
use harmony::topology::K8sclient;
|
||||
|
||||
#[async_trait]
|
||||
impl K8sclient for MyTopology {
|
||||
async fn k8s_client(&self) -> Result<Arc<K8sClient>, String> {
|
||||
let client = if let Some(kubeconfig) = &self.kubeconfig {
|
||||
K8sClient::from_kubeconfig(kubeconfig).await?
|
||||
} else {
|
||||
K8sClient::try_default().await?
|
||||
};
|
||||
Ok(Arc::new(client))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Loading Topology from Environment
|
||||
|
||||
For flexibility, implement `from_env()` to read configuration from environment variables:
|
||||
|
||||
```rust
|
||||
impl MyTopology {
|
||||
pub fn from_env() -> Self {
|
||||
Self {
|
||||
name: std::env::var("MY_TOPOLOGY_NAME")
|
||||
.unwrap_or_else(|_| "default".to_string()),
|
||||
kubeconfig: std::env::var("KUBECONFIG").ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This pattern lets operators switch between environments without recompiling:
|
||||
|
||||
```bash
|
||||
export KUBECONFIG=/path/to/prod-cluster.kubeconfig
|
||||
cargo run --example my_example
|
||||
```
|
||||
|
||||
## Complete Example: K8sAnywhereTopology
|
||||
|
||||
The `K8sAnywhereTopology` is the most commonly used Topology and handles both local (K3D) and remote Kubernetes clusters:
|
||||
|
||||
```rust
|
||||
pub struct K8sAnywhereTopology {
|
||||
pub k8s_state: Arc<OnceCell<K8sState>>,
|
||||
pub tenant_manager: Arc<OnceCell<TenantManager>>,
|
||||
pub config: Arc<K8sAnywhereConfig>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Topology for K8sAnywhereTopology {
|
||||
fn name(&self) -> &str {
|
||||
"K8sAnywhereTopology"
|
||||
}
|
||||
|
||||
async fn ensure_ready(&self) -> Result<PreparationOutcome, PreparationError> {
|
||||
// 1. If autoinstall is enabled and no cluster exists, provision K3D
|
||||
// 2. Verify kubectl connectivity
|
||||
// 3. Optionally wait for cluster operators to be ready
|
||||
Ok(PreparationOutcome::Success { details: "cluster ready".to_string() })
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Key Patterns
|
||||
|
||||
### Lazy Initialization
|
||||
|
||||
Use `OnceCell` for expensive resources like Kubernetes clients:
|
||||
|
||||
```rust
|
||||
pub struct K8sAnywhereTopology {
|
||||
k8s_state: Arc<OnceCell<K8sState>>,
|
||||
}
|
||||
```
|
||||
|
||||
### Multi-Target Topologies
|
||||
|
||||
For Scores that span multiple clusters (like NATS supercluster), implement `MultiTargetTopology`:
|
||||
|
||||
```rust
|
||||
pub trait MultiTargetTopology: Topology {
|
||||
fn current_target(&self) -> &str;
|
||||
fn set_target(&mut self, target: &str);
|
||||
}
|
||||
```
|
||||
|
||||
### Composing Topologies
|
||||
|
||||
Complex topologies combine multiple infrastructure components:
|
||||
|
||||
```rust
|
||||
pub struct HAClusterTopology {
|
||||
pub router: Arc<dyn Router>,
|
||||
pub load_balancer: Arc<dyn LoadBalancer>,
|
||||
pub firewall: Arc<dyn Firewall>,
|
||||
pub dhcp_server: Arc<dyn DhcpServer>,
|
||||
pub dns_server: Arc<dyn DnsServer>,
|
||||
pub kubeconfig: Option<String>,
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Testing Your Topology
|
||||
|
||||
Test Topologies in isolation by implementing them against mock infrastructure:
|
||||
|
||||
```rust
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_topology_ensure_ready() {
|
||||
let topo = MyTopology::from_env();
|
||||
let result = topo.ensure_ready().await;
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
}
|
||||
```
|
||||
17
docs/use-cases/README.md
Normal file
17
docs/use-cases/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Use Cases
|
||||
|
||||
Real-world scenarios demonstrating Harmony in action.
|
||||
|
||||
## Available Use Cases
|
||||
|
||||
### [PostgreSQL on Local K3D](./postgresql-on-local-k3d.md)
|
||||
|
||||
Deploy a fully functional PostgreSQL cluster on a local K3D cluster in under 10 minutes. The quickest way to see Harmony in action.
|
||||
|
||||
### [OKD on Bare Metal](./okd-on-bare-metal.md)
|
||||
|
||||
A complete walkthrough of bootstrapping a high-availability OKD cluster from physical hardware. Covers inventory discovery, bootstrap, control plane, and worker provisioning.
|
||||
|
||||
---
|
||||
|
||||
_These use cases are community-tested scenarios. For questions or contributions, open an issue on the [Harmony repository](https://git.nationtech.io/NationTech/harmony/issues)._
|
||||
159
docs/use-cases/okd-on-bare-metal.md
Normal file
159
docs/use-cases/okd-on-bare-metal.md
Normal file
@@ -0,0 +1,159 @@
|
||||
# Use Case: OKD on Bare Metal
|
||||
|
||||
Provision a production-grade OKD (OpenShift Kubernetes Distribution) cluster from physical hardware using Harmony. This use case covers the full lifecycle: hardware discovery, bootstrap, control plane, workers, and post-install validation.
|
||||
|
||||
## What you'll have at the end
|
||||
|
||||
A highly-available OKD cluster with:
|
||||
- 3 control plane nodes
|
||||
- 2+ worker nodes
|
||||
- Network bonding configured on nodes and switches
|
||||
- Load balancer routing API and ingress traffic
|
||||
- DNS and DHCP services for the cluster
|
||||
- Post-install health validation
|
||||
|
||||
## Target hardware model
|
||||
|
||||
This setup assumes a typical lab environment:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Network 192.168.x.0/24 (flat, DHCP + PXE capable) │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ cp0 │ │ cp1 │ │ cp2 │ (control) │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ wk0 │ │ wk1 │ ... (workers) │
|
||||
│ └──────────┘ └──────────┘ │
|
||||
│ ┌──────────┐ │
|
||||
│ │ bootstrap│ (temporary, can be repurposed) │
|
||||
│ └──────────┘ │
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ firewall │ │ switch │ (OPNsense + Brocade) │
|
||||
│ └──────────┘ └──────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Required infrastructure
|
||||
|
||||
Harmony models this as an `HAClusterTopology`, which requires these capabilities:
|
||||
|
||||
| Capability | Implementation |
|
||||
|------------|---------------|
|
||||
| **Router** | OPNsense firewall |
|
||||
| **Load Balancer** | OPNsense HAProxy |
|
||||
| **Firewall** | OPNsense |
|
||||
| **DHCP Server** | OPNsense |
|
||||
| **TFTP Server** | OPNsense |
|
||||
| **HTTP Server** | OPNsense |
|
||||
| **DNS Server** | OPNsense |
|
||||
| **Node Exporter** | Prometheus node_exporter on OPNsense |
|
||||
| **Switch Client** | Brocade SNMP |
|
||||
|
||||
See `examples/okd_installation/` for a reference topology implementation.
|
||||
|
||||
## The Provisioning Pipeline
|
||||
|
||||
Harmony orchestrates OKD installation in ordered stages:
|
||||
|
||||
### Stage 1: Inventory Discovery (`OKDSetup01InventoryScore`)
|
||||
|
||||
Harmony boots all nodes via PXE into a CentOS Stream live environment, runs an inventory agent on each, and collects:
|
||||
- MAC addresses and NIC details
|
||||
- IP addresses assigned by DHCP
|
||||
- Hardware profile (CPU, RAM, storage)
|
||||
|
||||
This is the "discovery-first" approach: no pre-configuration required on nodes.
|
||||
|
||||
### Stage 2: Bootstrap Node (`OKDSetup02BootstrapScore`)
|
||||
|
||||
The user selects one discovered node to serve as the bootstrap node. Harmony:
|
||||
- Renders per-MAC iPXE boot configuration with OKD 4.19 SCOS live assets + ignition
|
||||
- Reboots the bootstrap node via SSH
|
||||
- Waits for the bootstrap process to complete (API server becomes available)
|
||||
|
||||
### Stage 3: Control Plane (`OKDSetup03ControlPlaneScore`)
|
||||
|
||||
With bootstrap complete, Harmony provisions the control plane nodes:
|
||||
- Renders per-MAC iPXE for each control plane node
|
||||
- Reboots via SSH and waits for node to join the cluster
|
||||
- Applies network bond configuration via NMState MachineConfig where relevant
|
||||
|
||||
### Stage 4: Network Bonding (`OKDSetupPersistNetworkBondScore`)
|
||||
|
||||
Configures LACP bonds on nodes and corresponding port-channels on the switch stack for high-availability.
|
||||
|
||||
### Stage 5: Worker Nodes (`OKDSetup04WorkersScore`)
|
||||
|
||||
Provisions worker nodes similarly to control plane, joining them to the cluster.
|
||||
|
||||
### Stage 6: Sanity Check (`OKDSetup05SanityCheckScore`)
|
||||
|
||||
Validates:
|
||||
- API server is reachable
|
||||
- Ingress controller is operational
|
||||
- Cluster operators are healthy
|
||||
- SDN (software-defined networking) is functional
|
||||
|
||||
### Stage 7: Installation Report (`OKDSetup06InstallationReportScore`)
|
||||
|
||||
Produces a machine-readable JSON report and human-readable summary of the installation.
|
||||
|
||||
## Network notes
|
||||
|
||||
**During discovery:** Ports must be in access mode (no LACP). DHCP succeeds; iPXE loads CentOS Stream live with Kickstart and starts the inventory endpoint.
|
||||
|
||||
**During provisioning:** After SCOS is on disk and Ignition/MachineConfig can be applied, bonds are set persistently. This avoids the PXE/DHCP recovery race condition that occurs if bonding is configured too early.
|
||||
|
||||
**PXE limitation:** The generic discovery path cannot use bonded networks for PXE boot because the DHCP recovery process conflicts with bond formation.
|
||||
|
||||
## Configuration knobs
|
||||
|
||||
When using `OKDInstallationPipeline`, configure these domains:
|
||||
|
||||
| Parameter | Example | Description |
|
||||
|-----------|---------|-------------|
|
||||
| `public_domain` | `apps.example.com` | Wildcard domain for application ingress |
|
||||
| `internal_domain` | `cluster.local` | Internal cluster DNS domain |
|
||||
|
||||
## Running the example
|
||||
|
||||
See `examples/okd_installation/` for a complete reference. The topology must be configured with your infrastructure details:
|
||||
|
||||
```bash
|
||||
# Configure the example with your hardware/network specifics
|
||||
# See examples/okd_installation/src/topology.rs
|
||||
|
||||
cargo run -p example-okd_installation
|
||||
```
|
||||
|
||||
This example requires:
|
||||
- Physical hardware configured as described above
|
||||
- OPNsense firewall with SSH access
|
||||
- Brocade switch with SNMP access
|
||||
- All nodes connected to the same Layer 2 network
|
||||
|
||||
## Post-install
|
||||
|
||||
After the cluster is bootstrapped, `~/.kube/config` is updated with the cluster credentials. Verify:
|
||||
|
||||
```bash
|
||||
kubectl get nodes
|
||||
kubectl get pods -n openshift-monitoring
|
||||
oc get routes -n openshift-console
|
||||
```
|
||||
|
||||
## Next steps
|
||||
|
||||
- Enable monitoring with `PrometheusAlertScore` or `OpenshiftClusterAlertScore`
|
||||
- Configure TLS certificates with `CertManagerHelmScore`
|
||||
- Add storage with Rook Ceph
|
||||
- Scale workers with `OKDSetup04WorkersScore`
|
||||
|
||||
## Further reading
|
||||
|
||||
- [OKD Installation Module](../../harmony/src/modules/okd/installation.rs) — source of truth for pipeline stages
|
||||
- [HAClusterTopology](../../harmony/src/domain/topology/ha_cluster.rs) — infrastructure capability model
|
||||
- [Scores Catalog](../catalogs/scores.md) — all available Scores including OKD-specific ones
|
||||
115
docs/use-cases/postgresql-on-local-k3d.md
Normal file
115
docs/use-cases/postgresql-on-local-k3d.md
Normal file
@@ -0,0 +1,115 @@
|
||||
# Use Case: PostgreSQL on Local K3D
|
||||
|
||||
Deploy a production-grade PostgreSQL cluster on a local Kubernetes cluster (K3D) using Harmony. This is the fastest way to get started with Harmony and requires no external infrastructure.
|
||||
|
||||
## What you'll have at the end
|
||||
|
||||
A fully operational PostgreSQL cluster with:
|
||||
- 1 primary instance with 1 GiB of storage
|
||||
- CloudNativePG operator managing the cluster lifecycle
|
||||
- Automatic failover support (foundation for high-availability)
|
||||
- Exposed as a Kubernetes Service for easy connection
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Rust 2024 edition
|
||||
- Docker running locally
|
||||
- ~5 minutes
|
||||
|
||||
## The Score
|
||||
|
||||
The entire deployment is expressed in ~20 lines of Rust:
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::postgresql::{PostgreSQLScore, capability::PostgreSQLConfig},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let postgres = PostgreSQLScore {
|
||||
config: PostgreSQLConfig {
|
||||
cluster_name: "harmony-postgres-example".to_string(),
|
||||
namespace: "harmony-postgres-example".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(postgres)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
## What Harmony does
|
||||
|
||||
When you run this, Harmony:
|
||||
|
||||
1. **Connects to K8sAnywhereTopology** — this auto-provisions a K3D cluster if none exists
|
||||
2. **Installs the CloudNativePG operator** — one-time setup that enables PostgreSQL cluster management in Kubernetes
|
||||
3. **Creates a PostgreSQL cluster** — Harmony translates the Score into a `Cluster` CRD and applies it
|
||||
4. **Exposes the database** — creates a Kubernetes Service for the PostgreSQL primary
|
||||
|
||||
## Running it
|
||||
|
||||
```bash
|
||||
cargo run -p example-postgresql
|
||||
```
|
||||
|
||||
## Verifying the deployment
|
||||
|
||||
```bash
|
||||
# Check pods
|
||||
kubectl get pods -n harmony-postgres-example
|
||||
|
||||
# Get the password
|
||||
PASSWORD=$(kubectl get secret -n harmony-postgres-example \
|
||||
harmony-postgres-example-db-user \
|
||||
-o jsonpath='{.data.password}' | base64 -d)
|
||||
|
||||
# Connect via port-forward
|
||||
kubectl port-forward -n harmony-postgres-example svc/harmony-postgres-example-rw 5432:5432
|
||||
psql -h localhost -p 5432 -U postgres -W "$PASSWORD"
|
||||
```
|
||||
|
||||
## Customizing the deployment
|
||||
|
||||
The `PostgreSQLConfig` struct supports:
|
||||
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `cluster_name` | — | Name of the PostgreSQL cluster |
|
||||
| `namespace` | — | Kubernetes namespace to deploy to |
|
||||
| `instances` | `1` | Number of instances |
|
||||
| `storage_size` | `1Gi` | Persistent storage size per instance |
|
||||
|
||||
Example with custom settings:
|
||||
|
||||
```rust
|
||||
let postgres = PostgreSQLScore {
|
||||
config: PostgreSQLConfig {
|
||||
cluster_name: "my-prod-db".to_string(),
|
||||
namespace: "database".to_string(),
|
||||
instances: 3,
|
||||
storage_size: "10Gi".to_string().into(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Extending the pattern
|
||||
|
||||
This pattern extends to any Kubernetes-native workload:
|
||||
|
||||
- Add **monitoring** by including a `Monitoring` feature alongside your Score
|
||||
- Add **TLS certificates** by including a `CertificateScore`
|
||||
- Add **tenant isolation** by wrapping in a `TenantScore`
|
||||
|
||||
See [Scores Catalog](../catalogs/scores.md) for the full list.
|
||||
151
docs/use-cases/rustfs-on-local-k3d.md
Normal file
151
docs/use-cases/rustfs-on-local-k3d.md
Normal file
@@ -0,0 +1,151 @@
|
||||
# Use Case: RustFS (S3-Compatible Store) on Local K3D
|
||||
|
||||
Deploy a RustFS object store on a local Kubernetes cluster (K3D) using Harmony. RustFS is a Rust-based S3-compatible storage server, a modern alternative to MinIO for local development.
|
||||
|
||||
## What you'll have at the end
|
||||
|
||||
A fully operational S3-compatible object store with:
|
||||
- 1 standalone instance with 1 GiB of storage
|
||||
- S3 API endpoint on port 9000
|
||||
- Web console on port 9001
|
||||
- Ingress-based access at `http://rustfs.local`
|
||||
- Default credentials: `rustfsadmin` / `rustfsadmin`
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Rust 2024 edition
|
||||
- Docker running locally
|
||||
- ~5 minutes
|
||||
|
||||
## The Score
|
||||
|
||||
The entire deployment is expressed in ~20 lines of Rust:
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::rustfs::{K8sRustFsScore, RustFsConfig},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let rustfs = K8sRustFsScore {
|
||||
config: RustFsConfig {
|
||||
release_name: "harmony-rustfs".to_string(),
|
||||
namespace: "harmony-rustfs".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(rustfs)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
## What Harmony does
|
||||
|
||||
When you run this, Harmony:
|
||||
|
||||
1. **Connects to K8sAnywhereTopology** — auto-provisions a K3D cluster if none exists
|
||||
2. **Creates a namespace** — `harmony-rustfs` (or your custom namespace)
|
||||
3. **Creates credentials secret** — stores the access/secret keys securely
|
||||
4. **Deploys via Helm** — installs the RustFS chart in standalone mode
|
||||
5. **Configures Ingress** — sets up routing at `rustfs.local`
|
||||
|
||||
## Running it
|
||||
|
||||
```bash
|
||||
cargo run -p example-rustfs
|
||||
```
|
||||
|
||||
## Verifying the deployment
|
||||
|
||||
```bash
|
||||
# Check pods
|
||||
kubectl get pods -n harmony-rustfs
|
||||
|
||||
# Check ingress
|
||||
kubectl get ingress -n harmony-rustfs
|
||||
|
||||
# Access the S3 API
|
||||
# Add rustfs.local to your /etc/hosts
|
||||
echo "127.0.0.1 rustfs.local" | sudo tee -a /etc/hosts
|
||||
|
||||
# Use the AWS CLI or any S3 client
|
||||
AWS_ACCESS_KEY_ID=rustfsadmin \
|
||||
AWS_SECRET_ACCESS_KEY=rustfsadmin \
|
||||
aws s3 ls --endpoint-url http://rustfs.local:9000
|
||||
|
||||
# Or via the web console
|
||||
open http://rustfs.local:9001
|
||||
```
|
||||
|
||||
## Customizing the deployment
|
||||
|
||||
The `RustFsConfig` struct supports:
|
||||
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `release_name` | `rustfs` | Helm release name |
|
||||
| `namespace` | `harmony-rustfs` | Kubernetes namespace |
|
||||
| `storage_size` | `1Gi` | Data storage size |
|
||||
| `mode` | `Standalone` | Deployment mode (standalone only for now) |
|
||||
| `access_key` | `None` | S3 access key (default: `rustfsadmin`) |
|
||||
| `secret_key` | `None` | S3 secret key (default: `rustfsadmin`) |
|
||||
| `ingress_class` | `None` | Ingress class to use (default: `nginx`) |
|
||||
|
||||
Example with custom credentials:
|
||||
|
||||
```rust
|
||||
let rustfs = K8sRustFsScore {
|
||||
config: RustFsConfig {
|
||||
release_name: "my-rustfs".to_string(),
|
||||
namespace: "storage".to_string(),
|
||||
access_key: Some("myaccess".to_string()),
|
||||
secret_key: Some("mysecret".to_string()),
|
||||
ingress_class: Some("traefik".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
The RustFS module follows the same pattern as PostgreSQL:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ K8sRustFsScore (user-facing) │
|
||||
│ └── K8sRustFsInterpret │
|
||||
│ ├── ensure_namespace() │
|
||||
│ ├── ensure_secret() → K8sResourceScore │
|
||||
│ └── HelmChartScore → HelmChartInterpret │
|
||||
│ └── Installs rustfs/rustfs chart │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Future: Unified S3 Capability
|
||||
|
||||
This is the first step toward a unified S3 capability that will work with:
|
||||
- **RustFS** — local development (this example)
|
||||
- **Ceph RGW** — production S3 via Rook/Ceph
|
||||
- **AWS S3** — cloud-native S3
|
||||
|
||||
The pattern will be:
|
||||
|
||||
```rust
|
||||
// Future: unified S3 interface
|
||||
trait S3Store: Send + Sync {
|
||||
async fn deploy_bucket(&self, config: &BucketConfig) -> Result<(), String>;
|
||||
async fn get_endpoint(&self) -> Result<S3Endpoint, String>;
|
||||
}
|
||||
```
|
||||
|
||||
See the [Scores Catalog](../catalogs/scores.md) for related components.
|
||||
129
examples/README.md
Normal file
129
examples/README.md
Normal file
@@ -0,0 +1,129 @@
|
||||
# Examples
|
||||
|
||||
This directory contains runnable examples demonstrating Harmony's capabilities. Each example is a self-contained program that can be run with `cargo run -p example-<name>`.
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Example | Description | Local K3D | Existing Cluster | Hardware Needed |
|
||||
|---------|-------------|:---------:|:----------------:|:---------------:|
|
||||
| `postgresql` | Deploy a PostgreSQL cluster | ✅ | ✅ | — |
|
||||
| `rustfs` | Deploy a RustFS S3-compatible store | ✅ | ✅ | — |
|
||||
| `ntfy` | Deploy ntfy notification server | ✅ | ✅ | — |
|
||||
| `tenant` | Create a multi-tenant namespace | ✅ | ✅ | — |
|
||||
| `cert_manager` | Provision TLS certificates | ✅ | ✅ | — |
|
||||
| `node_health` | Check Kubernetes node health | ✅ | ✅ | — |
|
||||
| `monitoring` | Deploy Prometheus alerting | ✅ | ✅ | — |
|
||||
| `monitoring_with_tenant` | Monitoring + tenant isolation | ✅ | ✅ | — |
|
||||
| `operatorhub_catalog` | Install OperatorHub catalog | ✅ | ✅ | — |
|
||||
| `validate_ceph_cluster_health` | Verify Ceph cluster health | — | ✅ | Rook/Ceph |
|
||||
| `remove_rook_osd` | Remove a Rook OSD | — | ✅ | Rook/Ceph |
|
||||
| `brocade_snmp_server` | Configure Brocade switch SNMP | — | ✅ | Brocade switch |
|
||||
| `opnsense_node_exporter` | Node exporter on OPNsense | — | ✅ | OPNsense firewall |
|
||||
| `okd_pxe` | PXE boot configuration for OKD | — | — | ✅ |
|
||||
| `okd_installation` | Full OKD bare-metal install | — | — | ✅ |
|
||||
| `okd_cluster_alerts` | OKD cluster monitoring alerts | — | ✅ | OKD cluster |
|
||||
| `multisite_postgres` | Multi-site PostgreSQL failover | — | ✅ | Multi-cluster |
|
||||
| `nats` | Deploy NATS messaging | — | ✅ | Multi-cluster |
|
||||
| `nats-supercluster` | NATS supercluster across sites | — | ✅ | Multi-cluster |
|
||||
| `lamp` | LAMP stack deployment | ✅ | ✅ | — |
|
||||
| `openbao` | Deploy OpenBao vault | ✅ | ✅ | — |
|
||||
| `zitadel` | Deploy Zitadel identity provider | ✅ | ✅ | — |
|
||||
| `try_rust_webapp` | Rust webapp with packaging | ✅ | ✅ | Submodule |
|
||||
| `rust` | Rust webapp with full monitoring | ✅ | ✅ | — |
|
||||
| `rhob_application_monitoring` | RHOB monitoring setup | ✅ | ✅ | — |
|
||||
| `sttest` | Full OKD stack test | — | — | ✅ |
|
||||
| `application_monitoring_with_tenant` | App monitoring + tenant | — | ✅ | OKD cluster |
|
||||
| `kube-rs` | Direct kube-rs client usage | ✅ | ✅ | — |
|
||||
| `k8s_drain_node` | Drain a Kubernetes node | ✅ | ✅ | — |
|
||||
| `k8s_write_file_on_node` | Write files to K8s nodes | ✅ | ✅ | — |
|
||||
| `harmony_inventory_builder` | Discover hosts via subnet scan | ✅ | — | — |
|
||||
| `cli` | CLI tool with inventory discovery | ✅ | — | — |
|
||||
| `tui` | Terminal UI demonstration | ✅ | — | — |
|
||||
|
||||
## Status Legend
|
||||
|
||||
| Symbol | Meaning |
|
||||
|--------|---------|
|
||||
| ✅ | Works out-of-the-box |
|
||||
| — | Not applicable or requires specific setup |
|
||||
|
||||
## By Category
|
||||
|
||||
### Data Services
|
||||
- **`postgresql`** — Deploy a PostgreSQL cluster via CloudNativePG
|
||||
- **`multisite_postgres`** — Multi-site PostgreSQL with failover
|
||||
- **`public_postgres`** — Public-facing PostgreSQL (⚠️ uses NationTech DNS)
|
||||
- **`rustfs`** — Deploy a RustFS S3-compatible object store
|
||||
|
||||
### Kubernetes Utilities
|
||||
- **`node_health`** — Check node health in a cluster
|
||||
- **`k8s_drain_node`** — Drain and reboot a node
|
||||
- **`k8s_write_file_on_node`** — Write files to nodes
|
||||
- **`validate_ceph_cluster_health`** — Verify Ceph/Rook cluster health
|
||||
- **`remove_rook_osd`** — Remove an OSD from Rook/Ceph
|
||||
- **`kube-rs`** — Direct Kubernetes client usage demo
|
||||
|
||||
### Monitoring & Alerting
|
||||
- **`monitoring`** — Deploy Prometheus alerting with Discord webhooks
|
||||
- **`monitoring_with_tenant`** — Monitoring with tenant isolation
|
||||
- **`ntfy`** — Deploy ntfy notification server
|
||||
- **`okd_cluster_alerts`** — OKD-specific cluster alerts
|
||||
|
||||
### Application Deployment
|
||||
- **`try_rust_webapp`** — Deploy a Rust webapp with packaging (⚠️ requires `tryrust.org` submodule)
|
||||
- **`rust`** — Rust webapp with full monitoring features
|
||||
- **`rhob_application_monitoring`** — Red Hat Observability Stack monitoring
|
||||
- **`lamp`** — LAMP stack deployment (⚠️ uses NationTech DNS)
|
||||
- **`application_monitoring_with_tenant`** — App monitoring with tenant isolation
|
||||
|
||||
### Infrastructure & Bare Metal
|
||||
- **`okd_installation`** — Full OKD cluster from scratch
|
||||
- **`okd_pxe`** — PXE boot configuration for OKD
|
||||
- **`sttest`** — Full OKD stack test with specific hardware
|
||||
- **`brocade_snmp_server`** — Configure Brocade switch via SNMP
|
||||
- **`opnsense_node_exporter`** — Node exporter on OPNsense firewall
|
||||
|
||||
### Multi-Cluster
|
||||
- **`nats`** — NATS deployment on a cluster
|
||||
- **`nats-supercluster`** — NATS supercluster across multiple sites
|
||||
- **`multisite_postgres`** — PostgreSQL with multi-site failover
|
||||
|
||||
### Identity & Secrets
|
||||
- **`openbao`** — Deploy OpenBao vault (⚠️ uses NationTech DNS)
|
||||
- **`zitadel`** — Deploy Zitadel identity provider (⚠️ uses NationTech DNS)
|
||||
|
||||
### Cluster Services
|
||||
- **`cert_manager`** — Provision TLS certificates
|
||||
- **`tenant`** — Create a multi-tenant namespace
|
||||
- **`operatorhub_catalog`** — Install OperatorHub catalog sources
|
||||
|
||||
### Development & Testing
|
||||
- **`cli`** — CLI tool with inventory discovery
|
||||
- **`tui`** — Terminal UI demonstration
|
||||
- **`harmony_inventory_builder`** — Host discovery via subnet scan
|
||||
|
||||
## Running Examples
|
||||
|
||||
```bash
|
||||
# Build first
|
||||
cargo build --release
|
||||
|
||||
# Run any example
|
||||
cargo run -p example-postgresql
|
||||
cargo run -p example-ntfy
|
||||
cargo run -p example-tenant
|
||||
```
|
||||
|
||||
For examples that need an existing Kubernetes cluster:
|
||||
|
||||
```bash
|
||||
export KUBECONFIG=/path/to/your/kubeconfig
|
||||
export HARMONY_USE_LOCAL_K3D=false
|
||||
export HARMONY_AUTOINSTALL=false
|
||||
|
||||
cargo run -p example-monitoring
|
||||
```
|
||||
|
||||
## Notes on Private Infrastructure
|
||||
|
||||
Some examples use NationTech-hosted infrastructure by default (DNS domains like `*.nationtech.io`, `*.harmony.mcd`). These are not suitable for public use without modification. See the [Getting Started Guide](../docs/guides/getting-started.md) for the recommended public examples.
|
||||
@@ -1,8 +1,8 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::cert_manager::{
|
||||
capability::CertificateManagementConfig, score_cert_management::CertificateManagementScore,
|
||||
score_certificate::CertificateScore, score_issuer::CertificateIssuerScore,
|
||||
capability::CertificateManagementConfig, score_certificate::CertificateScore,
|
||||
score_issuer::CertificateIssuerScore,
|
||||
},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
@@ -10,9 +10,10 @@ publish = false
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
harmony-k8s = { path = "../../harmony-k8s" }
|
||||
cidr.workspace = true
|
||||
tokio.workspace = true
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
url.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use harmony::topology::k8s::{DrainOptions, K8sClient};
|
||||
use harmony_k8s::{DrainOptions, K8sClient};
|
||||
use log::{info, trace};
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -10,9 +10,10 @@ publish = false
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
harmony-k8s = { path = "../../harmony-k8s" }
|
||||
cidr.workspace = true
|
||||
tokio.workspace = true
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
url.workspace = true
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use harmony::topology::k8s::{DrainOptions, K8sClient, NodeFile};
|
||||
use harmony_k8s::{K8sClient, NodeFile};
|
||||
use log::{info, trace};
|
||||
|
||||
#[tokio::main]
|
||||
|
||||
@@ -14,7 +14,6 @@ async fn main() {
|
||||
..Default::default() // Use harmony defaults, they are based on CNPG's default values :
|
||||
// "default" namespace, 1 instance, 1Gi storage
|
||||
},
|
||||
hostname: "postgrestest.sto1.nationtech.io".to_string(),
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
|
||||
@@ -6,7 +6,10 @@ use harmony::{
|
||||
data::{FileContent, FilePath},
|
||||
modules::{
|
||||
inventory::HarmonyDiscoveryStrategy,
|
||||
okd::{installation::OKDInstallationPipeline, ipxe::OKDIpxeScore},
|
||||
okd::{
|
||||
installation::OKDInstallationPipeline, ipxe::OKDIpxeScore,
|
||||
load_balancer::OKDLoadBalancerScore,
|
||||
},
|
||||
},
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
@@ -32,6 +35,7 @@ async fn main() {
|
||||
scores
|
||||
.append(&mut OKDInstallationPipeline::get_all_scores(HarmonyDiscoveryStrategy::MDNS).await);
|
||||
|
||||
scores.push(Box::new(OKDLoadBalancerScore::new(&topology)));
|
||||
harmony_cli::run(inventory, topology, scores, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -5,7 +5,7 @@ use harmony::{
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let openbao = OpenbaoScore {
|
||||
host: String::new(),
|
||||
host: "openbao.sebastien.sto1.nationtech.io".to_string(),
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::{k8s::apps::OperatorHubCatalogSourceScore, postgresql::CloudNativePgOperatorScore},
|
||||
@@ -9,7 +7,7 @@ use harmony::{
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let operatorhub_catalog = OperatorHubCatalogSourceScore::default();
|
||||
let cnpg_operator = CloudNativePgOperatorScore::default();
|
||||
let cnpg_operator = CloudNativePgOperatorScore::default_openshift();
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
|
||||
@@ -1,22 +1,13 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cidr::Ipv4Cidr;
|
||||
use harmony::{
|
||||
executors::ExecutorError,
|
||||
hardware::{HostCategory, Location, PhysicalHost, SwitchGroup},
|
||||
infra::opnsense::OPNSenseManagementInterface,
|
||||
inventory::Inventory,
|
||||
modules::opnsense::node_exporter::NodeExporterScore,
|
||||
topology::{
|
||||
HAClusterTopology, LogicalHost, PreparationError, PreparationOutcome, Topology,
|
||||
UnmanagedRouter, node_exporter::NodeExporter,
|
||||
},
|
||||
topology::{PreparationError, PreparationOutcome, Topology, node_exporter::NodeExporter},
|
||||
};
|
||||
use harmony_macros::{ip, ipv4, mac_address};
|
||||
use harmony_macros::ip;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OpnSenseTopology {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::postgresql::{
|
||||
K8sPostgreSQLScore, PostgreSQLConnectionScore, PublicPostgreSQLScore,
|
||||
capability::PostgreSQLConfig,
|
||||
PostgreSQLConnectionScore, PublicPostgreSQLScore, capability::PostgreSQLConfig,
|
||||
},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
@@ -16,7 +15,6 @@ async fn main() {
|
||||
..Default::default() // Use harmony defaults, they are based on CNPG's default values :
|
||||
// 1 instance, 1Gi storage
|
||||
},
|
||||
hostname: "postgrestest.sto1.nationtech.io".to_string(),
|
||||
};
|
||||
|
||||
let test_connection = PostgreSQLConnectionScore {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::{collections::HashMap, path::PathBuf, sync::Arc};
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
|
||||
13
examples/rustfs/Cargo.toml
Normal file
13
examples/rustfs/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "example-rustfs"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
tokio = { workspace = true }
|
||||
25
examples/rustfs/src/main.rs
Normal file
25
examples/rustfs/src/main.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
modules::rustfs::{K8sRustFsScore, RustFsConfig},
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let rustfs = K8sRustFsScore {
|
||||
config: RustFsConfig {
|
||||
release_name: "harmony-rustfs".to_string(),
|
||||
namespace: "harmony-rustfs".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(rustfs)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -44,6 +44,7 @@ fn build_large_score() -> LoadBalancerScore {
|
||||
],
|
||||
listening_port: SocketAddr::V4(SocketAddrV4::new(ipv4!("192.168.0.0"), 49387)),
|
||||
health_check: Some(HealthCheck::HTTP(
|
||||
Some(1993),
|
||||
"/some_long_ass_path_to_see_how_it_is_displayed_but_it_has_to_be_even_longer"
|
||||
.to_string(),
|
||||
HttpMethod::GET,
|
||||
|
||||
14
examples/zitadel/Cargo.toml
Normal file
14
examples/zitadel/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "example-zitadel"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
20
examples/zitadel/src/main.rs
Normal file
20
examples/zitadel/src/main.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use harmony::{
|
||||
inventory::Inventory, modules::zitadel::ZitadelScore, topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let zitadel = ZitadelScore {
|
||||
host: "sso.sto1.nationtech.io".to_string(),
|
||||
zitadel_version: "v4.12.1".to_string(),
|
||||
};
|
||||
|
||||
harmony_cli::run(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
vec![Box::new(zitadel)],
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
BIN
examples/zitadel/zitadel-9.24.0.tgz
Normal file
BIN
examples/zitadel/zitadel-9.24.0.tgz
Normal file
Binary file not shown.
23
harmony-k8s/Cargo.toml
Normal file
23
harmony-k8s/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "harmony-k8s"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
kube.workspace = true
|
||||
k8s-openapi.workspace = true
|
||||
tokio.workspace = true
|
||||
tokio-retry.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
log.workspace = true
|
||||
similar.workspace = true
|
||||
reqwest.workspace = true
|
||||
url.workspace = true
|
||||
inquire.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions.workspace = true
|
||||
593
harmony-k8s/src/apply.rs
Normal file
593
harmony-k8s/src/apply.rs
Normal file
@@ -0,0 +1,593 @@
|
||||
use kube::{
|
||||
Client, Error, Resource,
|
||||
api::{
|
||||
Api, ApiResource, DynamicObject, GroupVersionKind, Patch, PatchParams, PostParams,
|
||||
ResourceExt,
|
||||
},
|
||||
core::ErrorResponse,
|
||||
discovery::Scope,
|
||||
error::DiscoveryError,
|
||||
};
|
||||
use log::{debug, error, trace, warn};
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use serde_json::Value;
|
||||
use similar::TextDiff;
|
||||
use url::Url;
|
||||
|
||||
use crate::client::K8sClient;
|
||||
use crate::helper;
|
||||
use crate::types::WriteMode;
|
||||
|
||||
/// The field-manager token sent with every server-side apply request.
|
||||
pub const FIELD_MANAGER: &str = "harmony-k8s";
|
||||
|
||||
// ── Private helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/// Serialise any `Serialize` payload to a [`DynamicObject`] via JSON.
|
||||
fn to_dynamic<T: Serialize>(payload: &T) -> Result<DynamicObject, Error> {
|
||||
serde_json::from_value(serde_json::to_value(payload).map_err(Error::SerdeError)?)
|
||||
.map_err(Error::SerdeError)
|
||||
}
|
||||
|
||||
/// Fetch the current resource, display a unified diff against `payload`, and
|
||||
/// return `()`. All output goes to stdout (same behaviour as before).
|
||||
///
|
||||
/// A 404 is treated as "resource would be created" — not an error.
|
||||
async fn show_dry_run<T: Serialize>(
|
||||
api: &Api<DynamicObject>,
|
||||
name: &str,
|
||||
payload: &T,
|
||||
) -> Result<(), Error> {
|
||||
let new_yaml = serde_yaml::to_string(payload)
|
||||
.unwrap_or_else(|_| "Failed to serialize new resource".to_string());
|
||||
|
||||
match api.get(name).await {
|
||||
Ok(current) => {
|
||||
println!("\nDry-run for resource: '{name}'");
|
||||
let mut current_val = serde_yaml::to_value(¤t).unwrap_or(serde_yaml::Value::Null);
|
||||
if let Some(map) = current_val.as_mapping_mut() {
|
||||
map.remove(&serde_yaml::Value::String("status".to_string()));
|
||||
}
|
||||
let current_yaml = serde_yaml::to_string(¤t_val)
|
||||
.unwrap_or_else(|_| "Failed to serialize current resource".to_string());
|
||||
|
||||
if current_yaml == new_yaml {
|
||||
println!("No changes detected.");
|
||||
} else {
|
||||
println!("Changes detected:");
|
||||
let diff = TextDiff::from_lines(¤t_yaml, &new_yaml);
|
||||
for change in diff.iter_all_changes() {
|
||||
let sign = match change.tag() {
|
||||
similar::ChangeTag::Delete => "-",
|
||||
similar::ChangeTag::Insert => "+",
|
||||
similar::ChangeTag::Equal => " ",
|
||||
};
|
||||
print!("{sign}{change}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(Error::Api(ErrorResponse { code: 404, .. })) => {
|
||||
println!("\nDry-run for new resource: '{name}'");
|
||||
println!("Resource does not exist. Would be created:");
|
||||
for line in new_yaml.lines() {
|
||||
println!("+{line}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to fetch resource '{name}' for dry-run: {e}");
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute the real (non-dry-run) apply, respecting [`WriteMode`].
|
||||
async fn do_apply<T: Serialize + std::fmt::Debug>(
|
||||
api: &Api<DynamicObject>,
|
||||
name: &str,
|
||||
payload: &T,
|
||||
patch_params: &PatchParams,
|
||||
write_mode: &WriteMode,
|
||||
) -> Result<DynamicObject, Error> {
|
||||
match write_mode {
|
||||
WriteMode::CreateOrUpdate => {
|
||||
// TODO refactor this arm to perform self.update and if fail with 404 self.create
|
||||
// This will avoid the repetition of the api.patch and api.create calls within this
|
||||
// function body. This makes the code more maintainable
|
||||
match api.patch(name, patch_params, &Patch::Apply(payload)).await {
|
||||
Ok(obj) => Ok(obj),
|
||||
Err(Error::Api(ErrorResponse { code: 404, .. })) => {
|
||||
debug!("Resource '{name}' not found via SSA, falling back to POST");
|
||||
let dyn_obj = to_dynamic(payload)?;
|
||||
api.create(&PostParams::default(), &dyn_obj)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to create '{name}': {e}");
|
||||
e
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to apply '{name}': {e}");
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
WriteMode::Create => {
|
||||
let dyn_obj = to_dynamic(payload)?;
|
||||
api.create(&PostParams::default(), &dyn_obj)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to create '{name}': {e}");
|
||||
e
|
||||
})
|
||||
}
|
||||
WriteMode::Update => match api.patch(name, patch_params, &Patch::Apply(payload)).await {
|
||||
Ok(obj) => Ok(obj),
|
||||
Err(Error::Api(ErrorResponse { code: 404, .. })) => Err(Error::Api(ErrorResponse {
|
||||
code: 404,
|
||||
message: format!("Resource '{name}' not found and WriteMode is UpdateOnly"),
|
||||
reason: "NotFound".to_string(),
|
||||
status: "Failure".to_string(),
|
||||
})),
|
||||
Err(e) => {
|
||||
error!("Failed to update '{name}': {e}");
|
||||
Err(e)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────────────
|
||||
|
||||
impl K8sClient {
|
||||
/// Server-side apply: create if absent, update if present.
|
||||
/// Equivalent to `kubectl apply`.
|
||||
pub async fn apply<K>(&self, resource: &K, namespace: Option<&str>) -> Result<K, Error>
|
||||
where
|
||||
K: Resource + Clone + std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
<K as Resource>::DynamicType: Default,
|
||||
{
|
||||
self.apply_with_strategy(resource, namespace, WriteMode::CreateOrUpdate)
|
||||
.await
|
||||
}
|
||||
|
||||
/// POST only — returns an error if the resource already exists.
|
||||
pub async fn create<K>(&self, resource: &K, namespace: Option<&str>) -> Result<K, Error>
|
||||
where
|
||||
K: Resource + Clone + std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
<K as Resource>::DynamicType: Default,
|
||||
{
|
||||
self.apply_with_strategy(resource, namespace, WriteMode::Create)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Server-side apply only — returns an error if the resource does not exist.
|
||||
pub async fn update<K>(&self, resource: &K, namespace: Option<&str>) -> Result<K, Error>
|
||||
where
|
||||
K: Resource + Clone + std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
<K as Resource>::DynamicType: Default,
|
||||
{
|
||||
self.apply_with_strategy(resource, namespace, WriteMode::Update)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn apply_with_strategy<K>(
|
||||
&self,
|
||||
resource: &K,
|
||||
namespace: Option<&str>,
|
||||
write_mode: WriteMode,
|
||||
) -> Result<K, Error>
|
||||
where
|
||||
K: Resource + Clone + std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
<K as Resource>::DynamicType: Default,
|
||||
{
|
||||
debug!(
|
||||
"apply_with_strategy: {:?} ns={:?}",
|
||||
resource.meta().name,
|
||||
namespace
|
||||
);
|
||||
trace!("{:#}", serde_json::to_value(resource).unwrap_or_default());
|
||||
|
||||
let dyntype = K::DynamicType::default();
|
||||
let gvk = GroupVersionKind {
|
||||
group: K::group(&dyntype).to_string(),
|
||||
version: K::version(&dyntype).to_string(),
|
||||
kind: K::kind(&dyntype).to_string(),
|
||||
};
|
||||
|
||||
let discovery = self.discovery().await?;
|
||||
let (ar, caps) = discovery.resolve_gvk(&gvk).ok_or_else(|| {
|
||||
Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Cannot resolve GVK: {gvk:?}"
|
||||
)))
|
||||
})?;
|
||||
|
||||
let effective_ns = if caps.scope == Scope::Cluster {
|
||||
None
|
||||
} else {
|
||||
namespace.or_else(|| resource.meta().namespace.as_deref())
|
||||
};
|
||||
|
||||
let api: Api<DynamicObject> =
|
||||
get_dynamic_api(ar, caps, self.client.clone(), effective_ns, false);
|
||||
|
||||
let name = resource
|
||||
.meta()
|
||||
.name
|
||||
.as_deref()
|
||||
.expect("Kubernetes resource must have a name");
|
||||
|
||||
if self.dry_run {
|
||||
show_dry_run(&api, name, resource).await?;
|
||||
return Ok(resource.clone());
|
||||
}
|
||||
|
||||
let patch_params = PatchParams::apply(FIELD_MANAGER);
|
||||
do_apply(&api, name, resource, &patch_params, &write_mode)
|
||||
.await
|
||||
.and_then(helper::dyn_to_typed)
|
||||
}
|
||||
|
||||
/// Applies resources in order, one at a time
|
||||
pub async fn apply_many<K>(&self, resources: &[K], ns: Option<&str>) -> Result<Vec<K>, Error>
|
||||
where
|
||||
K: Resource + Clone + std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
<K as Resource>::DynamicType: Default,
|
||||
{
|
||||
let mut result = Vec::new();
|
||||
for r in resources.iter() {
|
||||
let res = self.apply(r, ns).await;
|
||||
if res.is_err() {
|
||||
// NOTE: this may log sensitive data; downgrade to debug if needed.
|
||||
warn!(
|
||||
"Failed to apply k8s resource: {}",
|
||||
serde_json::to_string_pretty(r).map_err(Error::SerdeError)?
|
||||
);
|
||||
}
|
||||
result.push(res?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Apply a [`DynamicObject`] resource using server-side apply.
|
||||
pub async fn apply_dynamic(
|
||||
&self,
|
||||
resource: &DynamicObject,
|
||||
namespace: Option<&str>,
|
||||
force_conflicts: bool,
|
||||
) -> Result<DynamicObject, Error> {
|
||||
trace!("apply_dynamic {resource:#?} ns={namespace:?} force={force_conflicts}");
|
||||
|
||||
let discovery = self.discovery().await?;
|
||||
let type_meta = resource.types.as_ref().ok_or_else(|| {
|
||||
Error::BuildRequest(kube::core::request::Error::Validation(
|
||||
"DynamicObject must have types (apiVersion and kind)".to_string(),
|
||||
))
|
||||
})?;
|
||||
|
||||
let gvk = GroupVersionKind::try_from(type_meta).map_err(|_| {
|
||||
Error::BuildRequest(kube::core::request::Error::Validation(format!(
|
||||
"Invalid GVK in DynamicObject: {type_meta:?}"
|
||||
)))
|
||||
})?;
|
||||
|
||||
let (ar, caps) = discovery.resolve_gvk(&gvk).ok_or_else(|| {
|
||||
Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Cannot resolve GVK: {gvk:?}"
|
||||
)))
|
||||
})?;
|
||||
|
||||
let effective_ns = if caps.scope == Scope::Cluster {
|
||||
None
|
||||
} else {
|
||||
namespace.or_else(|| resource.metadata.namespace.as_deref())
|
||||
};
|
||||
|
||||
let api = get_dynamic_api(ar, caps, self.client.clone(), effective_ns, false);
|
||||
let name = resource.metadata.name.as_deref().ok_or_else(|| {
|
||||
Error::BuildRequest(kube::core::request::Error::Validation(
|
||||
"DynamicObject must have metadata.name".to_string(),
|
||||
))
|
||||
})?;
|
||||
|
||||
debug!(
|
||||
"apply_dynamic kind={:?} name='{name}' ns={effective_ns:?}",
|
||||
resource.types.as_ref().map(|t| &t.kind),
|
||||
);
|
||||
|
||||
// NOTE would be nice to improve cohesion between the dynamic and typed apis and avoid copy
|
||||
// pasting the dry_run and some more logic
|
||||
if self.dry_run {
|
||||
show_dry_run(&api, name, resource).await?;
|
||||
return Ok(resource.clone());
|
||||
}
|
||||
|
||||
let mut patch_params = PatchParams::apply(FIELD_MANAGER);
|
||||
patch_params.force = force_conflicts;
|
||||
|
||||
do_apply(
|
||||
&api,
|
||||
name,
|
||||
resource,
|
||||
&patch_params,
|
||||
&WriteMode::CreateOrUpdate,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn apply_dynamic_many(
|
||||
&self,
|
||||
resources: &[DynamicObject],
|
||||
namespace: Option<&str>,
|
||||
force_conflicts: bool,
|
||||
) -> Result<Vec<DynamicObject>, Error> {
|
||||
let mut result = Vec::new();
|
||||
for r in resources.iter() {
|
||||
result.push(self.apply_dynamic(r, namespace, force_conflicts).await?);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn apply_yaml_many(
|
||||
&self,
|
||||
#[allow(clippy::ptr_arg)] 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> {
|
||||
// NOTE wouldn't it be possible to parse this into a DynamicObject and simply call
|
||||
// apply_dynamic instead of reimplementing api interactions?
|
||||
let obj: DynamicObject =
|
||||
serde_yaml::from_value(yaml.clone()).expect("YAML must deserialise to DynamicObject");
|
||||
let name = obj.metadata.name.as_ref().expect("YAML must have a name");
|
||||
|
||||
let api_version = yaml["apiVersion"].as_str().expect("missing apiVersion");
|
||||
let kind = yaml["kind"].as_str().expect("missing kind");
|
||||
|
||||
let mut it = api_version.splitn(2, '/');
|
||||
let first = it.next().unwrap();
|
||||
let (g, v) = match it.next() {
|
||||
Some(second) => (first, second),
|
||||
None => ("", first),
|
||||
};
|
||||
|
||||
let api_resource = ApiResource::from_gvk(&GroupVersionKind::gvk(g, v, kind));
|
||||
let namespace = ns.unwrap_or_else(|| {
|
||||
obj.metadata
|
||||
.namespace
|
||||
.as_deref()
|
||||
.expect("YAML must have a namespace when ns is not provided")
|
||||
});
|
||||
|
||||
let api: Api<DynamicObject> =
|
||||
Api::namespaced_with(self.client.clone(), namespace, &api_resource);
|
||||
|
||||
println!("Applying '{name}' in namespace '{namespace}'...");
|
||||
let patch_params = PatchParams::apply(FIELD_MANAGER);
|
||||
let result = api.patch(name, &patch_params, &Patch::Apply(&obj)).await?;
|
||||
println!("Successfully applied '{}'.", result.name_any());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Equivalent to `kubectl apply -f <url>`.
|
||||
pub async fn apply_url(&self, url: Url, ns: Option<&str>) -> Result<(), Error> {
|
||||
let patch_params = PatchParams::apply(FIELD_MANAGER);
|
||||
let discovery = self.discovery().await?;
|
||||
|
||||
let yaml = reqwest::get(url)
|
||||
.await
|
||||
.expect("Could not fetch URL")
|
||||
.text()
|
||||
.await
|
||||
.expect("Could not read response body");
|
||||
|
||||
for doc in multidoc_deserialize(&yaml).expect("Failed to parse YAML from URL") {
|
||||
let obj: DynamicObject =
|
||||
serde_yaml::from_value(doc).expect("YAML document is not a valid object");
|
||||
let namespace = obj.metadata.namespace.as_deref().or(ns);
|
||||
let type_meta = obj.types.as_ref().expect("Object is missing TypeMeta");
|
||||
let gvk =
|
||||
GroupVersionKind::try_from(type_meta).expect("Object has invalid GroupVersionKind");
|
||||
let name = obj.name_any();
|
||||
|
||||
if let Some((ar, caps)) = discovery.resolve_gvk(&gvk) {
|
||||
let api = get_dynamic_api(ar, caps, self.client.clone(), namespace, false);
|
||||
trace!(
|
||||
"Applying {}:\n{}",
|
||||
gvk.kind,
|
||||
serde_yaml::to_string(&obj).unwrap_or_default()
|
||||
);
|
||||
let data: Value = serde_json::to_value(&obj).expect("serialisation failed");
|
||||
let _r = api.patch(&name, &patch_params, &Patch::Apply(data)).await?;
|
||||
debug!("Applied {} '{name}'", gvk.kind);
|
||||
} else {
|
||||
warn!("Skipping document with unknown GVK: {gvk:?}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build a dynamic API client from a [`DynamicObject`]'s type metadata.
|
||||
pub(crate) fn get_api_for_dynamic_object(
|
||||
&self,
|
||||
object: &DynamicObject,
|
||||
ns: Option<&str>,
|
||||
) -> Result<Api<DynamicObject>, Error> {
|
||||
let ar = object
|
||||
.types
|
||||
.as_ref()
|
||||
.and_then(|t| {
|
||||
let parts: Vec<&str> = t.api_version.split('/').collect();
|
||||
match parts.as_slice() {
|
||||
[version] => Some(ApiResource::from_gvk(&GroupVersionKind::gvk(
|
||||
"", version, &t.kind,
|
||||
))),
|
||||
[group, version] => Some(ApiResource::from_gvk(&GroupVersionKind::gvk(
|
||||
group, version, &t.kind,
|
||||
))),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
Error::BuildRequest(kube::core::request::Error::Validation(format!(
|
||||
"Invalid apiVersion in DynamicObject: {object:#?}"
|
||||
)))
|
||||
})?;
|
||||
|
||||
Ok(match ns {
|
||||
Some(ns) => Api::namespaced_with(self.client.clone(), ns, &ar),
|
||||
None => Api::default_namespaced_with(self.client.clone(), &ar),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── Free functions ───────────────────────────────────────────────────────────
|
||||
|
||||
pub(crate) fn get_dynamic_api(
|
||||
resource: kube::api::ApiResource,
|
||||
capabilities: kube::discovery::ApiCapabilities,
|
||||
client: Client,
|
||||
ns: Option<&str>,
|
||||
all: bool,
|
||||
) -> Api<DynamicObject> {
|
||||
if capabilities.scope == Scope::Cluster || all {
|
||||
Api::all_with(client, &resource)
|
||||
} else if let Some(namespace) = ns {
|
||||
Api::namespaced_with(client, namespace, &resource)
|
||||
} else {
|
||||
Api::default_namespaced_with(client, &resource)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn multidoc_deserialize(
|
||||
data: &str,
|
||||
) -> Result<Vec<serde_yaml::Value>, serde_yaml::Error> {
|
||||
use serde::Deserialize;
|
||||
let mut docs = vec![];
|
||||
for de in serde_yaml::Deserializer::from_str(data) {
|
||||
docs.push(serde_yaml::Value::deserialize(de)?);
|
||||
}
|
||||
Ok(docs)
|
||||
}
|
||||
|
||||
// ── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_tests {
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use k8s_openapi::api::core::v1::ConfigMap;
|
||||
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
|
||||
use kube::api::{DeleteParams, TypeMeta};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires kubernetes cluster"]
|
||||
async fn apply_creates_new_configmap() {
|
||||
let client = K8sClient::try_default().await.unwrap();
|
||||
let ns = "default";
|
||||
let name = format!(
|
||||
"test-cm-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
);
|
||||
|
||||
let cm = ConfigMap {
|
||||
metadata: ObjectMeta {
|
||||
name: Some(name.clone()),
|
||||
namespace: Some(ns.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
data: Some(BTreeMap::from([("key1".to_string(), "value1".to_string())])),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(client.apply(&cm, Some(ns)).await.is_ok());
|
||||
|
||||
let api: Api<ConfigMap> = Api::namespaced(client.client.clone(), ns);
|
||||
let _ = api.delete(&name, &DeleteParams::default()).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires kubernetes cluster"]
|
||||
async fn apply_is_idempotent() {
|
||||
let client = K8sClient::try_default().await.unwrap();
|
||||
let ns = "default";
|
||||
let name = format!(
|
||||
"test-idem-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
);
|
||||
|
||||
let cm = ConfigMap {
|
||||
metadata: ObjectMeta {
|
||||
name: Some(name.clone()),
|
||||
namespace: Some(ns.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
data: Some(BTreeMap::from([("key".to_string(), "value".to_string())])),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(
|
||||
client.apply(&cm, Some(ns)).await.is_ok(),
|
||||
"first apply failed"
|
||||
);
|
||||
assert!(
|
||||
client.apply(&cm, Some(ns)).await.is_ok(),
|
||||
"second apply failed (not idempotent)"
|
||||
);
|
||||
|
||||
let api: Api<ConfigMap> = Api::namespaced(client.client.clone(), ns);
|
||||
let _ = api.delete(&name, &DeleteParams::default()).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires kubernetes cluster"]
|
||||
async fn apply_dynamic_creates_new_resource() {
|
||||
let client = K8sClient::try_default().await.unwrap();
|
||||
let ns = "default";
|
||||
let name = format!(
|
||||
"test-dyn-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis()
|
||||
);
|
||||
|
||||
let obj = DynamicObject {
|
||||
types: Some(TypeMeta {
|
||||
api_version: "v1".to_string(),
|
||||
kind: "ConfigMap".to_string(),
|
||||
}),
|
||||
metadata: ObjectMeta {
|
||||
name: Some(name.clone()),
|
||||
namespace: Some(ns.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
data: serde_json::json!({}),
|
||||
};
|
||||
|
||||
let result = client.apply_dynamic(&obj, Some(ns), false).await;
|
||||
assert!(result.is_ok(), "apply_dynamic failed: {:?}", result.err());
|
||||
|
||||
let api: Api<ConfigMap> = Api::namespaced(client.client.clone(), ns);
|
||||
let _ = api.delete(&name, &DeleteParams::default()).await;
|
||||
}
|
||||
}
|
||||
@@ -25,9 +25,9 @@
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! ```rust,no_run
|
||||
//! use harmony::topology::k8s::{K8sClient, helper};
|
||||
//! use harmony::topology::KubernetesDistribution;
|
||||
//! ```
|
||||
//! use harmony_k8s::{K8sClient, helper};
|
||||
//! use harmony_k8s::KubernetesDistribution;
|
||||
//!
|
||||
//! async fn write_network_config(client: &K8sClient, node: &str) {
|
||||
//! // Create a bundle with platform-specific RBAC
|
||||
@@ -56,7 +56,7 @@ use kube::{Error, Resource, ResourceExt, api::DynamicObject};
|
||||
use serde::Serialize;
|
||||
use serde_json;
|
||||
|
||||
use crate::domain::topology::k8s::K8sClient;
|
||||
use crate::K8sClient;
|
||||
|
||||
/// A ResourceBundle represents a logical unit of work consisting of multiple
|
||||
/// Kubernetes resources that should be applied or deleted together.
|
||||
99
harmony-k8s/src/client.rs
Normal file
99
harmony-k8s/src/client.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use kube::config::{KubeConfigOptions, Kubeconfig};
|
||||
use kube::{Client, Config, Discovery, Error};
|
||||
use log::error;
|
||||
use serde::Serialize;
|
||||
use tokio::sync::OnceCell;
|
||||
|
||||
use crate::types::KubernetesDistribution;
|
||||
|
||||
// TODO not cool, should use a proper configuration mechanism
|
||||
// cli arg, env var, config file
|
||||
fn read_dry_run_from_env() -> bool {
|
||||
std::env::var("DRY_RUN")
|
||||
.map(|v| v == "true" || v == "1")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct K8sClient {
|
||||
pub(crate) client: Client,
|
||||
/// When `true` no mutation is sent to the API server; diffs are printed
|
||||
/// to stdout instead. Initialised from the `DRY_RUN` environment variable.
|
||||
pub(crate) dry_run: bool,
|
||||
pub(crate) k8s_distribution: Arc<OnceCell<KubernetesDistribution>>,
|
||||
pub(crate) discovery: Arc<OnceCell<Discovery>>,
|
||||
}
|
||||
|
||||
impl Serialize for K8sClient {
|
||||
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
todo!("K8sClient serialization is not meaningful; remove this impl if unused")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for K8sClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_fmt(format_args!(
|
||||
"K8sClient {{ namespace: {}, dry_run: {} }}",
|
||||
self.client.default_namespace(),
|
||||
self.dry_run,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sClient {
|
||||
/// Create a client, reading `DRY_RUN` from the environment.
|
||||
pub fn new(client: Client) -> Self {
|
||||
Self {
|
||||
dry_run: read_dry_run_from_env(),
|
||||
client,
|
||||
k8s_distribution: Arc::new(OnceCell::new()),
|
||||
discovery: Arc::new(OnceCell::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a client that always operates in dry-run mode, regardless of
|
||||
/// the environment variable.
|
||||
pub fn new_dry_run(client: Client) -> Self {
|
||||
Self {
|
||||
dry_run: true,
|
||||
..Self::new(client)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if this client is operating in dry-run mode.
|
||||
pub fn is_dry_run(&self) -> bool {
|
||||
self.dry_run
|
||||
}
|
||||
|
||||
pub async fn try_default() -> Result<Self, Error> {
|
||||
Ok(Self::new(Client::try_default().await?))
|
||||
}
|
||||
|
||||
pub async fn from_kubeconfig(path: &str) -> Option<Self> {
|
||||
Self::from_kubeconfig_with_opts(path, &KubeConfigOptions::default()).await
|
||||
}
|
||||
|
||||
pub async fn from_kubeconfig_with_context(path: &str, context: Option<String>) -> Option<Self> {
|
||||
let mut opts = KubeConfigOptions::default();
|
||||
opts.context = context;
|
||||
Self::from_kubeconfig_with_opts(path, &opts).await
|
||||
}
|
||||
|
||||
pub async fn from_kubeconfig_with_opts(path: &str, opts: &KubeConfigOptions) -> Option<Self> {
|
||||
let k = match Kubeconfig::read_from(path) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
error!("Failed to load kubeconfig from {path}: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(Self::new(
|
||||
Client::try_from(Config::from_custom_kubeconfig(k, opts).await.unwrap()).unwrap(),
|
||||
))
|
||||
}
|
||||
}
|
||||
83
harmony-k8s/src/discovery.rs
Normal file
83
harmony-k8s/src/discovery.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use kube::{Discovery, Error};
|
||||
use log::{debug, error, info, trace, warn};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_retry::{Retry, strategy::ExponentialBackoff};
|
||||
|
||||
use crate::client::K8sClient;
|
||||
use crate::types::KubernetesDistribution;
|
||||
|
||||
impl K8sClient {
|
||||
pub async fn get_apiserver_version(
|
||||
&self,
|
||||
) -> Result<k8s_openapi::apimachinery::pkg::version::Info, Error> {
|
||||
self.client.clone().apiserver_version().await
|
||||
}
|
||||
|
||||
/// Runs (and caches) Kubernetes API discovery with exponential-backoff retries.
|
||||
pub async fn discovery(&self) -> Result<&Discovery, Error> {
|
||||
let retry_strategy = ExponentialBackoff::from_millis(1000)
|
||||
.max_delay(Duration::from_secs(32))
|
||||
.take(6);
|
||||
|
||||
let attempt = Mutex::new(0u32);
|
||||
Retry::spawn(retry_strategy, || async {
|
||||
let mut n = attempt.lock().await;
|
||||
*n += 1;
|
||||
match self
|
||||
.discovery
|
||||
.get_or_try_init(async || {
|
||||
debug!("Running Kubernetes API discovery (attempt {})", *n);
|
||||
let d = Discovery::new(self.client.clone()).run().await?;
|
||||
debug!("Kubernetes API discovery completed");
|
||||
Ok(d)
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(d) => Ok(d),
|
||||
Err(e) => {
|
||||
warn!("Kubernetes API discovery failed (attempt {}): {}", *n, e);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Kubernetes API discovery failed after all retries: {}", e);
|
||||
e
|
||||
})
|
||||
}
|
||||
|
||||
/// Detect which Kubernetes distribution is running. Result is cached for
|
||||
/// the lifetime of the client.
|
||||
pub async fn get_k8s_distribution(&self) -> Result<KubernetesDistribution, Error> {
|
||||
self.k8s_distribution
|
||||
.get_or_try_init(async || {
|
||||
debug!("Detecting Kubernetes distribution");
|
||||
let api_groups = self.client.list_api_groups().await?;
|
||||
trace!("list_api_groups: {:?}", api_groups);
|
||||
|
||||
let version = self.get_apiserver_version().await?;
|
||||
|
||||
if api_groups
|
||||
.groups
|
||||
.iter()
|
||||
.any(|g| g.name == "project.openshift.io")
|
||||
{
|
||||
info!("Detected distribution: OpenshiftFamily");
|
||||
return Ok(KubernetesDistribution::OpenshiftFamily);
|
||||
}
|
||||
|
||||
if version.git_version.contains("k3s") {
|
||||
info!("Detected distribution: K3sFamily");
|
||||
return Ok(KubernetesDistribution::K3sFamily);
|
||||
}
|
||||
|
||||
info!("Distribution not identified, using Default");
|
||||
Ok(KubernetesDistribution::Default)
|
||||
})
|
||||
.await
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::topology::KubernetesDistribution;
|
||||
use crate::KubernetesDistribution;
|
||||
|
||||
use super::bundle::ResourceBundle;
|
||||
use super::config::PRIVILEGED_POD_IMAGE;
|
||||
@@ -133,9 +133,9 @@ pub fn host_root_volume() -> (Volume, VolumeMount) {
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// # use harmony::topology::k8s::helper::{build_privileged_bundle, PrivilegedPodConfig};
|
||||
/// # use harmony::topology::KubernetesDistribution;
|
||||
/// ```
|
||||
/// use harmony_k8s::helper::{build_privileged_bundle, PrivilegedPodConfig};
|
||||
/// use harmony_k8s::KubernetesDistribution;
|
||||
/// let bundle = build_privileged_bundle(
|
||||
/// PrivilegedPodConfig {
|
||||
/// name: "network-setup".to_string(),
|
||||
13
harmony-k8s/src/lib.rs
Normal file
13
harmony-k8s/src/lib.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
pub mod apply;
|
||||
pub mod bundle;
|
||||
pub mod client;
|
||||
pub mod config;
|
||||
pub mod discovery;
|
||||
pub mod helper;
|
||||
pub mod node;
|
||||
pub mod pod;
|
||||
pub mod resources;
|
||||
pub mod types;
|
||||
|
||||
pub use client::K8sClient;
|
||||
pub use types::{DrainOptions, KubernetesDistribution, NodeFile, ScopeResolver, WriteMode};
|
||||
3
harmony-k8s/src/main.rs
Normal file
3
harmony-k8s/src/main.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
722
harmony-k8s/src/node.rs
Normal file
722
harmony-k8s/src/node.rs
Normal file
@@ -0,0 +1,722 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use k8s_openapi::api::core::v1::{
|
||||
ConfigMap, ConfigMapVolumeSource, Node, Pod, Volume, VolumeMount,
|
||||
};
|
||||
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
|
||||
use kube::{
|
||||
Error,
|
||||
api::{Api, DeleteParams, EvictParams, ListParams, PostParams},
|
||||
core::ErrorResponse,
|
||||
error::DiscoveryError,
|
||||
};
|
||||
use log::{debug, error, info, warn};
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::client::K8sClient;
|
||||
use crate::helper::{self, PrivilegedPodConfig};
|
||||
use crate::types::{DrainOptions, NodeFile};
|
||||
|
||||
impl K8sClient {
|
||||
pub async fn cordon_node(&self, node_name: &str) -> Result<(), Error> {
|
||||
Api::<Node>::all(self.client.clone())
|
||||
.cordon(node_name)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn uncordon_node(&self, node_name: &str) -> Result<(), Error> {
|
||||
Api::<Node>::all(self.client.clone())
|
||||
.uncordon(node_name)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn wait_for_node_ready(&self, node_name: &str) -> Result<(), Error> {
|
||||
self.wait_for_node_ready_with_timeout(node_name, Duration::from_secs(600))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn wait_for_node_ready_with_timeout(
|
||||
&self,
|
||||
node_name: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<(), Error> {
|
||||
let api: Api<Node> = Api::all(self.client.clone());
|
||||
let start = tokio::time::Instant::now();
|
||||
let poll = Duration::from_secs(5);
|
||||
loop {
|
||||
if start.elapsed() > timeout {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Node '{node_name}' did not become Ready within {timeout:?}"
|
||||
))));
|
||||
}
|
||||
match api.get(node_name).await {
|
||||
Ok(node) => {
|
||||
if node
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.conditions.as_ref())
|
||||
.map(|conds| {
|
||||
conds
|
||||
.iter()
|
||||
.any(|c| c.type_ == "Ready" && c.status == "True")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
{
|
||||
debug!("Node '{node_name}' is Ready");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(e) => debug!("Error polling node '{node_name}': {e}"),
|
||||
}
|
||||
sleep(poll).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_node_not_ready(
|
||||
&self,
|
||||
node_name: &str,
|
||||
timeout: Duration,
|
||||
) -> Result<(), Error> {
|
||||
let api: Api<Node> = Api::all(self.client.clone());
|
||||
let start = tokio::time::Instant::now();
|
||||
let poll = Duration::from_secs(5);
|
||||
loop {
|
||||
if start.elapsed() > timeout {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Node '{node_name}' did not become NotReady within {timeout:?}"
|
||||
))));
|
||||
}
|
||||
match api.get(node_name).await {
|
||||
Ok(node) => {
|
||||
let is_ready = node
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.conditions.as_ref())
|
||||
.map(|conds| {
|
||||
conds
|
||||
.iter()
|
||||
.any(|c| c.type_ == "Ready" && c.status == "True")
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !is_ready {
|
||||
debug!("Node '{node_name}' is NotReady");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(e) => debug!("Error polling node '{node_name}': {e}"),
|
||||
}
|
||||
sleep(poll).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn list_pods_on_node(&self, node_name: &str) -> Result<Vec<Pod>, Error> {
|
||||
let api: Api<Pod> = Api::all(self.client.clone());
|
||||
Ok(api
|
||||
.list(&ListParams::default().fields(&format!("spec.nodeName={node_name}")))
|
||||
.await?
|
||||
.items)
|
||||
}
|
||||
|
||||
fn is_mirror_pod(pod: &Pod) -> bool {
|
||||
pod.metadata
|
||||
.annotations
|
||||
.as_ref()
|
||||
.map(|a| a.contains_key("kubernetes.io/config.mirror"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn is_daemonset_pod(pod: &Pod) -> bool {
|
||||
pod.metadata
|
||||
.owner_references
|
||||
.as_ref()
|
||||
.map(|refs| refs.iter().any(|r| r.kind == "DaemonSet"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn has_emptydir_volume(pod: &Pod) -> bool {
|
||||
pod.spec
|
||||
.as_ref()
|
||||
.and_then(|s| s.volumes.as_ref())
|
||||
.map(|vols| vols.iter().any(|v| v.empty_dir.is_some()))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn is_completed_pod(pod: &Pod) -> bool {
|
||||
pod.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.phase.as_deref())
|
||||
.map(|phase| phase == "Succeeded" || phase == "Failed")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn classify_pods_for_drain(
|
||||
pods: &[Pod],
|
||||
options: &DrainOptions,
|
||||
) -> Result<(Vec<Pod>, Vec<String>), String> {
|
||||
let mut evictable = Vec::new();
|
||||
let mut skipped = Vec::new();
|
||||
let mut blocking = Vec::new();
|
||||
|
||||
for pod in pods {
|
||||
let name = pod.metadata.name.as_deref().unwrap_or("<unknown>");
|
||||
let ns = pod.metadata.namespace.as_deref().unwrap_or("<unknown>");
|
||||
let qualified = format!("{ns}/{name}");
|
||||
|
||||
if Self::is_mirror_pod(pod) {
|
||||
skipped.push(format!("{qualified} (mirror pod)"));
|
||||
continue;
|
||||
}
|
||||
if Self::is_completed_pod(pod) {
|
||||
skipped.push(format!("{qualified} (completed)"));
|
||||
continue;
|
||||
}
|
||||
if Self::is_daemonset_pod(pod) {
|
||||
if options.ignore_daemonsets {
|
||||
skipped.push(format!("{qualified} (DaemonSet-managed)"));
|
||||
} else {
|
||||
blocking.push(format!(
|
||||
"{qualified} is managed by a DaemonSet (set ignore_daemonsets to skip)"
|
||||
));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if Self::has_emptydir_volume(pod) && !options.delete_emptydir_data {
|
||||
blocking.push(format!(
|
||||
"{qualified} uses emptyDir volumes (set delete_emptydir_data to allow eviction)"
|
||||
));
|
||||
continue;
|
||||
}
|
||||
evictable.push(pod.clone());
|
||||
}
|
||||
|
||||
if !blocking.is_empty() {
|
||||
return Err(format!(
|
||||
"Cannot drain node — the following pods block eviction:\n - {}",
|
||||
blocking.join("\n - ")
|
||||
));
|
||||
}
|
||||
Ok((evictable, skipped))
|
||||
}
|
||||
|
||||
async fn evict_pod(&self, pod: &Pod) -> Result<(), Error> {
|
||||
let name = pod.metadata.name.as_deref().unwrap_or_default();
|
||||
let ns = pod.metadata.namespace.as_deref().unwrap_or_default();
|
||||
debug!("Evicting pod {ns}/{name}");
|
||||
Api::<Pod>::namespaced(self.client.clone(), ns)
|
||||
.evict(name, &EvictParams::default())
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
/// Drains a node: cordon → classify → evict & wait.
|
||||
pub async fn drain_node(&self, node_name: &str, options: &DrainOptions) -> Result<(), Error> {
|
||||
debug!("Cordoning '{node_name}'");
|
||||
self.cordon_node(node_name).await?;
|
||||
|
||||
let pods = self.list_pods_on_node(node_name).await?;
|
||||
debug!("Found {} pod(s) on '{node_name}'", pods.len());
|
||||
|
||||
let (evictable, skipped) =
|
||||
Self::classify_pods_for_drain(&pods, options).map_err(|msg| {
|
||||
error!("{msg}");
|
||||
Error::Discovery(DiscoveryError::MissingResource(msg))
|
||||
})?;
|
||||
|
||||
for s in &skipped {
|
||||
info!("Skipping pod: {s}");
|
||||
}
|
||||
if evictable.is_empty() {
|
||||
info!("No pods to evict on '{node_name}'");
|
||||
return Ok(());
|
||||
}
|
||||
info!("Evicting {} pod(s) from '{node_name}'", evictable.len());
|
||||
|
||||
let mut start = tokio::time::Instant::now();
|
||||
let poll = Duration::from_secs(5);
|
||||
let mut pending = evictable;
|
||||
|
||||
loop {
|
||||
for pod in &pending {
|
||||
match self.evict_pod(pod).await {
|
||||
Ok(()) => {}
|
||||
Err(Error::Api(ErrorResponse { code: 404, .. })) => {}
|
||||
Err(Error::Api(ErrorResponse { code: 429, .. })) => {
|
||||
warn!(
|
||||
"PDB blocked eviction of {}/{}; will retry",
|
||||
pod.metadata.namespace.as_deref().unwrap_or(""),
|
||||
pod.metadata.name.as_deref().unwrap_or("")
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
error!(
|
||||
"Failed to evict {}/{}: {e}",
|
||||
pod.metadata.namespace.as_deref().unwrap_or(""),
|
||||
pod.metadata.name.as_deref().unwrap_or("")
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sleep(poll).await;
|
||||
|
||||
let mut still_present = Vec::new();
|
||||
for pod in pending {
|
||||
let ns = pod.metadata.namespace.as_deref().unwrap_or_default();
|
||||
let name = pod.metadata.name.as_deref().unwrap_or_default();
|
||||
match self.get_pod(name, Some(ns)).await? {
|
||||
Some(_) => still_present.push(pod),
|
||||
None => debug!("Pod {ns}/{name} evicted"),
|
||||
}
|
||||
}
|
||||
pending = still_present;
|
||||
|
||||
if pending.is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
if start.elapsed() > options.timeout {
|
||||
match helper::prompt_drain_timeout_action(
|
||||
node_name,
|
||||
pending.len(),
|
||||
options.timeout,
|
||||
)? {
|
||||
helper::DrainTimeoutAction::Accept => break,
|
||||
helper::DrainTimeoutAction::Retry => {
|
||||
start = tokio::time::Instant::now();
|
||||
continue;
|
||||
}
|
||||
helper::DrainTimeoutAction::Abort => {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Drain aborted. {} pod(s) remaining on '{node_name}'",
|
||||
pending.len()
|
||||
))));
|
||||
}
|
||||
}
|
||||
}
|
||||
debug!("Waiting for {} pod(s) on '{node_name}'", pending.len());
|
||||
}
|
||||
|
||||
debug!("'{node_name}' drained successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Safely reboots a node: drain → reboot → wait for Ready → uncordon.
|
||||
pub async fn reboot_node(
|
||||
&self,
|
||||
node_name: &str,
|
||||
drain_options: &DrainOptions,
|
||||
timeout: Duration,
|
||||
) -> Result<(), Error> {
|
||||
info!("Starting reboot for '{node_name}'");
|
||||
let node_api: Api<Node> = Api::all(self.client.clone());
|
||||
|
||||
let boot_id_before = node_api
|
||||
.get(node_name)
|
||||
.await?
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.node_info.as_ref())
|
||||
.map(|ni| ni.boot_id.clone())
|
||||
.ok_or_else(|| {
|
||||
Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Node '{node_name}' has no boot_id in status"
|
||||
)))
|
||||
})?;
|
||||
|
||||
info!("Draining '{node_name}'");
|
||||
self.drain_node(node_name, drain_options).await?;
|
||||
|
||||
let start = tokio::time::Instant::now();
|
||||
|
||||
info!("Scheduling reboot for '{node_name}'");
|
||||
let reboot_cmd =
|
||||
"echo rebooting ; nohup bash -c 'sleep 5 && nsenter -t 1 -m -- systemctl reboot'";
|
||||
match self
|
||||
.run_privileged_command_on_node(node_name, reboot_cmd)
|
||||
.await
|
||||
{
|
||||
Ok(_) => debug!("Reboot command dispatched"),
|
||||
Err(e) => debug!("Reboot command error (expected if node began shutdown): {e}"),
|
||||
}
|
||||
|
||||
info!("Waiting for '{node_name}' to begin shutdown");
|
||||
self.wait_for_node_not_ready(node_name, timeout.saturating_sub(start.elapsed()))
|
||||
.await?;
|
||||
|
||||
if start.elapsed() > timeout {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Timeout during reboot of '{node_name}' (shutdown phase)"
|
||||
))));
|
||||
}
|
||||
|
||||
info!("Waiting for '{node_name}' to come back online");
|
||||
self.wait_for_node_ready_with_timeout(node_name, timeout.saturating_sub(start.elapsed()))
|
||||
.await?;
|
||||
|
||||
if start.elapsed() > timeout {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Timeout during reboot of '{node_name}' (ready phase)"
|
||||
))));
|
||||
}
|
||||
|
||||
let boot_id_after = node_api
|
||||
.get(node_name)
|
||||
.await?
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.node_info.as_ref())
|
||||
.map(|ni| ni.boot_id.clone())
|
||||
.ok_or_else(|| {
|
||||
Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Node '{node_name}' has no boot_id after reboot"
|
||||
)))
|
||||
})?;
|
||||
|
||||
if boot_id_before == boot_id_after {
|
||||
return Err(Error::Discovery(DiscoveryError::MissingResource(format!(
|
||||
"Node '{node_name}' did not actually reboot (boot_id unchanged: {boot_id_before})"
|
||||
))));
|
||||
}
|
||||
|
||||
info!("'{node_name}' rebooted ({boot_id_before} → {boot_id_after})");
|
||||
self.uncordon_node(node_name).await?;
|
||||
info!("'{node_name}' reboot complete ({:?})", start.elapsed());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a set of files to a node's filesystem via a privileged ephemeral pod.
|
||||
pub async fn write_files_to_node(
|
||||
&self,
|
||||
node_name: &str,
|
||||
files: &[NodeFile],
|
||||
) -> Result<String, Error> {
|
||||
let ns = self.client.default_namespace();
|
||||
let suffix = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
let name = format!("harmony-k8s-writer-{suffix}");
|
||||
|
||||
debug!("Writing {} file(s) to '{node_name}'", files.len());
|
||||
|
||||
let mut data = BTreeMap::new();
|
||||
let mut script = String::from("set -e\n");
|
||||
for (i, file) in files.iter().enumerate() {
|
||||
let key = format!("f{i}");
|
||||
data.insert(key.clone(), file.content.clone());
|
||||
script.push_str(&format!("mkdir -p \"$(dirname \"/host{}\")\"\n", file.path));
|
||||
script.push_str(&format!("cp \"/payload/{key}\" \"/host{}\"\n", file.path));
|
||||
script.push_str(&format!("chmod {:o} \"/host{}\"\n", file.mode, file.path));
|
||||
}
|
||||
|
||||
let cm = ConfigMap {
|
||||
metadata: ObjectMeta {
|
||||
name: Some(name.clone()),
|
||||
namespace: Some(ns.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
data: Some(data),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let cm_api: Api<ConfigMap> = Api::namespaced(self.client.clone(), ns);
|
||||
cm_api.create(&PostParams::default(), &cm).await?;
|
||||
debug!("Created ConfigMap '{name}'");
|
||||
|
||||
let (host_vol, host_mount) = helper::host_root_volume();
|
||||
let payload_vol = Volume {
|
||||
name: "payload".to_string(),
|
||||
config_map: Some(ConfigMapVolumeSource {
|
||||
name: name.clone(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let payload_mount = VolumeMount {
|
||||
name: "payload".to_string(),
|
||||
mount_path: "/payload".to_string(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let bundle = helper::build_privileged_bundle(
|
||||
PrivilegedPodConfig {
|
||||
name: name.clone(),
|
||||
namespace: ns.to_string(),
|
||||
node_name: node_name.to_string(),
|
||||
container_name: "writer".to_string(),
|
||||
command: vec!["/bin/bash".to_string(), "-c".to_string(), script],
|
||||
volumes: vec![payload_vol, host_vol],
|
||||
volume_mounts: vec![payload_mount, host_mount],
|
||||
host_pid: false,
|
||||
host_network: false,
|
||||
},
|
||||
&self.get_k8s_distribution().await?,
|
||||
);
|
||||
|
||||
bundle.apply(self).await?;
|
||||
debug!("Created privileged pod bundle '{name}'");
|
||||
|
||||
let result = self.wait_for_pod_completion(&name, ns).await;
|
||||
|
||||
debug!("Cleaning up '{name}'");
|
||||
let _ = bundle.delete(self).await;
|
||||
let _ = cm_api.delete(&name, &DeleteParams::default()).await;
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Run a privileged command on a node via an ephemeral pod.
|
||||
pub async fn run_privileged_command_on_node(
|
||||
&self,
|
||||
node_name: &str,
|
||||
command: &str,
|
||||
) -> Result<String, Error> {
|
||||
let namespace = self.client.default_namespace();
|
||||
let suffix = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis();
|
||||
let name = format!("harmony-k8s-cmd-{suffix}");
|
||||
|
||||
debug!("Running privileged command on '{node_name}': {command}");
|
||||
|
||||
let (host_vol, host_mount) = helper::host_root_volume();
|
||||
let bundle = helper::build_privileged_bundle(
|
||||
PrivilegedPodConfig {
|
||||
name: name.clone(),
|
||||
namespace: namespace.to_string(),
|
||||
node_name: node_name.to_string(),
|
||||
container_name: "runner".to_string(),
|
||||
command: vec![
|
||||
"/bin/bash".to_string(),
|
||||
"-c".to_string(),
|
||||
command.to_string(),
|
||||
],
|
||||
volumes: vec![host_vol],
|
||||
volume_mounts: vec![host_mount],
|
||||
host_pid: true,
|
||||
host_network: true,
|
||||
},
|
||||
&self.get_k8s_distribution().await?,
|
||||
);
|
||||
|
||||
bundle.apply(self).await?;
|
||||
debug!("Privileged pod '{name}' created");
|
||||
|
||||
let result = self.wait_for_pod_completion(&name, namespace).await;
|
||||
|
||||
debug!("Cleaning up '{name}'");
|
||||
let _ = bundle.delete(self).await;
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use k8s_openapi::api::core::v1::{EmptyDirVolumeSource, PodSpec, PodStatus, Volume};
|
||||
use k8s_openapi::apimachinery::pkg::apis::meta::v1::{ObjectMeta, OwnerReference};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn base_pod(name: &str, ns: &str) -> Pod {
|
||||
Pod {
|
||||
metadata: ObjectMeta {
|
||||
name: Some(name.to_string()),
|
||||
namespace: Some(ns.to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
spec: Some(PodSpec::default()),
|
||||
status: Some(PodStatus {
|
||||
phase: Some("Running".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn mirror_pod(name: &str, ns: &str) -> Pod {
|
||||
let mut pod = base_pod(name, ns);
|
||||
pod.metadata.annotations = Some(std::collections::BTreeMap::from([(
|
||||
"kubernetes.io/config.mirror".to_string(),
|
||||
"abc123".to_string(),
|
||||
)]));
|
||||
pod
|
||||
}
|
||||
|
||||
fn daemonset_pod(name: &str, ns: &str) -> Pod {
|
||||
let mut pod = base_pod(name, ns);
|
||||
pod.metadata.owner_references = Some(vec![OwnerReference {
|
||||
api_version: "apps/v1".to_string(),
|
||||
kind: "DaemonSet".to_string(),
|
||||
name: "some-ds".to_string(),
|
||||
uid: "uid-ds".to_string(),
|
||||
..Default::default()
|
||||
}]);
|
||||
pod
|
||||
}
|
||||
|
||||
fn emptydir_pod(name: &str, ns: &str) -> Pod {
|
||||
let mut pod = base_pod(name, ns);
|
||||
pod.spec = Some(PodSpec {
|
||||
volumes: Some(vec![Volume {
|
||||
name: "scratch".to_string(),
|
||||
empty_dir: Some(EmptyDirVolumeSource::default()),
|
||||
..Default::default()
|
||||
}]),
|
||||
..Default::default()
|
||||
});
|
||||
pod
|
||||
}
|
||||
|
||||
fn completed_pod(name: &str, ns: &str, phase: &str) -> Pod {
|
||||
let mut pod = base_pod(name, ns);
|
||||
pod.status = Some(PodStatus {
|
||||
phase: Some(phase.to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
pod
|
||||
}
|
||||
|
||||
fn default_opts() -> DrainOptions {
|
||||
DrainOptions::default()
|
||||
}
|
||||
|
||||
// All test bodies are identical to the original — only the module path changed.
|
||||
|
||||
#[test]
|
||||
fn empty_pod_list_returns_empty_vecs() {
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&[], &default_opts()).unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normal_pod_is_evictable() {
|
||||
let pods = vec![base_pod("web", "default")];
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &default_opts()).unwrap();
|
||||
assert_eq!(e.len(), 1);
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_pod_is_skipped() {
|
||||
let pods = vec![mirror_pod("kube-apiserver", "kube-system")];
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &default_opts()).unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert!(s[0].contains("mirror pod"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_pods_are_skipped() {
|
||||
for phase in ["Succeeded", "Failed"] {
|
||||
let pods = vec![completed_pod("job", "batch", phase)];
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &default_opts()).unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert!(s[0].contains("completed"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemonset_skipped_when_ignored() {
|
||||
let pods = vec![daemonset_pod("fluentd", "logging")];
|
||||
let opts = DrainOptions {
|
||||
ignore_daemonsets: true,
|
||||
..default_opts()
|
||||
};
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &opts).unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert!(s[0].contains("DaemonSet-managed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daemonset_blocks_when_not_ignored() {
|
||||
let pods = vec![daemonset_pod("fluentd", "logging")];
|
||||
let opts = DrainOptions {
|
||||
ignore_daemonsets: false,
|
||||
..default_opts()
|
||||
};
|
||||
let err = K8sClient::classify_pods_for_drain(&pods, &opts).unwrap_err();
|
||||
assert!(err.contains("DaemonSet") && err.contains("logging/fluentd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emptydir_blocks_without_flag() {
|
||||
let pods = vec![emptydir_pod("cache", "default")];
|
||||
let opts = DrainOptions {
|
||||
delete_emptydir_data: false,
|
||||
..default_opts()
|
||||
};
|
||||
let err = K8sClient::classify_pods_for_drain(&pods, &opts).unwrap_err();
|
||||
assert!(err.contains("emptyDir") && err.contains("default/cache"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emptydir_evictable_with_flag() {
|
||||
let pods = vec![emptydir_pod("cache", "default")];
|
||||
let opts = DrainOptions {
|
||||
delete_emptydir_data: true,
|
||||
..default_opts()
|
||||
};
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &opts).unwrap();
|
||||
assert_eq!(e.len(), 1);
|
||||
assert!(s.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_blocking_all_reported() {
|
||||
let pods = vec![daemonset_pod("ds", "ns1"), emptydir_pod("ed", "ns2")];
|
||||
let opts = DrainOptions {
|
||||
ignore_daemonsets: false,
|
||||
delete_emptydir_data: false,
|
||||
..default_opts()
|
||||
};
|
||||
let err = K8sClient::classify_pods_for_drain(&pods, &opts).unwrap_err();
|
||||
assert!(err.contains("ns1/ds") && err.contains("ns2/ed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_pods_classified_correctly() {
|
||||
let pods = vec![
|
||||
base_pod("web", "default"),
|
||||
mirror_pod("kube-apiserver", "kube-system"),
|
||||
daemonset_pod("fluentd", "logging"),
|
||||
completed_pod("job", "batch", "Succeeded"),
|
||||
base_pod("api", "default"),
|
||||
];
|
||||
let (e, s) = K8sClient::classify_pods_for_drain(&pods, &default_opts()).unwrap();
|
||||
let names: Vec<&str> = e
|
||||
.iter()
|
||||
.map(|p| p.metadata.name.as_deref().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["web", "api"]);
|
||||
assert_eq!(s.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_checked_before_completed() {
|
||||
let mut pod = mirror_pod("static-etcd", "kube-system");
|
||||
pod.status = Some(PodStatus {
|
||||
phase: Some("Succeeded".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
let (_, s) = K8sClient::classify_pods_for_drain(&[pod], &default_opts()).unwrap();
|
||||
assert!(s[0].contains("mirror pod"), "got: {}", s[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completed_checked_before_daemonset() {
|
||||
let mut pod = daemonset_pod("collector", "monitoring");
|
||||
pod.status = Some(PodStatus {
|
||||
phase: Some("Failed".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
let (_, s) = K8sClient::classify_pods_for_drain(&[pod], &default_opts()).unwrap();
|
||||
assert!(s[0].contains("completed"), "got: {}", s[0]);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user