Compare commits
211 Commits
2950235d23
...
dev/postgr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0b8525fe05 | ||
| 6bf10b093c | |||
| 3eecc2f590 | |||
| 3959c07261 | |||
| e50c01c0b3 | |||
| 286460d59e | |||
| 4baa3ae707 | |||
| 82119076cf | |||
| f2a350fae6 | |||
| 197770a603 | |||
| ab69a2c264 | |||
| e857efa92f | |||
| 2ff3f4afa9 | |||
| 2f6a11ead7 | |||
| 7de9860dcf | |||
| 6e884cff3a | |||
| c74c51090a | |||
| 8ae0d6b548 | |||
| ee02906ce9 | |||
| 284cc6afd7 | |||
| 9bf6aac82e | |||
| 460c8b59e1 | |||
| 8e857bc72a | |||
| e8d55d27e4 | |||
| fea7e9ddb9 | |||
| 7ec89cdac5 | |||
| 55143dcad4 | |||
| 17ad92402d | |||
| 29e74a2712 | |||
| e16f8fa82e | |||
| c21f3084dc | |||
| 2c706225a1 | |||
| acfb93f1a2 | |||
| f437c40428 | |||
| e06548ac44 | |||
| 155e9bac28 | |||
| 7bebc58615 | |||
| 246d6718c3 | |||
| d776042e20 | |||
| 86c681be70 | |||
| b94dd1e595 | |||
| ef5ec4a131 | |||
| a8eb06f686 | |||
| d1678b529e | |||
| 1451260d4d | |||
| 415488ba39 | |||
| bf7a6d590c | |||
| 8d8120bbfd | |||
| 6cf61ae67c | |||
| 8c65aef127 | |||
| 00e71b97f6 | |||
| ee2bba5623 | |||
| 118d34db55 | |||
| 24e466fadd | |||
| 14fc4345c1 | |||
| 8e472e4c65 | |||
| ec17ccc246 | |||
| 5127f44ab3 | |||
| 2ff70db0b1 | |||
| e17ac1af83 | |||
| 31e59937dc | |||
| 12eb4ae31f | |||
| a2be9457b9 | |||
| 0d56fbc09d | |||
| 56dc1e93c1 | |||
| 691540fe64 | |||
| 7e3f1b1830 | |||
| b631e8ccbb | |||
| 60f2f31d6c | |||
| 045954f8d3 | |||
| 27f1a9dbdd | |||
| 7c809bf18a | |||
| 6490e5e82a | |||
| 5e51f7490c | |||
| 97fba07f4e | |||
| 624e4330bb | |||
| e7917843bc | |||
| 7cd541bdd8 | |||
| 270dd49567 | |||
| 0187300473 | |||
| bf16566b4e | |||
| 895fb02f4e | |||
| 88d6af9815 | |||
| 5aa9dc701f | |||
| f4ef895d2e | |||
| 6e7148a945 | |||
| 83453273c6 | |||
| 76ae5eb747 | |||
| 9c51040f3b | |||
| e1a8ee1c15 | |||
| 44b2b092a8 | |||
| 19bd47a545 | |||
| 2b6d2e8606 | |||
| 7fc2b1ebfe | |||
| e80752ea3f | |||
| bae7222d64 | |||
| f7d3da3ac9 | |||
| eb8a8a2e04 | |||
| b4c6848433 | |||
| 0d94c537a0 | |||
| 861f266c4e | |||
| 51724d0e55 | |||
| c2d1cb9b76 | |||
|
|
c84a02c8ec | ||
| 8d3d167848 | |||
| 94f6cc6942 | |||
| 4a9b95acad | |||
| ef9c1cce77 | |||
| df65ac3439 | |||
| e5ddd296db | |||
| 4be008556e | |||
| 78e9893341 | |||
| d9921b857b | |||
| e62ef001ed | |||
| 1fb7132c64 | |||
| 2d74c66fc6 | |||
| 8a199b64f5 | |||
| b7fe62fcbb | |||
| cd8542258c | |||
| 472a3c1051 | |||
| 88270ece61 | |||
| e7cfbf914a | |||
| fbd466a85c | |||
| 2f8e150f41 | |||
| 764fd6d451 | |||
| 78fffcd725 | |||
| e1133ea114 | |||
| d8e8a49745 | |||
| a7ba9be486 | |||
| 1c3669cb47 | |||
| 90b80b24bc | |||
| c879ca143f | |||
| bc2bd2f2f4 | |||
| 28978299c9 | |||
| 87f6afc249 | |||
| 254f392cb5 | |||
| a6bcaade46 | |||
| 6c145f1100 | |||
| 40cd765019 | |||
| db9c8d83e6 | |||
| 20551b4a80 | |||
| 5c026ae6dd | |||
| 76c0cacc1b | |||
| f17948397f | |||
| 16a665241e | |||
| 065e3904b8 | |||
| 22752960f9 | |||
| 23971ecd7c | |||
| fbcd3e4f7f | |||
| d307893f15 | |||
| 00c0566533 | |||
| f5e3f1aaea | |||
| 508b97ca7c | |||
| 80bdd0ee8a | |||
| 6c06a4ae07 | |||
| ad1aa897b1 | |||
| dccc9c04f5 | |||
| 9345e63a32 | |||
| ff830486af | |||
| da83019d85 | |||
| 53aa47f91e | |||
| 8f470278a7 | |||
| 213fb25686 | |||
| 45668638e1 | |||
| 0857aba039 | |||
| 452ebc2614 | |||
| 9e456bb4f5 | |||
| 83ba0e1044 | |||
| 2229e9d7af | |||
| 15785dd219 | |||
| 847d84b46f | |||
| 3f6f1fa0d4 | |||
| 6812d05849 | |||
| 027114c48c | |||
| eeafa086f3 | |||
| abd20b96a2 | |||
| 0ba7f2536c | |||
| 3097e6af67 | |||
| 606ea43b51 | |||
| 31ae8365a6 | |||
| 1cbf4de2a1 | |||
| b4cc5cff4f | |||
| ab9b7476a4 | |||
| e6384da57e | |||
| 79213ba8d7 | |||
| 8a1627e728 | |||
| fc718f11cf | |||
| f7dc15cbf0 | |||
| 6e9bf3a4be | |||
| fda007f014 | |||
| d7897f29c4 | |||
| 3962238f0d | |||
| 2433c02de9 | |||
| 3d6f646460 | |||
| 35fcc295aa | |||
| 7291db7ca3 | |||
| fbc18d2fad | |||
| fe42ebd347 | |||
| c8547e38f2 | |||
| bfc79abfb6 | |||
| 7697a170bd | |||
| 941c9bc0b0 | |||
| 51aeea1ec9 | |||
| 8118df85ee | |||
| 7af83910ef | |||
| 1475f4af0c | |||
| a3a61c734f | |||
| 3f77bc7aef | |||
| d5125dd811 | |||
| 1ca316c085 | |||
| e390f1edb3 |
5
.cargo/config.toml
Normal file
5
.cargo/config.toml
Normal file
@@ -0,0 +1,5 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "link-arg=/STACK:8000000"]
|
||||
|
||||
[target.x86_64-pc-windows-gnu]
|
||||
rustflags = ["-C", "link-arg=-Wl,--stack,8000000"]
|
||||
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@@ -0,0 +1,2 @@
|
||||
target/
|
||||
Dockerfile
|
||||
18
.gitea/workflows/check.yml
Normal file
18
.gitea/workflows/check.yml
Normal file
@@ -0,0 +1,18 @@
|
||||
name: Run Check Script
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: docker
|
||||
container:
|
||||
image: hub.nationtech.io/harmony/harmony_composer:latest@sha256:eb0406fcb95c63df9b7c4b19bc50ad7914dd8232ce98e9c9abef628e07c69386
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run check script
|
||||
run: bash check.sh
|
||||
95
.gitea/workflows/harmony_composer.yaml
Normal file
95
.gitea/workflows/harmony_composer.yaml
Normal file
@@ -0,0 +1,95 @@
|
||||
name: Compile and package harmony_composer
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
package_harmony_composer:
|
||||
container:
|
||||
image: hub.nationtech.io/harmony/harmony_composer:latest@sha256:eb0406fcb95c63df9b7c4b19bc50ad7914dd8232ce98e9c9abef628e07c69386
|
||||
runs-on: dind
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Build for Linux x86_64
|
||||
run: cargo build --release --bin harmony_composer --target x86_64-unknown-linux-gnu
|
||||
|
||||
- name: Build for Windows x86_64 GNU
|
||||
run: cargo build --release --bin harmony_composer --target x86_64-pc-windows-gnu
|
||||
|
||||
- name: Setup log into hub.nationtech.io
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: hub.nationtech.io
|
||||
username: ${{ secrets.HUB_BOT_USER }}
|
||||
password: ${{ secrets.HUB_BOT_PASSWORD }}
|
||||
|
||||
# TODO: build ARM images and MacOS binaries (or other targets) too
|
||||
|
||||
- name: Update snapshot-latest tag
|
||||
run: |
|
||||
git config user.name "Gitea CI"
|
||||
git config user.email "ci@nationtech.io"
|
||||
git tag -f snapshot-latest
|
||||
git push origin snapshot-latest --force
|
||||
|
||||
- name: Install jq
|
||||
run: apt install -y jq # The current image includes apt lists so we don't have to apt update and rm /var/lib/apt... every time. But if the image is optimized it won't work anymore
|
||||
|
||||
- name: Create or update release
|
||||
run: |
|
||||
# First, check if release exists and delete it if it does
|
||||
RELEASE_ID=$(curl -s -X GET \
|
||||
-H "Authorization: token ${{ secrets.GITEATOKEN }}" \
|
||||
"https://git.nationtech.io/api/v1/repos/nationtech/harmony/releases/tags/snapshot-latest" \
|
||||
| jq -r '.id // empty')
|
||||
|
||||
if [ -n "$RELEASE_ID" ]; then
|
||||
# Delete existing release
|
||||
curl -X DELETE \
|
||||
-H "Authorization: token ${{ secrets.GITEATOKEN }}" \
|
||||
"https://git.nationtech.io/api/v1/repos/nationtech/harmony/releases/$RELEASE_ID"
|
||||
fi
|
||||
|
||||
# Create new release
|
||||
RESPONSE=$(curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITEATOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"tag_name": "snapshot-latest",
|
||||
"name": "Latest Snapshot",
|
||||
"body": "Automated snapshot build from master branch",
|
||||
"draft": false,
|
||||
"prerelease": true
|
||||
}' \
|
||||
"https://git.nationtech.io/api/v1/repos/nationtech/harmony/releases")
|
||||
|
||||
echo "RELEASE_ID=$(echo $RESPONSE | jq -r '.id')" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload Linux binary
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITEATOKEN }}" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@target/x86_64-unknown-linux-gnu/release/harmony_composer" \
|
||||
"https://git.nationtech.io/api/v1/repos/nationtech/harmony/releases/${{ env.RELEASE_ID }}/assets?name=harmony_composer"
|
||||
|
||||
- name: Upload Windows binary
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: token ${{ secrets.GITEATOKEN }}" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary "@target/x86_64-pc-windows-gnu/release/harmony_composer.exe" \
|
||||
"https://git.nationtech.io/api/v1/repos/nationtech/harmony/releases/${{ env.RELEASE_ID }}/assets?name=harmony_composer.exe"
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: hub.nationtech.io/harmony/harmony_composer:latest
|
||||
36
CONTRIBUTING.md
Normal file
36
CONTRIBUTING.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Contributing to the Harmony project
|
||||
|
||||
## Write small P-R
|
||||
|
||||
Aim for the smallest piece of work that is mergeable.
|
||||
|
||||
Mergeable means that :
|
||||
|
||||
- it does not break the build
|
||||
- it moves the codebase one step forward
|
||||
|
||||
P-Rs can be many things, they do not have to be complete features.
|
||||
|
||||
### What a P-R **should** be
|
||||
|
||||
- Introduce a new trait : This will be the place to discuss the new trait addition, its design and implementation
|
||||
- A new implementation of a trait : a new concrete implementation of the LoadBalancer trait
|
||||
- A new CI check : something that improves quality, robustness, ci performance
|
||||
- Documentation improvements
|
||||
- Refactoring
|
||||
- Bugfix
|
||||
|
||||
### What a P-R **should not** be
|
||||
|
||||
- Large. Anything over 200 lines (excluding generated lines) should have a very good reason to be this large.
|
||||
- A mix of refactoring, bug fixes and new features.
|
||||
- Introducing multiple new features or ideas at once.
|
||||
- Multiple new implementations of a trait/functionnality at once
|
||||
|
||||
The general idea is to keep P-Rs small and single purpose.
|
||||
|
||||
## Commit message formatting
|
||||
|
||||
We follow conventional commits guidelines.
|
||||
|
||||
https://www.conventionalcommits.org/en/v1.0.0/
|
||||
2819
Cargo.lock
generated
2819
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
57
Cargo.toml
57
Cargo.toml
@@ -9,6 +9,9 @@ members = [
|
||||
"harmony_tui",
|
||||
"opnsense-config",
|
||||
"opnsense-config-xml",
|
||||
"harmony_cli",
|
||||
"k3d",
|
||||
"harmony_composer",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
@@ -17,25 +20,35 @@ readme = "README.md"
|
||||
license = "GNU AGPL v3"
|
||||
|
||||
[workspace.dependencies]
|
||||
log = "0.4.22"
|
||||
env_logger = "0.11.5"
|
||||
derive-new = "0.7.0"
|
||||
async-trait = "0.1.82"
|
||||
tokio = { version = "1.40.0", features = ["io-std", "fs"] }
|
||||
cidr = "0.2.3"
|
||||
russh = "0.45.0"
|
||||
russh-keys = "0.45.0"
|
||||
rand = "0.8.5"
|
||||
url = "2.5.4"
|
||||
kube = "0.98.0"
|
||||
k8s-openapi = { version = "0.24.0", features = [ "v1_30" ] }
|
||||
serde_yaml = "0.9.34"
|
||||
http = "1.2.0"
|
||||
|
||||
[workspace.dependencies.uuid]
|
||||
version = "1.11.0"
|
||||
features = [
|
||||
"v4", # Lets you generate random UUIDs
|
||||
"fast-rng", # Use a faster (but still sufficiently random) RNG
|
||||
"macro-diagnostics", # Enable better diagnostics for compile-time UUIDs
|
||||
]
|
||||
log = "0.4"
|
||||
env_logger = "0.11"
|
||||
derive-new = "0.7"
|
||||
async-trait = "0.1"
|
||||
tokio = { version = "1.40", features = [
|
||||
"io-std",
|
||||
"fs",
|
||||
"macros",
|
||||
"rt-multi-thread",
|
||||
] }
|
||||
cidr = { features = ["serde"], version = "0.2" }
|
||||
russh = "0.45"
|
||||
russh-keys = "0.45"
|
||||
rand = "0.8"
|
||||
url = "2.5"
|
||||
kube = { version = "1.1.0", features = [
|
||||
"config",
|
||||
"client",
|
||||
"runtime",
|
||||
"rustls-tls",
|
||||
"ws",
|
||||
"jsonpatch",
|
||||
] }
|
||||
k8s-openapi = { version = "0.25", features = ["v1_30"] }
|
||||
serde_yaml = "0.9"
|
||||
serde-value = "0.7"
|
||||
http = "1.2"
|
||||
inquire = "0.7"
|
||||
convert_case = "0.8"
|
||||
chrono = "0.4"
|
||||
similar = "2"
|
||||
uuid = { version = "1.11", features = ["v4", "fast-rng", "macro-diagnostics"] }
|
||||
|
||||
25
Dockerfile
Normal file
25
Dockerfile
Normal file
@@ -0,0 +1,25 @@
|
||||
FROM docker.io/rust:1.87.0 AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN cargo build --release --bin harmony_composer
|
||||
|
||||
FROM docker.io/rust:1.87.0
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN rustup target add x86_64-pc-windows-gnu
|
||||
RUN rustup target add x86_64-unknown-linux-gnu
|
||||
RUN rustup component add rustfmt
|
||||
|
||||
RUN apt update
|
||||
|
||||
# TODO: Consider adding more supported targets
|
||||
# nodejs for checkout action, docker for building containers, mingw for cross-compiling for windows
|
||||
RUN apt install -y nodejs docker.io mingw-w64
|
||||
|
||||
COPY --from=build /app/target/release/harmony_composer .
|
||||
|
||||
ENTRYPOINT ["/app/harmony_composer"]
|
||||
152
README.md
152
README.md
@@ -1,9 +1,151 @@
|
||||
### Watch the whole repo on every change
|
||||
# Harmony : Open-source infrastructure orchestration that treats your platform like first-class code.
|
||||
*By [NationTech](https://nationtech.io)*
|
||||
|
||||
Due to the current setup being a mix of separate repositories with gitignore and rust workspace, a few options are required for cargo-watch to have the desired behavior :
|
||||
[](https://git.nationtech.io/nationtech/harmony)
|
||||
[](LICENSE)
|
||||
|
||||
```sh
|
||||
RUST_LOG=info cargo watch --ignore-nothing -w harmony -w private_repos/ -x 'run --bin nationtech'
|
||||
### Unify
|
||||
|
||||
- **Project Scaffolding**
|
||||
- **Infrastructure Provisioning**
|
||||
- **Application Deployment**
|
||||
- **Day-2 operations**
|
||||
|
||||
All in **one strongly-typed Rust codebase**.
|
||||
|
||||
### Deploy anywhere
|
||||
|
||||
From a **developer laptop** to a **global production cluster**, a single **source of truth** drives the **full software lifecycle.**
|
||||
|
||||
---
|
||||
|
||||
## 1 · 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.
|
||||
|
||||
| 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. |
|
||||
|
||||
These principles surface as simple, ergonomic Rust APIs that let teams focus on their product while trusting the platform underneath.
|
||||
|
||||
---
|
||||
|
||||
## 2 · Quick Start
|
||||
|
||||
The snippet below spins up a complete **production-grade LAMP stack** with monitoring. Swap it for your own scores to deploy anything from microservices to machine-learning pipelines.
|
||||
|
||||
```rust
|
||||
use harmony::{
|
||||
data::Version,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
lamp::{LAMPConfig, LAMPScore},
|
||||
monitoring::monitoring_alerting::MonitoringAlertingStackScore,
|
||||
},
|
||||
topology::{K8sAnywhereTopology, Url},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// 1. Describe what you want
|
||||
let lamp_stack = LAMPScore {
|
||||
name: "harmony-lamp-demo".into(),
|
||||
domain: Url::Url(url::Url::parse("https://lampdemo.example.com").unwrap()),
|
||||
php_version: Version::from("8.3.0").unwrap(),
|
||||
config: LAMPConfig {
|
||||
project_root: "./php".into(),
|
||||
database_size: "4Gi".into(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
// 2. Pick where it should run
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(), // auto-detect hardware / kube-config
|
||||
K8sAnywhereTopology::from_env(), // local k3d, CI, staging, prod…
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// 3. Enhance with extra scores (monitoring, CI/CD, …)
|
||||
let mut monitoring = MonitoringAlertingStackScore::new();
|
||||
monitoring.namespace = Some(lamp_stack.config.namespace.clone());
|
||||
|
||||
maestro.register_all(vec![Box::new(lamp_stack), Box::new(monitoring)]);
|
||||
|
||||
// 4. Launch an interactive CLI / TUI
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
This will run the nationtech bin (likely `private_repos/nationtech/src/main.rs`) on any change in the harmony or private_repos folders.
|
||||
Run it:
|
||||
|
||||
```bash
|
||||
cargo run
|
||||
```
|
||||
|
||||
Harmony analyses the code, shows an execution plan in a TUI, and applies it once you confirm. Same code, same binary—every environment.
|
||||
|
||||
---
|
||||
|
||||
## 3 · Core Concepts
|
||||
|
||||
| Term | One-liner |
|
||||
|------|-----------|
|
||||
| **Score<T>** | Declarative description of the desired state (e.g., `LAMPScore`). |
|
||||
| **Interpret<T>** | Imperative logic that realises a `Score` on a specific environment. |
|
||||
| **Topology** | An environment (local k3d, AWS, bare-metal) exposing verified *Capabilities* (Kubernetes, DNS, …). |
|
||||
| **Maestro** | Orchestrator that compiles Scores + Topology, ensuring all capabilities line up **at compile-time**. |
|
||||
| **Inventory** | Optional catalogue of physical assets for bare-metal and edge deployments. |
|
||||
|
||||
A visual overview is in the diagram below.
|
||||
|
||||
[Harmony Core Architecture](docs/diagrams/Harmony_Core_Architecture.drawio.svg)
|
||||
|
||||
---
|
||||
|
||||
## 4 · Install
|
||||
|
||||
Prerequisites:
|
||||
|
||||
* Rust
|
||||
* Docker (if you deploy locally)
|
||||
* `kubectl` / `helm` for Kubernetes-based topologies
|
||||
|
||||
```bash
|
||||
git clone https://git.nationtech.io/nationtech/harmony
|
||||
cd harmony
|
||||
cargo build --release # builds the CLI, TUI and libraries
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5 · Learning More
|
||||
|
||||
* **Architectural Decision Records** – dive into the rationale
|
||||
- [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)
|
||||
|
||||
* **Extending Harmony** – write new Scores / Interprets, add hardware like OPNsense firewalls, or embed Harmony in your own tooling (`/docs`).
|
||||
|
||||
* **Community** – discussions and roadmap live in [GitLab issues](https://git.nationtech.io/nationtech/harmony/-/issues). PRs, ideas, and feedback are welcome!
|
||||
|
||||
---
|
||||
|
||||
## 6 · 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.
|
||||
|
||||
See [LICENSE](LICENSE) for the full text.
|
||||
|
||||
---
|
||||
|
||||
*Made with ❤️ & 🦀 by the NationTech and the Harmony community*
|
||||
|
||||
33
adr/000-ADR-Template.md
Normal file
33
adr/000-ADR-Template.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Architecture Decision Record: \<Title\>
|
||||
|
||||
Initial Author: \<Name\>
|
||||
|
||||
Initial Date: \<Date\>
|
||||
|
||||
Last Updated Date: \<Date\>
|
||||
|
||||
## Status
|
||||
|
||||
Proposed/Pending/Accepted/Implemented
|
||||
|
||||
## Context
|
||||
|
||||
The problem, background, the "why" behind this decision/discussion
|
||||
|
||||
## Decision
|
||||
|
||||
Proposed solution to the problem
|
||||
|
||||
## Rationale
|
||||
|
||||
Reasoning behind the decision
|
||||
|
||||
## Consequences
|
||||
|
||||
Pros/Cons of chosen solution
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Pros/Cons of various proposed solutions considered
|
||||
|
||||
## Additional Notes
|
||||
360
adr/003-abstractions/main_context_prompt.md
Normal file
360
adr/003-abstractions/main_context_prompt.md
Normal file
@@ -0,0 +1,360 @@
|
||||
|
||||
# Here is the current condenses architecture sample for Harmony's core abstractions
|
||||
|
||||
```rust
|
||||
use std::process::Command;
|
||||
|
||||
pub trait Capability {}
|
||||
|
||||
pub trait CommandCapability: Capability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait KubernetesCapability: Capability {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String>;
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait Topology {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
pub trait Score<T: Topology> {
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
pub struct LinuxHostTopology {
|
||||
name: String,
|
||||
host: String,
|
||||
}
|
||||
|
||||
impl Capability for LinuxHostTopology {}
|
||||
|
||||
impl LinuxHostTopology {
|
||||
pub fn new(name: String, host: String) -> Self {
|
||||
Self { name, host }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxHostTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
println!("Executing on {}: {} {:?}", self.host, command, args);
|
||||
// In a real implementation, this would SSH to the host and execute the command
|
||||
let output = Command::new(command)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&output.stderr).to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct K3DTopology {
|
||||
name: String,
|
||||
linux_host: LinuxHostTopology,
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl Capability for K3DTopology {}
|
||||
|
||||
impl K3DTopology {
|
||||
pub fn new(name: String, linux_host: LinuxHostTopology, cluster_name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
linux_host,
|
||||
cluster_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for K3DTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
self.linux_host.execute_command(command, args)
|
||||
}
|
||||
}
|
||||
|
||||
impl KubernetesCapability for K3DTopology {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String> {
|
||||
println!("Applying manifest to K3D cluster '{}'", self.cluster_name);
|
||||
// Write manifest to a temporary file
|
||||
let temp_file = format!("/tmp/manifest-harmony-temp.yaml");
|
||||
|
||||
// Use the linux_host directly to avoid capability trait bounds
|
||||
self.linux_host
|
||||
.execute_command("bash", &["-c", &format!("cat > {}", temp_file)])?;
|
||||
|
||||
// Apply with kubectl
|
||||
self.linux_host.execute_command("kubectl", &[
|
||||
"--context",
|
||||
&format!("k3d-{}", self.cluster_name),
|
||||
"apply",
|
||||
"-f",
|
||||
&temp_file,
|
||||
])?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String> {
|
||||
println!(
|
||||
"Getting resource {}/{} from K3D cluster '{}'",
|
||||
resource_type, name, self.cluster_name
|
||||
);
|
||||
self.linux_host.execute_command("kubectl", &[
|
||||
"--context",
|
||||
&format!("k3d-{}", self.cluster_name),
|
||||
"get",
|
||||
resource_type,
|
||||
name,
|
||||
"-o",
|
||||
"yaml",
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CommandScore {
|
||||
name: String,
|
||||
command: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
pub fn new(name: String, command: String, args: Vec<String>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
command,
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Interpret<T: Topology> {
|
||||
fn execute(&self, topology: &T) -> Result<String, String>;
|
||||
}
|
||||
|
||||
struct CommandInterpret;
|
||||
|
||||
impl<T> Interpret<T> for CommandInterpret
|
||||
where
|
||||
T: Topology + CommandCapability,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for CommandScore
|
||||
where
|
||||
T: Topology + CommandCapability,
|
||||
{
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String> {
|
||||
Ok(Box::new(CommandInterpret {}))
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct K8sResourceScore {
|
||||
name: String,
|
||||
manifest: String,
|
||||
}
|
||||
|
||||
impl K8sResourceScore {
|
||||
pub fn new(name: String, manifest: String) -> Self {
|
||||
Self { name, manifest }
|
||||
}
|
||||
}
|
||||
|
||||
struct K8sResourceInterpret {
|
||||
score: K8sResourceScore,
|
||||
}
|
||||
|
||||
impl<T: Topology + KubernetesCapability> Interpret<T> for K8sResourceInterpret {
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for K8sResourceScore
|
||||
where
|
||||
T: Topology + KubernetesCapability,
|
||||
{
|
||||
fn compile(&self) -> Result<Box<(dyn Interpret<T> + 'static)>, String> {
|
||||
Ok(Box::new(K8sResourceInterpret {
|
||||
score: self.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Maestro<T: Topology> {
|
||||
topology: T,
|
||||
scores: Vec<Box<dyn Score<T>>>,
|
||||
}
|
||||
|
||||
|
||||
impl<T: Topology> Maestro<T> {
|
||||
pub fn new(topology: T) -> Self {
|
||||
Self {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_score<S>(&mut self, score: S)
|
||||
where
|
||||
S: Score<T> + 'static,
|
||||
{
|
||||
println!(
|
||||
"Registering score '{}' for topology '{}'",
|
||||
score.name(),
|
||||
self.topology.name()
|
||||
);
|
||||
self.scores.push(Box::new(score));
|
||||
}
|
||||
|
||||
pub fn orchestrate(&self) -> Result<(), String> {
|
||||
println!("Orchestrating topology '{}'", self.topology.name());
|
||||
for score in &self.scores {
|
||||
let interpret = score.compile()?;
|
||||
interpret.execute(&self.topology)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let linux_host = LinuxHostTopology::new("dev-machine".to_string(), "localhost".to_string());
|
||||
|
||||
let mut linux_maestro = Maestro::new(linux_host);
|
||||
|
||||
linux_maestro.register_score(CommandScore::new(
|
||||
"check-disk".to_string(),
|
||||
"df".to_string(),
|
||||
vec!["-h".to_string()],
|
||||
));
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
|
||||
// This would fail to compile if we tried to register a K8sResourceScore
|
||||
// because LinuxHostTopology doesn't implement KubernetesCapability
|
||||
//linux_maestro.register_score(K8sResourceScore::new(
|
||||
// "...".to_string(),
|
||||
// "...".to_string(),
|
||||
//));
|
||||
|
||||
// Create a K3D topology which has both Command and Kubernetes capabilities
|
||||
let k3d_host = LinuxHostTopology::new("k3d-host".to_string(), "localhost".to_string());
|
||||
|
||||
let k3d_topology = K3DTopology::new(
|
||||
"dev-cluster".to_string(),
|
||||
k3d_host,
|
||||
"devcluster".to_string(),
|
||||
);
|
||||
|
||||
// Create a maestro for the K3D topology
|
||||
let mut k3d_maestro = Maestro::new(k3d_topology);
|
||||
|
||||
// We can register both command scores and kubernetes scores
|
||||
k3d_maestro.register_score(CommandScore::new(
|
||||
"check-nodes".to_string(),
|
||||
"kubectl".to_string(),
|
||||
vec!["get".to_string(), "nodes".to_string()],
|
||||
));
|
||||
|
||||
k3d_maestro.register_score(K8sResourceScore::new(
|
||||
"deploy-nginx".to_string(),
|
||||
r#"
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: nginx
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: nginx
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: nginx
|
||||
spec:
|
||||
containers:
|
||||
- name: nginx
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- containerPort: 80
|
||||
"#
|
||||
.to_string(),
|
||||
));
|
||||
|
||||
// Orchestrate both topologies
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
k3d_maestro.orchestrate().unwrap();
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Technical take
|
||||
|
||||
The key insight is that we might not need a complex TypeMap or runtime capability checking. Instead, we should leverage Rust's trait system to express capability requirements directly in the type system.
|
||||
|
||||
By clarifying the problem and focusing on type-level solutions rather than runtime checks, we can likely arrive at a simpler, more robust design that leverages the strengths of Rust's type system.
|
||||
|
||||
## Philosophical Shifts
|
||||
|
||||
1. **From Runtime to Compile-Time**: Move capability checking from runtime to compile-time.
|
||||
|
||||
2. **From Objects to Functions**: Think of scores less as objects and more as functions that transform topologies.
|
||||
|
||||
3. **From Homogeneous to Heterogeneous API**: Embrace different API paths for different capability combinations rather than trying to force everything through a single interface.
|
||||
|
||||
4. **From Complex to Simple**: Focus on making common cases simple, even if it means less abstraction for uncommon cases.
|
||||
|
||||
## High level concepts
|
||||
|
||||
The high level concepts so far has evolved towards this definition.
|
||||
|
||||
Topology -> Has -> Capabilities
|
||||
Score -> Defines -> Work to be done / desired state
|
||||
Interpret -> Requires -> Capabilities to execute a Score
|
||||
Maestro -> Enforces -> Compatibility (through the type system at compile time)
|
||||
|
||||
## Why Harmony
|
||||
|
||||
The compile time safety is paramount here. Harmony's main goal is to make the entire software delivery pipeline robust. Current IaC tools are very hard to work with, require complex setups to test and debug real code.
|
||||
|
||||
Leveraging Rust's compiler allows us to shift left a lot of the complexities and frustration that comes with using tools like Ansible that is Yaml based and quickly becomes brittle at scale. Or Terraform, when running a `terraform plan` makes you think everything is correct only to fail horribly when confidently launching `terraform apply` and leaving you with tens or hundreds of resources to clean manually.
|
||||
|
||||
Of course, this requires a significant effort to get to the point where we have actually implemented all the logic.
|
||||
|
||||
But using Rust and a Type Driven Design approach, we believe we are providing a much more robust foundation for our customer's and user's deployments anywhere.
|
||||
|
||||
Also, having the full power of a mature programming language like Rust enables organizations and the community to customize their deployment any way they want, build upon it in a reliable way that has been evolved and proven over decades of enterprise dependency management, API definitions, etc.
|
||||
|
||||
===
|
||||
|
||||
Given all this c
|
||||
10
adr/003-abstractions/topology/Cargo.toml
Normal file
10
adr/003-abstractions/topology/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "example-topology"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
rand.workspace = true
|
||||
232
adr/003-abstractions/topology/src/main.rs
Normal file
232
adr/003-abstractions/topology/src/main.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
// Basic traits from your example
|
||||
trait Topology {}
|
||||
|
||||
trait Score: Clone + std::fmt::Debug {
|
||||
fn get_interpret<T: Topology>(&self) -> Box<dyn Interpret<T>>;
|
||||
fn name(&self) -> String;
|
||||
}
|
||||
|
||||
trait Interpret<T: Topology> {
|
||||
fn execute(&self);
|
||||
}
|
||||
|
||||
struct Maestro<T: Topology> {
|
||||
topology: T
|
||||
}
|
||||
|
||||
impl<T: Topology> Maestro<T> {
|
||||
pub fn new(topology: T) -> Self {
|
||||
Maestro { topology }
|
||||
}
|
||||
|
||||
pub fn register_score<S: Score + 'static>(&self, score: S) {
|
||||
println!("Registering score: {}", score.name());
|
||||
}
|
||||
|
||||
pub fn execute_score<S: Score + 'static>(&self, score: S) {
|
||||
println!("Executing score: {}", score.name());
|
||||
score.get_interpret::<T>().execute();
|
||||
}
|
||||
}
|
||||
|
||||
// Capability traits - these are used to enforce requirements
|
||||
trait CommandExecution {
|
||||
fn execute_command(&self, command: &[String]) -> Result<String, String>;
|
||||
}
|
||||
|
||||
trait FileSystem {
|
||||
fn read_file(&self, path: &str) -> Result<String, String>;
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
// A concrete topology implementation
|
||||
#[derive(Clone, Debug)]
|
||||
struct LinuxHostTopology {
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
impl Topology for LinuxHostTopology {}
|
||||
|
||||
// Implement the capabilities for LinuxHostTopology
|
||||
impl CommandExecution for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &[String]) -> Result<String, String> {
|
||||
println!("Executing command on {}: {:?}", self.hostname, command);
|
||||
// In a real implementation, this would use std::process::Command
|
||||
Ok(format!("Command executed successfully on {}", self.hostname))
|
||||
}
|
||||
}
|
||||
|
||||
impl FileSystem for LinuxHostTopology {
|
||||
fn read_file(&self, path: &str) -> Result<String, String> {
|
||||
println!("Reading file {} on {}", path, self.hostname);
|
||||
Ok(format!("Content of {} on {}", path, self.hostname))
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
|
||||
println!("Writing to file {} on {}: {}", path, self.hostname, content);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Another topology that doesn't support command execution
|
||||
#[derive(Clone, Debug)]
|
||||
struct BareMetalTopology {
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
impl Topology for BareMetalTopology {}
|
||||
|
||||
impl FileSystem for BareMetalTopology {
|
||||
fn read_file(&self, path: &str) -> Result<String, String> {
|
||||
println!("Reading file {} on device {}", path, self.device_id);
|
||||
Ok(format!("Content of {} on device {}", path, self.device_id))
|
||||
}
|
||||
|
||||
fn write_file(&self, path: &str, content: &str) -> Result<(), String> {
|
||||
println!("Writing to file {} on device {}: {}", path, self.device_id, content);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// CommandScore implementation
|
||||
#[derive(Clone, Debug)]
|
||||
struct CommandScore {
|
||||
name: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
pub fn new(name: String, args: Vec<String>) -> Self {
|
||||
CommandScore { name, args }
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for CommandScore {
|
||||
fn get_interpret<T: Topology + CommandExecution + 'static>(&self) -> Box<dyn Interpret<T>> {
|
||||
// This is the key part: we constrain T to implement CommandExecution
|
||||
// If T doesn't implement CommandExecution, this will fail to compile
|
||||
Box::new(CommandInterpret::<T>::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
}
|
||||
|
||||
// CommandInterpret implementation
|
||||
struct CommandInterpret<T: Topology + CommandExecution> {
|
||||
score: CommandScore,
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: Topology + CommandExecution> CommandInterpret<T> {
|
||||
pub fn new(score: CommandScore) -> Self {
|
||||
CommandInterpret {
|
||||
score,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology + CommandExecution> Interpret<T> for CommandInterpret<T> {
|
||||
fn execute(&self) {
|
||||
println!("Command interpret is executing: {:?}", self.score.args);
|
||||
// In a real implementation, you would call the topology's execute_command method
|
||||
// topology.execute_command(&self.score.args);
|
||||
}
|
||||
}
|
||||
|
||||
// FileScore implementation - a different type of score that requires FileSystem capability
|
||||
#[derive(Clone, Debug)]
|
||||
struct FileScore {
|
||||
name: String,
|
||||
path: String,
|
||||
content: Option<String>,
|
||||
}
|
||||
|
||||
impl FileScore {
|
||||
pub fn new_read(name: String, path: String) -> Self {
|
||||
FileScore { name, path, content: None }
|
||||
}
|
||||
|
||||
pub fn new_write(name: String, path: String, content: String) -> Self {
|
||||
FileScore { name, path, content: Some(content) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for FileScore {
|
||||
fn get_interpret<T: Topology>(&self) -> Box<dyn Interpret<T>> {
|
||||
// This constrains T to implement FileSystem
|
||||
Box::new(FileInterpret::<T>::new(self.clone()))
|
||||
}
|
||||
|
||||
fn name(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
}
|
||||
|
||||
// FileInterpret implementation
|
||||
struct FileInterpret<T: Topology + FileSystem> {
|
||||
score: FileScore,
|
||||
_marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: Topology + FileSystem> FileInterpret<T> {
|
||||
pub fn new(score: FileScore) -> Self {
|
||||
FileInterpret {
|
||||
score,
|
||||
_marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology + FileSystem> Interpret<T> for FileInterpret<T> {
|
||||
fn execute(&self) {
|
||||
match &self.score.content {
|
||||
Some(content) => {
|
||||
println!("File interpret is writing to {}: {}", self.score.path, content);
|
||||
// In a real implementation: topology.write_file(&self.score.path, content);
|
||||
},
|
||||
None => {
|
||||
println!("File interpret is reading from {}", self.score.path);
|
||||
// In a real implementation: let content = topology.read_file(&self.score.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Create our topologies
|
||||
let linux = LinuxHostTopology { hostname: "server1.example.com".to_string() };
|
||||
let bare_metal = BareMetalTopology { device_id: "device001".to_string() };
|
||||
|
||||
// Create our maestros
|
||||
let linux_maestro = Maestro::new(linux);
|
||||
let bare_metal_maestro = Maestro::new(bare_metal);
|
||||
|
||||
// Create scores
|
||||
let command_score = CommandScore::new(
|
||||
"List Files".to_string(),
|
||||
vec!["ls".to_string(), "-la".to_string()]
|
||||
);
|
||||
|
||||
let file_read_score = FileScore::new_read(
|
||||
"Read Config".to_string(),
|
||||
"/etc/config.json".to_string()
|
||||
);
|
||||
|
||||
// This will work because LinuxHostTopology implements CommandExecution
|
||||
linux_maestro.execute_score(command_score.clone());
|
||||
|
||||
// This will work because LinuxHostTopology implements FileSystem
|
||||
linux_maestro.execute_score(file_read_score.clone());
|
||||
|
||||
// This will work because BareMetalTopology implements FileSystem
|
||||
bare_metal_maestro.execute_score(file_read_score);
|
||||
|
||||
// This would NOT compile because BareMetalTopology doesn't implement CommandExecution:
|
||||
// bare_metal_maestro.execute_score(command_score);
|
||||
// The error would occur at compile time, ensuring type safety
|
||||
|
||||
println!("All scores executed successfully!");
|
||||
}
|
||||
314
adr/003-abstractions/topology/src/main_claude37_2.rs
Normal file
314
adr/003-abstractions/topology/src/main_claude37_2.rs
Normal file
@@ -0,0 +1,314 @@
|
||||
mod main_gemini25pro;
|
||||
use std::process::Command;
|
||||
|
||||
pub trait Capability {}
|
||||
|
||||
pub trait CommandCapability: Capability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait KubernetesCapability: Capability {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String>;
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait Topology {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
pub trait Score<T: Topology> {
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
pub struct LinuxHostTopology {
|
||||
name: String,
|
||||
host: String,
|
||||
}
|
||||
|
||||
impl Capability for LinuxHostTopology {}
|
||||
|
||||
impl LinuxHostTopology {
|
||||
pub fn new(name: String, host: String) -> Self {
|
||||
Self { name, host }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxHostTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
println!("Executing on {}: {} {:?}", self.host, command, args);
|
||||
// In a real implementation, this would SSH to the host and execute the command
|
||||
let output = Command::new(command)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&output.stderr).to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct K3DTopology {
|
||||
name: String,
|
||||
linux_host: LinuxHostTopology,
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl Capability for K3DTopology {}
|
||||
|
||||
impl K3DTopology {
|
||||
pub fn new(name: String, linux_host: LinuxHostTopology, cluster_name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
linux_host,
|
||||
cluster_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for K3DTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
self.linux_host.execute_command(command, args)
|
||||
}
|
||||
}
|
||||
|
||||
impl KubernetesCapability for K3DTopology {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String> {
|
||||
println!("Applying manifest to K3D cluster '{}'", self.cluster_name);
|
||||
// Write manifest to a temporary file
|
||||
let temp_file = format!("/tmp/manifest-harmony-temp.yaml");
|
||||
|
||||
// Use the linux_host directly to avoid capability trait bounds
|
||||
self.linux_host
|
||||
.execute_command("bash", &["-c", &format!("cat > {}", temp_file)])?;
|
||||
|
||||
// Apply with kubectl
|
||||
self.linux_host.execute_command("kubectl", &[
|
||||
"--context",
|
||||
&format!("k3d-{}", self.cluster_name),
|
||||
"apply",
|
||||
"-f",
|
||||
&temp_file,
|
||||
])?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String> {
|
||||
println!(
|
||||
"Getting resource {}/{} from K3D cluster '{}'",
|
||||
resource_type, name, self.cluster_name
|
||||
);
|
||||
self.linux_host.execute_command("kubectl", &[
|
||||
"--context",
|
||||
&format!("k3d-{}", self.cluster_name),
|
||||
"get",
|
||||
resource_type,
|
||||
name,
|
||||
"-o",
|
||||
"yaml",
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CommandScore {
|
||||
name: String,
|
||||
command: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
pub fn new(name: String, command: String, args: Vec<String>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
command,
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Interpret<T: Topology> {
|
||||
fn execute(&self, topology: &T) -> Result<String, String>;
|
||||
}
|
||||
|
||||
struct CommandInterpret;
|
||||
|
||||
impl<T> Interpret<T> for CommandInterpret
|
||||
where
|
||||
T: Topology + CommandCapability,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for CommandScore
|
||||
where
|
||||
T: Topology + CommandCapability,
|
||||
{
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String> {
|
||||
Ok(Box::new(CommandInterpret {}))
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct K8sResourceScore {
|
||||
name: String,
|
||||
manifest: String,
|
||||
}
|
||||
|
||||
impl K8sResourceScore {
|
||||
pub fn new(name: String, manifest: String) -> Self {
|
||||
Self { name, manifest }
|
||||
}
|
||||
}
|
||||
|
||||
struct K8sResourceInterpret {
|
||||
score: K8sResourceScore,
|
||||
}
|
||||
|
||||
impl<T: Topology + KubernetesCapability> Interpret<T> for K8sResourceInterpret {
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for K8sResourceScore
|
||||
where
|
||||
T: Topology + KubernetesCapability,
|
||||
{
|
||||
fn compile(&self) -> Result<Box<(dyn Interpret<T> + 'static)>, String> {
|
||||
Ok(Box::new(K8sResourceInterpret {
|
||||
score: self.clone(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Maestro<T: Topology> {
|
||||
topology: T,
|
||||
scores: Vec<Box<dyn Score<T>>>,
|
||||
}
|
||||
|
||||
|
||||
impl<T: Topology> Maestro<T> {
|
||||
pub fn new(topology: T) -> Self {
|
||||
Self {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_score<S>(&mut self, score: S)
|
||||
where
|
||||
S: Score<T> + 'static,
|
||||
{
|
||||
println!(
|
||||
"Registering score '{}' for topology '{}'",
|
||||
score.name(),
|
||||
self.topology.name()
|
||||
);
|
||||
self.scores.push(Box::new(score));
|
||||
}
|
||||
|
||||
pub fn orchestrate(&self) -> Result<(), String> {
|
||||
println!("Orchestrating topology '{}'", self.topology.name());
|
||||
for score in &self.scores {
|
||||
let interpret = score.compile()?;
|
||||
interpret.execute(&self.topology)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let linux_host = LinuxHostTopology::new("dev-machine".to_string(), "localhost".to_string());
|
||||
|
||||
let mut linux_maestro = Maestro::new(linux_host);
|
||||
|
||||
linux_maestro.register_score(CommandScore::new(
|
||||
"check-disk".to_string(),
|
||||
"df".to_string(),
|
||||
vec!["-h".to_string()],
|
||||
));
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
|
||||
// This would fail to compile if we tried to register a K8sResourceScore
|
||||
// because LinuxHostTopology doesn't implement KubernetesCapability
|
||||
//linux_maestro.register_score(K8sResourceScore::new(
|
||||
// "...".to_string(),
|
||||
// "...".to_string(),
|
||||
//));
|
||||
|
||||
// Create a K3D topology which has both Command and Kubernetes capabilities
|
||||
let k3d_host = LinuxHostTopology::new("k3d-host".to_string(), "localhost".to_string());
|
||||
|
||||
let k3d_topology = K3DTopology::new(
|
||||
"dev-cluster".to_string(),
|
||||
k3d_host,
|
||||
"devcluster".to_string(),
|
||||
);
|
||||
|
||||
// Create a maestro for the K3D topology
|
||||
let mut k3d_maestro = Maestro::new(k3d_topology);
|
||||
|
||||
// We can register both command scores and kubernetes scores
|
||||
k3d_maestro.register_score(CommandScore::new(
|
||||
"check-nodes".to_string(),
|
||||
"kubectl".to_string(),
|
||||
vec!["get".to_string(), "nodes".to_string()],
|
||||
));
|
||||
|
||||
k3d_maestro.register_score(K8sResourceScore::new(
|
||||
"deploy-nginx".to_string(),
|
||||
r#"
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: nginx
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: nginx
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: nginx
|
||||
spec:
|
||||
containers:
|
||||
- name: nginx
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- containerPort: 80
|
||||
"#
|
||||
.to_string(),
|
||||
));
|
||||
|
||||
// Orchestrate both topologies
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
k3d_maestro.orchestrate().unwrap();
|
||||
}
|
||||
323
adr/003-abstractions/topology/src/main_claudev1.rs
Normal file
323
adr/003-abstractions/topology/src/main_claudev1.rs
Normal file
@@ -0,0 +1,323 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::process::Command;
|
||||
|
||||
// ===== Capability Traits =====
|
||||
|
||||
/// Base trait for all capabilities
|
||||
pub trait Capability {}
|
||||
|
||||
/// Capability for executing shell commands on a host
|
||||
pub trait CommandCapability: Capability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String>;
|
||||
}
|
||||
|
||||
/// Capability for interacting with a Kubernetes cluster
|
||||
pub trait KubernetesCapability: Capability {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String>;
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
// ===== Topology Traits =====
|
||||
|
||||
/// Base trait for all topologies
|
||||
pub trait Topology {
|
||||
// Base topology methods that don't depend on capabilities
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
// ===== Score Traits =====
|
||||
|
||||
/// Generic Score trait with an associated Capability type
|
||||
pub trait Score<T: Topology> {
|
||||
fn apply(&self, topology: &T) -> Result<(), String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
// ===== Concrete Topologies =====
|
||||
|
||||
/// A topology representing a Linux host
|
||||
pub struct LinuxHostTopology {
|
||||
name: String,
|
||||
host: String,
|
||||
}
|
||||
|
||||
impl LinuxHostTopology {
|
||||
pub fn new(name: String, host: String) -> Self {
|
||||
Self { name, host }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxHostTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
println!("Executing on {}: {} {:?}", self.host, command, args);
|
||||
// In a real implementation, this would SSH to the host and execute the command
|
||||
let output = Command::new(command)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&output.stderr).to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A topology representing a K3D Kubernetes cluster
|
||||
pub struct K3DTopology {
|
||||
name: String,
|
||||
linux_host: LinuxHostTopology,
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl K3DTopology {
|
||||
pub fn new(name: String, linux_host: LinuxHostTopology, cluster_name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
linux_host,
|
||||
cluster_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for K3DTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> Result<String, String> {
|
||||
// Delegate to the underlying Linux host
|
||||
self.linux_host.execute_command(command, args)
|
||||
}
|
||||
}
|
||||
|
||||
impl KubernetesCapability for K3DTopology {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String> {
|
||||
println!("Applying manifest to K3D cluster '{}'", self.cluster_name);
|
||||
// Write manifest to a temporary file
|
||||
let temp_file = format!("/tmp/manifest-{}.yaml", rand::random::<u32>());
|
||||
self.execute_command("bash", &["-c", &format!("cat > {}", temp_file)])?;
|
||||
|
||||
// Apply with kubectl
|
||||
self.execute_command(
|
||||
"kubectl",
|
||||
&["--context", &format!("k3d-{}", self.cluster_name), "apply", "-f", &temp_file]
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String> {
|
||||
println!("Getting resource {}/{} from K3D cluster '{}'", resource_type, name, self.cluster_name);
|
||||
self.execute_command(
|
||||
"kubectl",
|
||||
&[
|
||||
"--context",
|
||||
&format!("k3d-{}", self.cluster_name),
|
||||
"get",
|
||||
resource_type,
|
||||
name,
|
||||
"-o",
|
||||
"yaml",
|
||||
]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Concrete Scores =====
|
||||
|
||||
/// A score that executes commands on a topology
|
||||
pub struct CommandScore {
|
||||
name: String,
|
||||
command: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
pub fn new(name: String, command: String, args: Vec<String>) -> Self {
|
||||
Self { name, command, args }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for CommandScore
|
||||
where
|
||||
T: Topology + CommandCapability
|
||||
{
|
||||
fn apply(&self, topology: &T) -> Result<(), String> {
|
||||
println!("Applying CommandScore '{}' to topology '{}'", self.name, topology.name());
|
||||
let args_refs: Vec<&str> = self.args.iter().map(|s| s.as_str()).collect();
|
||||
topology.execute_command(&self.command, &args_refs)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// A score that applies Kubernetes resources to a topology
|
||||
pub struct K8sResourceScore {
|
||||
name: String,
|
||||
manifest: String,
|
||||
}
|
||||
|
||||
impl K8sResourceScore {
|
||||
pub fn new(name: String, manifest: String) -> Self {
|
||||
Self { name, manifest }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Score<T> for K8sResourceScore
|
||||
where
|
||||
T: Topology + KubernetesCapability
|
||||
{
|
||||
fn apply(&self, topology: &T) -> Result<(), String> {
|
||||
println!("Applying K8sResourceScore '{}' to topology '{}'", self.name, topology.name());
|
||||
topology.apply_manifest(&self.manifest)
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Maestro Orchestrator =====
|
||||
|
||||
/// Type-safe orchestrator that enforces capability requirements at compile time
|
||||
pub struct Maestro<T: Topology> {
|
||||
topology: T,
|
||||
scores: Vec<Box<dyn ScoreWrapper<T>>>,
|
||||
}
|
||||
|
||||
/// A trait object wrapper that hides the specific Score type but preserves its
|
||||
/// capability requirements
|
||||
trait ScoreWrapper<T: Topology> {
|
||||
fn apply(&self, topology: &T) -> Result<(), String>;
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
/// Implementation of ScoreWrapper for any Score that works with topology T
|
||||
impl<T, S> ScoreWrapper<T> for S
|
||||
where
|
||||
T: Topology,
|
||||
S: Score<T> + 'static
|
||||
{
|
||||
fn apply(&self, topology: &T) -> Result<(), String> {
|
||||
<S as Score<T>>::apply(self, topology)
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
<S as Score<T>>::name(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Topology> Maestro<T> {
|
||||
pub fn new(topology: T) -> Self {
|
||||
Self {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register a score that is compatible with this topology's capabilities
|
||||
pub fn register_score<S>(&mut self, score: S)
|
||||
where
|
||||
S: Score<T> + 'static
|
||||
{
|
||||
println!("Registering score '{}' for topology '{}'", score.name(), self.topology.name());
|
||||
self.scores.push(Box::new(score));
|
||||
}
|
||||
|
||||
/// Apply all registered scores to the topology
|
||||
pub fn orchestrate(&self) -> Result<(), String> {
|
||||
println!("Orchestrating topology '{}'", self.topology.name());
|
||||
for score in &self.scores {
|
||||
score.apply(&self.topology)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Example Usage =====
|
||||
|
||||
fn main() {
|
||||
// Create a Linux host topology
|
||||
let linux_host = LinuxHostTopology::new(
|
||||
"dev-machine".to_string(),
|
||||
"localhost".to_string()
|
||||
);
|
||||
|
||||
// Create a maestro for the Linux host
|
||||
let mut linux_maestro = Maestro::new(linux_host);
|
||||
|
||||
// Register a command score that works with any topology having CommandCapability
|
||||
linux_maestro.register_score(CommandScore::new(
|
||||
"check-disk".to_string(),
|
||||
"df".to_string(),
|
||||
vec!["-h".to_string()]
|
||||
));
|
||||
|
||||
// This would fail to compile if we tried to register a K8sResourceScore
|
||||
// because LinuxHostTopology doesn't implement KubernetesCapability
|
||||
// linux_maestro.register_score(K8sResourceScore::new(...));
|
||||
|
||||
// Create a K3D topology which has both Command and Kubernetes capabilities
|
||||
let k3d_host = LinuxHostTopology::new(
|
||||
"k3d-host".to_string(),
|
||||
"localhost".to_string()
|
||||
);
|
||||
|
||||
let k3d_topology = K3DTopology::new(
|
||||
"dev-cluster".to_string(),
|
||||
k3d_host,
|
||||
"devcluster".to_string()
|
||||
);
|
||||
|
||||
// Create a maestro for the K3D topology
|
||||
let mut k3d_maestro = Maestro::new(k3d_topology);
|
||||
|
||||
// We can register both command scores and kubernetes scores
|
||||
k3d_maestro.register_score(CommandScore::new(
|
||||
"check-nodes".to_string(),
|
||||
"kubectl".to_string(),
|
||||
vec!["get".to_string(), "nodes".to_string()]
|
||||
));
|
||||
|
||||
k3d_maestro.register_score(K8sResourceScore::new(
|
||||
"deploy-nginx".to_string(),
|
||||
r#"
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: nginx
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: nginx
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: nginx
|
||||
spec:
|
||||
containers:
|
||||
- name: nginx
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- containerPort: 80
|
||||
"#.to_string()
|
||||
));
|
||||
|
||||
// Orchestrate both topologies
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
k3d_maestro.orchestrate().unwrap();
|
||||
}
|
||||
369
adr/003-abstractions/topology/src/main_gemini25pro.rs
Normal file
369
adr/003-abstractions/topology/src/main_gemini25pro.rs
Normal file
@@ -0,0 +1,369 @@
|
||||
// Import necessary items (though for this example, few are needed beyond std)
|
||||
use std::fmt;
|
||||
|
||||
// --- Error Handling ---
|
||||
// A simple error type for demonstration purposes. In a real app, use `thiserror` or `anyhow`.
|
||||
#[derive(Debug)]
|
||||
enum OrchestrationError {
|
||||
CommandFailed(String),
|
||||
KubeClientError(String),
|
||||
TopologySetupFailed(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for OrchestrationError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
OrchestrationError::CommandFailed(e) => write!(f, "Command execution failed: {}", e),
|
||||
OrchestrationError::KubeClientError(e) => write!(f, "Kubernetes client error: {}", e),
|
||||
OrchestrationError::TopologySetupFailed(e) => write!(f, "Topology setup failed: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for OrchestrationError {}
|
||||
|
||||
// Define a common Result type
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
// --- 1. Capability Specification (as Traits) ---
|
||||
|
||||
/// Capability trait representing the ability to run Linux commands.
|
||||
/// This follows the "Parse, Don't Validate" idea implicitly - if you have an object
|
||||
/// implementing this, you know you *can* run commands, no need to check later.
|
||||
trait LinuxOperations {
|
||||
fn run_command(&self, command: &str) -> Result<String>;
|
||||
}
|
||||
|
||||
/// A mock Kubernetes client trait for demonstration.
|
||||
trait KubeClient {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<()>;
|
||||
fn get_pods(&self, namespace: &str) -> Result<Vec<String>>;
|
||||
}
|
||||
|
||||
/// Mock implementation of a KubeClient.
|
||||
struct MockKubeClient {
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl KubeClient for MockKubeClient {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<()> {
|
||||
println!(
|
||||
"[{}] Applying Kubernetes manifest:\n---\n{}\n---",
|
||||
self.cluster_name, manifest
|
||||
);
|
||||
// Simulate success or failure
|
||||
if manifest.contains("invalid") {
|
||||
Err(Box::new(OrchestrationError::KubeClientError(
|
||||
"Invalid manifest content".into(),
|
||||
)))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn get_pods(&self, namespace: &str) -> Result<Vec<String>> {
|
||||
println!(
|
||||
"[{}] Getting pods in namespace '{}'",
|
||||
self.cluster_name, namespace
|
||||
);
|
||||
Ok(vec![
|
||||
format!("pod-a-12345-{}-{}", namespace, self.cluster_name),
|
||||
format!("pod-b-67890-{}-{}", namespace, self.cluster_name),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
/// Capability trait representing access to a Kubernetes cluster.
|
||||
/// This follows Rust Embedded WG's "Zero-Cost Abstractions" - the trait itself
|
||||
/// adds no runtime overhead, only compile-time structure.
|
||||
trait KubernetesCluster {
|
||||
// Provides access to a Kubernetes client instance.
|
||||
// Using `impl Trait` in return position for flexibility.
|
||||
fn get_kube_client(&self) -> Result<impl KubeClient>;
|
||||
}
|
||||
|
||||
// --- 2. Topology Implementations ---
|
||||
// Topologies implement the capabilities they provide.
|
||||
|
||||
/// Represents a basic Linux host.
|
||||
#[derive(Debug, Clone)]
|
||||
struct LinuxHostTopology {
|
||||
hostname: String,
|
||||
// In a real scenario: SSH connection details, etc.
|
||||
}
|
||||
|
||||
impl LinuxHostTopology {
|
||||
fn new(hostname: &str) -> Self {
|
||||
println!("Initializing LinuxHostTopology for {}", hostname);
|
||||
Self {
|
||||
hostname: hostname.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// LinuxHostTopology provides LinuxOperations capability.
|
||||
impl LinuxOperations for LinuxHostTopology {
|
||||
fn run_command(&self, command: &str) -> Result<String> {
|
||||
println!("[{}] Running command: '{}'", self.hostname, command);
|
||||
// Simulate command execution (e.g., via SSH)
|
||||
if command.starts_with("fail") {
|
||||
Err(Box::new(OrchestrationError::CommandFailed(format!(
|
||||
"Command '{}' failed",
|
||||
command
|
||||
))))
|
||||
} else {
|
||||
Ok(format!("Output of '{}' on {}", command, self.hostname))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a K3D (Kubernetes in Docker) cluster running on a host.
|
||||
#[derive(Debug, Clone)]
|
||||
struct K3DTopology {
|
||||
cluster_name: String,
|
||||
host_os: String, // Example: might implicitly run commands on the underlying host
|
||||
// In a real scenario: Kubeconfig path, Docker client, etc.
|
||||
}
|
||||
|
||||
impl K3DTopology {
|
||||
fn new(cluster_name: &str) -> Self {
|
||||
println!("Initializing K3DTopology for cluster {}", cluster_name);
|
||||
Self {
|
||||
cluster_name: cluster_name.to_string(),
|
||||
host_os: "Linux".to_string(), // Assume k3d runs on Linux for this example
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// K3DTopology provides KubernetesCluster capability.
|
||||
impl KubernetesCluster for K3DTopology {
|
||||
fn get_kube_client(&self) -> Result<impl KubeClient> {
|
||||
println!("[{}] Creating mock Kubernetes client", self.cluster_name);
|
||||
// In a real scenario, this would initialize a client using kubeconfig etc.
|
||||
Ok(MockKubeClient {
|
||||
cluster_name: self.cluster_name.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// K3DTopology *also* provides LinuxOperations (e.g., for running commands inside nodes or on the host managing k3d).
|
||||
impl LinuxOperations for K3DTopology {
|
||||
fn run_command(&self, command: &str) -> Result<String> {
|
||||
println!(
|
||||
"[{} on {} host] Running command: '{}'",
|
||||
self.cluster_name, self.host_os, command
|
||||
);
|
||||
// Simulate command execution (maybe `docker exec` or similar)
|
||||
if command.starts_with("fail") {
|
||||
Err(Box::new(OrchestrationError::CommandFailed(format!(
|
||||
"Command '{}' failed within k3d context",
|
||||
command
|
||||
))))
|
||||
} else {
|
||||
Ok(format!(
|
||||
"Output of '{}' within k3d cluster {}",
|
||||
command, self.cluster_name
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- 3. Score Implementations ---
|
||||
// Scores require capabilities via trait bounds on their execution logic.
|
||||
|
||||
/// Base trait for identifying scores. Could be empty or hold metadata.
|
||||
trait Score {
|
||||
fn name(&self) -> &'static str;
|
||||
// We don't put execute here, as its signature depends on required capabilities.
|
||||
}
|
||||
|
||||
/// A score that runs a shell command on a Linux host.
|
||||
#[derive(Debug)]
|
||||
struct CommandScore {
|
||||
command: String,
|
||||
}
|
||||
|
||||
impl Score for CommandScore {
|
||||
fn name(&self) -> &'static str {
|
||||
"CommandScore"
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
fn new(command: &str) -> Self {
|
||||
Self {
|
||||
command: command.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute method is generic over T, but requires T implements LinuxOperations.
|
||||
/// This follows the "Scores as Polymorphic Functions" idea.
|
||||
fn execute<T: LinuxOperations + ?Sized>(&self, topology: &T) -> Result<()> {
|
||||
println!("Executing Score: {}", Score::name(self));
|
||||
let output = topology.run_command(&self.command)?;
|
||||
println!("Command Score Output: {}", output);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A score that applies a Kubernetes resource manifest.
|
||||
#[derive(Debug)]
|
||||
struct K8sResourceScore {
|
||||
manifest_path: String, // Path or content
|
||||
}
|
||||
|
||||
impl Score for K8sResourceScore {
|
||||
fn name(&self) -> &'static str {
|
||||
"K8sResourceScore"
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sResourceScore {
|
||||
fn new(manifest_path: &str) -> Self {
|
||||
Self {
|
||||
manifest_path: manifest_path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute method requires T implements KubernetesCluster.
|
||||
fn execute<T: KubernetesCluster + ?Sized>(&self, topology: &T) -> Result<()> {
|
||||
println!("Executing Score: {}", Score::name(self));
|
||||
let client = topology.get_kube_client()?;
|
||||
let manifest_content = format!(
|
||||
"apiVersion: v1\nkind: Pod\nmetadata:\n name: my-pod-from-{}",
|
||||
self.manifest_path
|
||||
); // Simulate reading file
|
||||
client.apply_manifest(&manifest_content)?;
|
||||
println!(
|
||||
"K8s Resource Score applied manifest: {}",
|
||||
self.manifest_path
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- 4. Maestro (The Orchestrator) ---
|
||||
|
||||
// This version of Maestro uses a helper trait (`ScoreRunner`) to enable
|
||||
// storing heterogeneous scores while preserving compile-time checks.
|
||||
|
||||
/// A helper trait to erase the specific capability requirements *after*
|
||||
/// the compiler has verified them, allowing storage in a Vec.
|
||||
/// The verification happens in the blanket impls below.
|
||||
trait ScoreRunner<T> {
|
||||
// T is the concrete Topology type
|
||||
fn run(&self, topology: &T) -> Result<()>;
|
||||
fn name(&self) -> &'static str;
|
||||
}
|
||||
|
||||
// Blanket implementation: A CommandScore can be run on any Topology T
|
||||
// *if and only if* T implements LinuxOperations.
|
||||
// The compiler checks this bound when `add_score` is called.
|
||||
impl<T: LinuxOperations> ScoreRunner<T> for CommandScore {
|
||||
fn run(&self, topology: &T) -> Result<()> {
|
||||
self.execute(topology) // Call the capability-specific execute method
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
Score::name(self)
|
||||
}
|
||||
}
|
||||
|
||||
// Blanket implementation: A K8sResourceScore can be run on any Topology T
|
||||
// *if and only if* T implements KubernetesCluster.
|
||||
impl<T: KubernetesCluster> ScoreRunner<T> for K8sResourceScore {
|
||||
fn run(&self, topology: &T) -> Result<()> {
|
||||
self.execute(topology) // Call the capability-specific execute method
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
Score::name(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The Maestro orchestrator, strongly typed to a specific Topology `T`.
|
||||
struct Maestro<T> {
|
||||
topology: T,
|
||||
// Stores type-erased runners, but addition is type-safe.
|
||||
scores: Vec<Box<dyn ScoreRunner<T>>>,
|
||||
}
|
||||
|
||||
impl<T> Maestro<T> {
|
||||
/// Creates a new Maestro instance bound to a specific topology.
|
||||
fn new(topology: T) -> Self {
|
||||
println!("Maestro initialized.");
|
||||
Maestro {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a score to the Maestro.
|
||||
/// **Compile-time check happens here!**
|
||||
/// The `S: ScoreRunner<T>` bound ensures that the score `S` provides an
|
||||
/// implementation of `ScoreRunner` *for the specific topology type `T`*.
|
||||
/// The blanket impls above ensure this is only possible if `T` has the
|
||||
/// required capabilities for `S`.
|
||||
/// This directly follows the "Theoretical Example: The Compiler as an Ally".
|
||||
fn add_score<S>(&mut self, score: S)
|
||||
where
|
||||
S: Score + ScoreRunner<T> + 'static, // S must be runnable on *this* T
|
||||
{
|
||||
println!("Registering score: {}", Score::name(&score));
|
||||
self.scores.push(Box::new(score));
|
||||
}
|
||||
|
||||
/// Runs all registered scores sequentially on the topology.
|
||||
fn run_all(&self) -> Vec<Result<()>> {
|
||||
println!("\n--- Running all scores ---");
|
||||
self.scores
|
||||
.iter()
|
||||
.map(|score_runner| {
|
||||
println!("---");
|
||||
let result = score_runner.run(&self.topology);
|
||||
match &result {
|
||||
Ok(_) => println!("Score '{}' completed successfully.", score_runner.name()),
|
||||
Err(e) => eprintln!("Score '{}' failed: {}", score_runner.name(), e),
|
||||
}
|
||||
result
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
// --- 5. Example Usage ---
|
||||
|
||||
fn main() {
|
||||
println!("=== Scenario 1: Linux Host Topology ===");
|
||||
let linux_host = LinuxHostTopology::new("server1.example.com");
|
||||
let mut maestro_linux = Maestro::new(linux_host);
|
||||
|
||||
// Add scores compatible with LinuxHostTopology (which has LinuxOperations)
|
||||
maestro_linux.add_score(CommandScore::new("uname -a"));
|
||||
maestro_linux.add_score(CommandScore::new("ls -l /tmp"));
|
||||
|
||||
// *** Compile-time Error Example ***
|
||||
// Try adding a score that requires KubernetesCluster capability.
|
||||
// This line WILL NOT COMPILE because LinuxHostTopology does not implement KubernetesCluster,
|
||||
// therefore K8sResourceScore does not implement ScoreRunner<LinuxHostTopology>.
|
||||
// maestro_linux.add_score(K8sResourceScore::new("my-app.yaml"));
|
||||
// Uncomment the line above to see the compiler error! The error message will
|
||||
// likely point to the `ScoreRunner<LinuxHostTopology>` bound not being satisfied
|
||||
// for `K8sResourceScore`.
|
||||
|
||||
let results_linux = maestro_linux.run_all();
|
||||
println!("\nLinux Host Results: {:?}", results_linux);
|
||||
|
||||
println!("\n=== Scenario 2: K3D Topology ===");
|
||||
let k3d_cluster = K3DTopology::new("dev-cluster");
|
||||
let mut maestro_k3d = Maestro::new(k3d_cluster);
|
||||
|
||||
// Add scores compatible with K3DTopology (which has LinuxOperations AND KubernetesCluster)
|
||||
maestro_k3d.add_score(CommandScore::new("pwd")); // Uses LinuxOperations
|
||||
maestro_k3d.add_score(K8sResourceScore::new("nginx-deployment.yaml")); // Uses KubernetesCluster
|
||||
maestro_k3d.add_score(K8sResourceScore::new("invalid-service.yaml")); // Test error case
|
||||
maestro_k3d.add_score(CommandScore::new("fail please")); // Test error case
|
||||
|
||||
let results_k3d = maestro_k3d.run_all();
|
||||
println!("\nK3D Cluster Results: {:?}", results_k3d);
|
||||
|
||||
println!("\n=== Compile-Time Safety Demonstrated ===");
|
||||
println!("(Check the commented-out line in the code for the compile error example)");
|
||||
}
|
||||
492
adr/003-abstractions/topology/src/main_geminifail.rs
Normal file
492
adr/003-abstractions/topology/src/main_geminifail.rs
Normal file
@@ -0,0 +1,492 @@
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
use std::process::Command;
|
||||
pub trait Capability {}
|
||||
|
||||
pub trait CommandCapability: Capability {
|
||||
fn execute_command(&self, command: &str, args: &Vec<String>) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait KubernetesCapability: Capability {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String>;
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
pub trait Topology {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
pub trait Interpret<T: Topology> {
|
||||
fn execute(&self, topology: &T) -> Result<String, String>;
|
||||
}
|
||||
|
||||
// --- Score Definition Structs (Concrete) ---
|
||||
// CommandScore struct remains the same
|
||||
#[derive(Debug, Clone)] // Added Debug/Clone for easier handling
|
||||
pub struct CommandScore {
|
||||
name: String,
|
||||
command: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl CommandScore {
|
||||
pub fn new(name: String, command: String, args: Vec<String>) -> Self {
|
||||
Self { name, command, args }
|
||||
}
|
||||
}
|
||||
|
||||
// K8sResourceScore struct remains the same
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct K8sResourceScore {
|
||||
name: String,
|
||||
manifest: String,
|
||||
}
|
||||
|
||||
impl K8sResourceScore {
|
||||
pub fn new(name: String, manifest: String) -> Self {
|
||||
Self { name, manifest }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// --- Metadata / Base Score Trait (Non-Generic) ---
|
||||
// Trait for common info and enabling downcasting later if needed
|
||||
pub trait ScoreDefinition: Debug + Send + Sync {
|
||||
fn name(&self) -> &str;
|
||||
// Method to allow downcasting
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
// Optional: Could add methods for description, parameters etc.
|
||||
// fn description(&self) -> &str;
|
||||
|
||||
// Optional but potentially useful: A way to clone the definition
|
||||
fn box_clone(&self) -> Box<dyn ScoreDefinition>;
|
||||
}
|
||||
|
||||
// Implement Clone for Box<dyn ScoreDefinition>
|
||||
impl Clone for Box<dyn ScoreDefinition> {
|
||||
fn clone(&self) -> Self {
|
||||
self.box_clone()
|
||||
}
|
||||
}
|
||||
|
||||
// Implement ScoreDefinition for your concrete score types
|
||||
impl ScoreDefinition for CommandScore {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
fn box_clone(&self) -> Box<dyn ScoreDefinition> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl ScoreDefinition for K8sResourceScore {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
fn box_clone(&self) -> Box<dyn ScoreDefinition> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// --- Score Compatibility Trait (Generic over T) ---
|
||||
// This remains largely the same, ensuring compile-time checks
|
||||
pub trait Score<T: Topology>: ScoreDefinition {
|
||||
// No need for name() here, it's in ScoreDefinition
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String>;
|
||||
}
|
||||
|
||||
// --- Implementations of Score<T> (Crucial Link) ---
|
||||
|
||||
// CommandScore implements Score<T> for any T with CommandCapability
|
||||
impl<T> Score<T> for CommandScore
|
||||
where
|
||||
T: Topology + CommandCapability + 'static, // Added 'static bound often needed for Box<dyn>
|
||||
// Self: ScoreDefinition // This bound is implicit now
|
||||
{
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String> {
|
||||
// Pass necessary data from self to CommandInterpret
|
||||
Ok(Box::new(CommandInterpret {
|
||||
command: self.command.clone(),
|
||||
args: self.args.clone(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
// K8sResourceScore implements Score<T> for any T with KubernetesCapability
|
||||
impl<T> Score<T> for K8sResourceScore
|
||||
where
|
||||
T: Topology + KubernetesCapability + 'static,
|
||||
// Self: ScoreDefinition
|
||||
{
|
||||
fn compile(&self) -> Result<Box<dyn Interpret<T>>, String> {
|
||||
Ok(Box::new(K8sResourceInterpret {
|
||||
manifest: self.manifest.clone(), // Pass needed data
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// --- Interpret Implementations ---
|
||||
// Need to hold the actual data now
|
||||
|
||||
struct CommandInterpret {
|
||||
command: String,
|
||||
args: Vec<String>, // Or owned Strings if lifetime is tricky
|
||||
}
|
||||
|
||||
impl<'a, T> Interpret<T> for CommandInterpret
|
||||
where
|
||||
T: Topology + CommandCapability,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
// Now uses data stored in self
|
||||
topology.execute_command(&self.command, &self.args)
|
||||
}
|
||||
}
|
||||
|
||||
struct K8sResourceInterpret {
|
||||
manifest: String,
|
||||
}
|
||||
|
||||
impl<T: Topology + KubernetesCapability> Interpret<T> for K8sResourceInterpret {
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
topology.apply_manifest(&self.manifest)?;
|
||||
// apply_manifest returns Result<(), String>, adapt if needed
|
||||
Ok(format!("Applied manifest for {}", topology.name())) // Example success message
|
||||
}
|
||||
}
|
||||
|
||||
// --- Maestro ---
|
||||
// Maestro remains almost identical, leveraging the Score<T> bound
|
||||
pub struct Maestro<T: Topology> {
|
||||
topology: T,
|
||||
// Stores Score<T> trait objects, ensuring compatibility
|
||||
scores: Vec<Box<dyn Score<T>>>,
|
||||
}
|
||||
|
||||
impl<T: Topology + 'static> Maestro<T> { // Often need T: 'static here
|
||||
pub fn new(topology: T) -> Self {
|
||||
Self {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
// This method signature is key - it takes a concrete S
|
||||
// and the compiler checks if S implements Score<T>
|
||||
pub fn register_score<S>(&mut self, score: S) -> Result<(), String>
|
||||
where
|
||||
S: Score<T> + ScoreDefinition + Clone + 'static, // Ensure S is a Score for *this* T
|
||||
// We might need S: Clone if we want to store Box::new(score)
|
||||
// Alternatively, accept Box<dyn ScoreDefinition> and try to downcast/wrap
|
||||
{
|
||||
println!(
|
||||
"Registering score '{}' for topology '{}'",
|
||||
score.name(),
|
||||
self.topology.name()
|
||||
);
|
||||
// The compiler has already guaranteed that S implements Score<T>
|
||||
// We need to box it as dyn Score<T>
|
||||
self.scores.push(Box::new(score));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Alternative registration if you have Box<dyn ScoreDefinition>
|
||||
pub fn register_score_definition(&mut self, score_def: Box<dyn ScoreDefinition>) -> Result<(), String>
|
||||
where
|
||||
T: Topology + CommandCapability + KubernetesCapability + 'static, // Example: list all needed caps here, or use generics + downcasting
|
||||
{
|
||||
println!(
|
||||
"Attempting to register score '{}' for topology '{}'",
|
||||
score_def.name(),
|
||||
self.topology.name()
|
||||
);
|
||||
|
||||
// Downcast to check concrete type and then check compatibility
|
||||
if let Some(cs) = score_def.as_any().downcast_ref::<CommandScore>() {
|
||||
// Check if T satisfies CommandScore's requirements (CommandCapability)
|
||||
// This check is somewhat manual or needs restructuring if we avoid listing all caps
|
||||
// A simpler way is to just try to create the Box<dyn Score<T>>
|
||||
let boxed_score: Box<dyn Score<T>> = Box::new(cs.clone()); // This relies on the blanket impls
|
||||
self.scores.push(boxed_score);
|
||||
Ok(())
|
||||
} else if let Some(ks) = score_def.as_any().downcast_ref::<K8sResourceScore>() {
|
||||
// Check if T satisfies K8sResourceScore's requirements (KubernetesCapability)
|
||||
let boxed_score: Box<dyn Score<T>> = Box::new(ks.clone());
|
||||
self.scores.push(boxed_score);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Score '{}' is of an unknown type or incompatible", score_def.name()))
|
||||
}
|
||||
// This downcasting approach in Maestro slightly undermines the full compile-time
|
||||
// check unless designed carefully. The generic `register_score<S: Score<T>>` is safer.
|
||||
}
|
||||
|
||||
|
||||
pub fn orchestrate(&self) -> Result<(), String> {
|
||||
println!("Orchestrating topology '{}'", self.topology.name());
|
||||
for score in &self.scores {
|
||||
println!("Compiling score '{}'", score.name()); // Use name() from ScoreDefinition
|
||||
let interpret = score.compile()?;
|
||||
println!("Executing score '{}'", score.name());
|
||||
interpret.execute(&self.topology)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// --- TUI Example ---
|
||||
struct ScoreItem {
|
||||
// Holds the definition/metadata, NOT the Score<T> trait object
|
||||
definition: Box<dyn ScoreDefinition>,
|
||||
}
|
||||
|
||||
struct HarmonyTui {
|
||||
// List of available score *definitions*
|
||||
available_scores: Vec<ScoreItem>,
|
||||
// Example: Maybe maps topology names to Maestros
|
||||
// maestros: HashMap<String, Box<dyn Any>>, // Storing Maestros generically is another challenge!
|
||||
}
|
||||
|
||||
impl HarmonyTui {
|
||||
fn new() -> Self {
|
||||
HarmonyTui { available_scores: vec![] }
|
||||
}
|
||||
|
||||
fn add_available_score(&mut self, score_def: Box<dyn ScoreDefinition>) {
|
||||
self.available_scores.push(ScoreItem { definition: score_def });
|
||||
}
|
||||
|
||||
fn display_scores(&self) {
|
||||
println!("Available Scores:");
|
||||
for (i, item) in self.available_scores.iter().enumerate() {
|
||||
println!("{}: {}", i, item.definition.name());
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_score(&self, score: ScoreItem) {
|
||||
score.definition.
|
||||
|
||||
}
|
||||
|
||||
// Example: Function to add a selected score to a specific Maestro
|
||||
// This function would need access to the Maestros and handle the types
|
||||
fn add_selected_score_to_maestro<T>(
|
||||
&self,
|
||||
score_index: usize,
|
||||
maestro: &mut Maestro<T>
|
||||
) -> Result<(), String>
|
||||
where
|
||||
T: Topology + CommandCapability + KubernetesCapability + 'static, // Adjust bounds as needed
|
||||
{
|
||||
let score_item = self.available_scores.get(score_index)
|
||||
.ok_or("Invalid score index")?;
|
||||
|
||||
// We have Box<dyn ScoreDefinition>, need to add to Maestro<T>
|
||||
// Easiest is to downcast and call the generic register_score
|
||||
|
||||
if let Some(cs) = score_item.definition.as_any().downcast_ref::<CommandScore>() {
|
||||
// Compiler checks if CommandScore: Score<T> via register_score's bound
|
||||
maestro.register_score(cs.clone())?;
|
||||
Ok(())
|
||||
} else if let Some(ks) = score_item.definition.as_any().downcast_ref::<K8sResourceScore>() {
|
||||
// Compiler checks if K8sResourceScore: Score<T> via register_score's bound
|
||||
maestro.register_score(ks.clone())?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("Cannot add score '{}': Unknown type or check Maestro compatibility", score_item.definition.name()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct K3DTopology {
|
||||
name: String,
|
||||
linux_host: LinuxHostTopology,
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl Capability for K3DTopology {}
|
||||
|
||||
impl K3DTopology {
|
||||
pub fn new(name: String, linux_host: LinuxHostTopology, cluster_name: String) -> Self {
|
||||
Self {
|
||||
name,
|
||||
linux_host,
|
||||
cluster_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for K3DTopology {
|
||||
fn execute_command(&self, command: &str, args: &Vec<String>) -> Result<String, String> {
|
||||
self.linux_host.execute_command(command, args)
|
||||
}
|
||||
}
|
||||
|
||||
impl KubernetesCapability for K3DTopology {
|
||||
fn apply_manifest(&self, manifest: &str) -> Result<(), String> {
|
||||
println!("Applying manifest to K3D cluster '{}'", self.cluster_name);
|
||||
// Write manifest to a temporary file
|
||||
let temp_file = format!("/tmp/manifest-harmony-temp.yaml");
|
||||
|
||||
// Use the linux_host directly to avoid capability trait bounds
|
||||
self.linux_host
|
||||
.execute_command("bash", &Vec::from(["-c".to_string(), format!("cat > {}", temp_file)]))?;
|
||||
|
||||
// Apply with kubectl
|
||||
self.linux_host.execute_command("kubectl", &Vec::from([
|
||||
"--context".to_string(),
|
||||
format!("k3d-{}", self.cluster_name),
|
||||
"apply".to_string(),
|
||||
"-f".to_string(),
|
||||
temp_file.to_string(),
|
||||
]))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_resource(&self, resource_type: &str, name: &str) -> Result<String, String> {
|
||||
println!(
|
||||
"Getting resource {}/{} from K3D cluster '{}'",
|
||||
resource_type, name, self.cluster_name
|
||||
);
|
||||
self.linux_host.execute_command("kubectl", &Vec::from([
|
||||
"--context".to_string(),
|
||||
format!("k3d-{}", self.cluster_name),
|
||||
"get".to_string(),
|
||||
resource_type.to_string(),
|
||||
name.to_string(),
|
||||
"-o".to_string(),
|
||||
"yaml".to_string(),
|
||||
]))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct LinuxHostTopology {
|
||||
name: String,
|
||||
host: String,
|
||||
}
|
||||
impl Capability for LinuxHostTopology {}
|
||||
|
||||
impl LinuxHostTopology {
|
||||
pub fn new(name: String, host: String) -> Self {
|
||||
Self { name, host }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxHostTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
impl CommandCapability for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &str, args: &Vec<String>) -> Result<String, String> {
|
||||
println!("Executing on {}: {} {:?}", self.host, command, args);
|
||||
// In a real implementation, this would SSH to the host and execute the command
|
||||
let output = Command::new(command)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
if output.status.success() {
|
||||
Ok(String::from_utf8_lossy(&output.stdout).to_string())
|
||||
} else {
|
||||
Err(String::from_utf8_lossy(&output.stderr).to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// --- Main Function Adapated ---
|
||||
fn main() {
|
||||
// --- Linux Host ---
|
||||
let linux_host = LinuxHostTopology::new("dev-machine".to_string(), "localhost".to_string());
|
||||
let mut linux_maestro = Maestro::new(linux_host);
|
||||
|
||||
let df_score = CommandScore::new(
|
||||
"check-disk".to_string(),
|
||||
"df".to_string(),
|
||||
vec!["-h".to_string()],
|
||||
);
|
||||
|
||||
// Registration uses the generic method, compiler checks CommandScore: Score<LinuxHostTopology>
|
||||
linux_maestro.register_score(df_score.clone()).unwrap(); // clone needed if df_score used later
|
||||
|
||||
// --- K3D Host ---
|
||||
let k3d_host = LinuxHostTopology::new("k3d-host".to_string(), "localhost".to_string());
|
||||
let k3d_topology = K3DTopology::new(
|
||||
"dev-cluster".to_string(),
|
||||
k3d_host,
|
||||
"devcluster".to_string(),
|
||||
);
|
||||
let mut k3d_maestro = Maestro::new(k3d_topology);
|
||||
|
||||
let nodes_score = CommandScore::new(
|
||||
"check-nodes".to_string(),
|
||||
"kubectl".to_string(),
|
||||
vec!["get".to_string(), "nodes".to_string()],
|
||||
);
|
||||
let nginx_score = K8sResourceScore::new(
|
||||
"deploy-nginx".to_string(),
|
||||
// ... manifest string ...
|
||||
r#"..."#.to_string(),
|
||||
);
|
||||
|
||||
// Compiler checks CommandScore: Score<K3DTopology>
|
||||
k3d_maestro.register_score(nodes_score.clone()).unwrap();
|
||||
// Compiler checks K8sResourceScore: Score<K3DTopology>
|
||||
k3d_maestro.register_score(nginx_score.clone()).unwrap();
|
||||
|
||||
|
||||
// --- TUI Example Usage ---
|
||||
let mut tui = HarmonyTui::new();
|
||||
// Add score *definitions* to the TUI
|
||||
tui.add_available_score(Box::new(df_score));
|
||||
tui.add_available_score(Box::new(nodes_score));
|
||||
tui.add_available_score(Box::new(nginx_score));
|
||||
|
||||
tui.display_scores();
|
||||
|
||||
// Simulate user selecting score 0 (check-disk) and adding to linux_maestro
|
||||
match tui.add_selected_score_to_maestro(0, &mut linux_maestro) {
|
||||
Ok(_) => println!("Successfully registered check-disk to linux_maestro via TUI selection"),
|
||||
Err(e) => println!("Failed: {}", e), // Should succeed
|
||||
}
|
||||
|
||||
// Simulate user selecting score 2 (deploy-nginx) and adding to linux_maestro
|
||||
match tui.add_selected_score_to_maestro(2, &mut linux_maestro) {
|
||||
Ok(_) => println!("Successfully registered deploy-nginx to linux_maestro via TUI selection"), // Should fail!
|
||||
Err(e) => println!("Correctly failed to add deploy-nginx to linux_maestro: {}", e),
|
||||
// The failure happens inside add_selected_score_to_maestro because the
|
||||
// maestro.register_score(ks.clone()) call fails the trait bound check
|
||||
// K8sResourceScore: Score<LinuxHostTopology> is false.
|
||||
}
|
||||
|
||||
// Simulate user selecting score 2 (deploy-nginx) and adding to k3d_maestro
|
||||
match tui.add_selected_score_to_maestro(2, &mut k3d_maestro) {
|
||||
Ok(_) => println!("Successfully registered deploy-nginx to k3d_maestro via TUI selection"), // Should succeed
|
||||
Err(e) => println!("Failed: {}", e),
|
||||
}
|
||||
|
||||
// --- Orchestration ---
|
||||
println!("\n--- Orchestrating Linux Maestro ---");
|
||||
linux_maestro.orchestrate().unwrap();
|
||||
println!("\n--- Orchestrating K3D Maestro ---");
|
||||
k3d_maestro.orchestrate().unwrap();
|
||||
}
|
||||
129
adr/003-abstractions/topology/src/main_right.rs
Normal file
129
adr/003-abstractions/topology/src/main_right.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Capability Trait Hierarchy
|
||||
pub trait Capability {}
|
||||
|
||||
// Specific Capability Traits
|
||||
pub trait ShellAccess: Capability {}
|
||||
pub trait ContainerRuntime: Capability {}
|
||||
pub trait KubernetesAccess: Capability {}
|
||||
pub trait FileSystemAccess: Capability {}
|
||||
|
||||
// Topology Trait - Defines the core interface for infrastructure topologies
|
||||
pub trait Topology {
|
||||
type Capabilities: Capability;
|
||||
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
// Score Trait - Defines the core interface for infrastructure transformation
|
||||
pub trait Score {
|
||||
type RequiredCapabilities: Capability;
|
||||
type OutputTopology: Topology;
|
||||
|
||||
fn apply<T: Topology>(&self, topology: T) -> Result<Self::OutputTopology, String>;
|
||||
}
|
||||
|
||||
// Linux Host Topology
|
||||
pub struct LinuxHostTopology;
|
||||
|
||||
impl Topology for LinuxHostTopology {
|
||||
type Capabilities = dyn ShellAccess + FileSystemAccess;
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"Linux Host"
|
||||
}
|
||||
}
|
||||
|
||||
impl ShellAccess for LinuxHostTopology {}
|
||||
impl FileSystemAccess for LinuxHostTopology {}
|
||||
|
||||
// K3D Topology
|
||||
pub struct K3DTopology;
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
type Capabilities = dyn ContainerRuntime + KubernetesAccess + ShellAccess;
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"K3D Kubernetes Cluster"
|
||||
}
|
||||
}
|
||||
|
||||
impl ContainerRuntime for K3DTopology {}
|
||||
impl KubernetesAccess for K3DTopology {}
|
||||
impl ShellAccess for K3DTopology {}
|
||||
|
||||
// Command Score - A score that requires shell access
|
||||
pub struct CommandScore {
|
||||
command: String,
|
||||
}
|
||||
|
||||
impl Score for CommandScore {
|
||||
type RequiredCapabilities = dyn ShellAccess;
|
||||
type OutputTopology = LinuxHostTopology;
|
||||
|
||||
fn apply<T: Topology>(&self, _topology: T) -> Result<Self::OutputTopology, String>
|
||||
where
|
||||
T: ShellAccess
|
||||
{
|
||||
// Simulate command execution
|
||||
println!("Executing command: {}", self.command);
|
||||
Ok(LinuxHostTopology)
|
||||
}
|
||||
}
|
||||
|
||||
// Kubernetes Resource Score
|
||||
pub struct K8sResourceScore {
|
||||
resource_definition: String,
|
||||
}
|
||||
|
||||
impl Score for K8sResourceScore {
|
||||
type RequiredCapabilities = dyn KubernetesAccess;
|
||||
type OutputTopology = K3DTopology;
|
||||
|
||||
fn apply<T: Topology>(&self, _topology: T) -> Result<Self::OutputTopology, String>
|
||||
where
|
||||
T: dyn KubernetesAccess
|
||||
{
|
||||
// Simulate Kubernetes resource application
|
||||
println!("Applying K8s resource: {}", self.resource_definition);
|
||||
Ok(K3DTopology)
|
||||
}
|
||||
}
|
||||
|
||||
// Maestro - The orchestration coordinator
|
||||
pub struct Maestro;
|
||||
|
||||
impl Maestro {
|
||||
// Type-safe score application
|
||||
pub fn apply_score<T, S>(topology: T, score: S) -> Result<S::OutputTopology, String>
|
||||
where
|
||||
T: Topology,
|
||||
S: Score,
|
||||
T: S::RequiredCapabilities
|
||||
{
|
||||
score.apply(topology)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Example usage demonstrating type-driven design
|
||||
let linux_host = LinuxHostTopology;
|
||||
let k3d_cluster = K3DTopology;
|
||||
|
||||
// Command score on Linux host
|
||||
let command_score = CommandScore {
|
||||
command: "echo 'Hello, World!'".to_string(),
|
||||
};
|
||||
|
||||
let result = Maestro::apply_score(linux_host, command_score)
|
||||
.expect("Command score application failed");
|
||||
|
||||
// K8s resource score on K3D cluster
|
||||
let k8s_score = K8sResourceScore {
|
||||
resource_definition: "apiVersion: v1\nkind: Pod\n...".to_string(),
|
||||
};
|
||||
|
||||
let k8s_result = Maestro::apply_score(k3d_cluster, k8s_score)
|
||||
.expect("K8s resource score application failed");
|
||||
}
|
||||
155
adr/003-abstractions/topology/src/main_v1.rs
Normal file
155
adr/003-abstractions/topology/src/main_v1.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
mod main_right;
|
||||
mod main_claude;
|
||||
// Capability Traits
|
||||
|
||||
trait Capability {}
|
||||
|
||||
trait LinuxOperations: Capability {
|
||||
fn execute_command(&self, command: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
trait KubernetesOperations: Capability {
|
||||
fn create_resource(&self, resource: &str) -> Result<String, String>;
|
||||
fn delete_resource(&self, resource: &str) -> Result<String, String>;
|
||||
}
|
||||
|
||||
// Topology Implementations
|
||||
|
||||
struct LinuxHostTopology;
|
||||
|
||||
impl LinuxOperations for LinuxHostTopology {
|
||||
fn execute_command(&self, command: &str) -> Result<String, String> {
|
||||
// Implementation for executing commands on a Linux host
|
||||
Ok(format!("Executed command: {}", command))
|
||||
}
|
||||
}
|
||||
|
||||
impl Capability for LinuxHostTopology {}
|
||||
|
||||
struct K3DTopology;
|
||||
|
||||
impl KubernetesOperations for K3DTopology {
|
||||
fn create_resource(&self, resource: &str) -> Result<String, String> {
|
||||
// Implementation for creating Kubernetes resources in K3D
|
||||
Ok(format!("Created resource: {}", resource))
|
||||
}
|
||||
|
||||
fn delete_resource(&self, resource: &str) -> Result<String, String> {
|
||||
// Implementation for deleting Kubernetes resources in K3D
|
||||
Ok(format!("Deleted resource: {}", resource))
|
||||
}
|
||||
}
|
||||
|
||||
impl Capability for K3DTopology {}
|
||||
|
||||
// Score Implementations
|
||||
|
||||
struct K8sResourceScore {
|
||||
resource: String,
|
||||
}
|
||||
|
||||
impl<T> Score<T> for K8sResourceScore
|
||||
where
|
||||
T: KubernetesOperations,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
topology.create_resource(&self.resource)
|
||||
}
|
||||
}
|
||||
|
||||
struct CommandScore {
|
||||
command: String,
|
||||
}
|
||||
|
||||
impl<T> Score<T> for CommandScore
|
||||
where
|
||||
T: LinuxOperations + 'static,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String> {
|
||||
topology.execute_command(&self.command)
|
||||
}
|
||||
}
|
||||
|
||||
// Score Trait
|
||||
|
||||
trait Score<T>
|
||||
where
|
||||
T: Capability + 'static,
|
||||
{
|
||||
fn execute(&self, topology: &T) -> Result<String, String>;
|
||||
}
|
||||
|
||||
// Maestro Implementation
|
||||
|
||||
struct Maestro {
|
||||
scores: Vec<Box<dyn Score<Box<dyn Capability>>>>,
|
||||
}
|
||||
|
||||
impl Maestro {
|
||||
fn new() -> Self {
|
||||
Maestro { scores: Vec::new() }
|
||||
}
|
||||
|
||||
fn register_score<T>(&mut self, score: Box<T>)
|
||||
where
|
||||
T: Score<Box<dyn Capability>> + 'static,
|
||||
{
|
||||
self.scores.push(Box::new(score));
|
||||
}
|
||||
|
||||
fn execute_scores<T>(&self, topology: &T) -> Result<Vec<String>, String>
|
||||
where
|
||||
T: Capability + 'static,
|
||||
{
|
||||
let mut results = Vec::new();
|
||||
for score in &self.scores {
|
||||
if let Some(score) = score.as_any().downcast_ref::<Box<dyn Score<T>>>() {
|
||||
results.push(score.execute(topology)?);
|
||||
}
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
}
|
||||
|
||||
// Helper trait for downcasting
|
||||
|
||||
trait AsAny {
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
impl<T: 'static> AsAny for T {
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// Main Function
|
||||
|
||||
fn main() {
|
||||
let mut maestro = Maestro::new();
|
||||
|
||||
let k8s_score = K8sResourceScore {
|
||||
resource: "deployment.yaml".to_string(),
|
||||
};
|
||||
maestro.register_score(k8s_score);
|
||||
|
||||
let command_score = CommandScore {
|
||||
command: "ls -l".to_string(),
|
||||
};
|
||||
maestro.register_score(command_score);
|
||||
|
||||
let linux_topology = LinuxHostTopology;
|
||||
let k3d_topology = K3DTopology;
|
||||
|
||||
let linux_results = maestro.execute_scores(&linux_topology).unwrap();
|
||||
println!("Linux Topology Results:");
|
||||
for result in linux_results {
|
||||
println!("{}", result);
|
||||
}
|
||||
|
||||
let k3d_results = maestro.execute_scores(&k3d_topology).unwrap();
|
||||
println!("K3D Topology Results:");
|
||||
for result in k3d_results {
|
||||
println!("{}", result);
|
||||
}
|
||||
}
|
||||
9
adr/003-abstractions/topology2/Cargo.toml
Normal file
9
adr/003-abstractions/topology2/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "example-topology2"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
183
adr/003-abstractions/topology2/src/main.rs
Normal file
183
adr/003-abstractions/topology2/src/main.rs
Normal file
@@ -0,0 +1,183 @@
|
||||
// Clean capability-based design using type parameters
|
||||
|
||||
trait Capability {}
|
||||
|
||||
trait K8sCapability: Capability {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str);
|
||||
fn execute_kubectl(&self, command: &str) -> String;
|
||||
}
|
||||
|
||||
trait LinuxCapability: Capability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]);
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
trait LoadBalancerCapability: Capability {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16);
|
||||
fn get_load_balancer_status(&self) -> String;
|
||||
}
|
||||
|
||||
// Score trait with capability type parameter
|
||||
trait Score<C: ?Sized> {
|
||||
fn execute(&self, capability: &C) -> String;
|
||||
}
|
||||
|
||||
// Topology implementations with marker trait
|
||||
trait Topology {}
|
||||
|
||||
struct K3DTopology {}
|
||||
impl Topology for K3DTopology {}
|
||||
impl Capability for K3DTopology {}
|
||||
impl K8sCapability for K3DTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
todo!()
|
||||
}
|
||||
// Implementation...
|
||||
}
|
||||
|
||||
struct LinuxTopology {}
|
||||
impl Topology for LinuxTopology {}
|
||||
impl Capability for LinuxTopology {}
|
||||
impl LinuxCapability for LinuxTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
todo!()
|
||||
}
|
||||
// Implementation...
|
||||
}
|
||||
|
||||
struct OKDHaClusterTopology {}
|
||||
impl Topology for OKDHaClusterTopology {}
|
||||
impl Capability for OKDHaClusterTopology {}
|
||||
impl K8sCapability for OKDHaClusterTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
todo!()
|
||||
}
|
||||
// Implementation...
|
||||
}
|
||||
impl LinuxCapability for OKDHaClusterTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
todo!()
|
||||
}
|
||||
// Implementation...
|
||||
}
|
||||
impl LoadBalancerCapability for OKDHaClusterTopology {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn get_load_balancer_status(&self) -> String {
|
||||
todo!()
|
||||
}
|
||||
// Implementation...
|
||||
}
|
||||
|
||||
// Score implementations
|
||||
struct LAMPScore {}
|
||||
impl Score<dyn K8sCapability> for LAMPScore {
|
||||
fn execute(&self, capability: &dyn K8sCapability) -> String {
|
||||
todo!()
|
||||
// Implementation...
|
||||
}
|
||||
}
|
||||
|
||||
struct BinaryScore {}
|
||||
impl Score<dyn LinuxCapability> for BinaryScore {
|
||||
fn execute(&self, capability: &dyn LinuxCapability) -> String {
|
||||
todo!()
|
||||
// Implementation...
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadBalancerScore {}
|
||||
impl Score<dyn LoadBalancerCapability> for LoadBalancerScore {
|
||||
fn execute(&self, capability: &dyn LoadBalancerCapability) -> String {
|
||||
todo!()
|
||||
// Implementation...
|
||||
}
|
||||
}
|
||||
|
||||
// Generic Maestro
|
||||
struct Maestro<T> {
|
||||
topology: T,
|
||||
scores: Vec<Box<dyn FnMut(&T) -> String>>,
|
||||
}
|
||||
|
||||
impl<T: 'static> Maestro<T> {
|
||||
fn new(topology: T) -> Self {
|
||||
Self {
|
||||
topology,
|
||||
scores: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn interpret_all(&mut self) -> Vec<String> {
|
||||
self.scores.iter_mut()
|
||||
.map(|score| score(&self.topology))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
// Capability-specific extensions
|
||||
impl<T: K8sCapability + 'static> Maestro<T> {
|
||||
fn register_k8s_score<S: Score<dyn K8sCapability> + 'static>(&mut self, score: S) {
|
||||
let score_box = Box::new(move |topology: &T| {
|
||||
score.execute(topology as &dyn K8sCapability)
|
||||
});
|
||||
self.scores.push(score_box);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: LinuxCapability + 'static> Maestro<T> {
|
||||
fn register_linux_score<S: Score<dyn LinuxCapability> + 'static>(&mut self, score: S) {
|
||||
let score_box = Box::new(move |topology: &T| {
|
||||
score.execute(topology as &dyn LinuxCapability)
|
||||
});
|
||||
self.scores.push(score_box);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: LoadBalancerCapability + 'static> Maestro<T> {
|
||||
fn register_lb_score<S: Score<dyn LoadBalancerCapability> + 'static>(&mut self, score: S) {
|
||||
let score_box = Box::new(move |topology: &T| {
|
||||
score.execute(topology as &dyn LoadBalancerCapability)
|
||||
});
|
||||
self.scores.push(score_box);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Example usage
|
||||
let k3d = K3DTopology {};
|
||||
let mut k3d_maestro = Maestro::new(k3d);
|
||||
|
||||
// These will compile because K3D implements K8sCapability
|
||||
k3d_maestro.register_k8s_score(LAMPScore {});
|
||||
|
||||
// This would not compile because K3D doesn't implement LoadBalancerCapability
|
||||
// k3d_maestro.register_lb_score(LoadBalancerScore {});
|
||||
|
||||
let linux = LinuxTopology {};
|
||||
let mut linux_maestro = Maestro::new(linux);
|
||||
|
||||
// This will compile because Linux implements LinuxCapability
|
||||
linux_maestro.register_linux_score(BinaryScore {});
|
||||
|
||||
// This would not compile because Linux doesn't implement K8sCapability
|
||||
// linux_maestro.register_k8s_score(LAMPScore {});
|
||||
}
|
||||
324
adr/003-abstractions/topology2/src/main_capabilities.rs
Normal file
324
adr/003-abstractions/topology2/src/main_capabilities.rs
Normal file
@@ -0,0 +1,324 @@
|
||||
fn main() {
|
||||
// Create various topologies
|
||||
let okd_topology = OKDHaClusterTopology::new();
|
||||
let k3d_topology = K3DTopology::new();
|
||||
let linux_topology = LinuxTopology::new();
|
||||
|
||||
// Create scores
|
||||
let lamp_score = LAMPScore::new("MySQL 8.0", "PHP 8.1", "Apache 2.4");
|
||||
let binary_score = BinaryScore::new("https://example.com/binary", vec!["--arg1", "--arg2"]);
|
||||
let load_balancer_score = LoadBalancerScore::new(vec!["service1", "service2"], 80);
|
||||
|
||||
// Example 1: Running LAMP stack on OKD
|
||||
println!("\n=== Deploying LAMP stack on OKD cluster ===");
|
||||
lamp_score.execute(&okd_topology);
|
||||
|
||||
// Example 2: Running LAMP stack on K3D
|
||||
println!("\n=== Deploying LAMP stack on K3D cluster ===");
|
||||
lamp_score.execute(&k3d_topology);
|
||||
|
||||
// Example 3: Running binary on Linux host
|
||||
println!("\n=== Running binary on Linux host ===");
|
||||
binary_score.execute(&linux_topology);
|
||||
|
||||
// Example 4: Running binary on OKD (which can also run Linux commands)
|
||||
println!("\n=== Running binary on OKD host ===");
|
||||
binary_score.execute(&okd_topology);
|
||||
|
||||
// Example 5: Load balancer configuration on OKD
|
||||
println!("\n=== Configuring load balancer on OKD ===");
|
||||
load_balancer_score.execute(&okd_topology);
|
||||
|
||||
// The following would not compile:
|
||||
// load_balancer_score.execute(&k3d_topology); // K3D doesn't implement LoadBalancerCapability
|
||||
// lamp_score.execute(&linux_topology); // Linux doesn't implement K8sCapability
|
||||
}
|
||||
|
||||
// Base Topology trait
|
||||
trait Topology {
|
||||
fn name(&self) -> &str;
|
||||
}
|
||||
|
||||
// Define capabilities
|
||||
trait K8sCapability {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str);
|
||||
fn execute_kubectl(&self, command: &str) -> String;
|
||||
}
|
||||
|
||||
trait OKDCapability: K8sCapability {
|
||||
fn execute_oc(&self, command: &str) -> String;
|
||||
}
|
||||
|
||||
trait LinuxCapability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> String;
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
trait LoadBalancerCapability {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16);
|
||||
fn get_load_balancer_status(&self) -> String;
|
||||
}
|
||||
|
||||
trait FirewallCapability {
|
||||
fn open_port(&self, port: u16, protocol: &str);
|
||||
fn close_port(&self, port: u16, protocol: &str);
|
||||
}
|
||||
|
||||
trait RouterCapability {
|
||||
fn configure_route(&self, service: &str, hostname: &str);
|
||||
}
|
||||
|
||||
// Topology implementations
|
||||
struct OKDHaClusterTopology {
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl OKDHaClusterTopology {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
cluster_name: "okd-ha-cluster".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for OKDHaClusterTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.cluster_name
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sCapability for OKDHaClusterTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
println!("Deploying K8s resource on OKD cluster: {}", resource_yaml);
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
println!("Executing kubectl command on OKD cluster: {}", command);
|
||||
"kubectl command output".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl OKDCapability for OKDHaClusterTopology {
|
||||
fn execute_oc(&self, command: &str) -> String {
|
||||
println!("Executing oc command on OKD cluster: {}", command);
|
||||
"oc command output".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl LinuxCapability for OKDHaClusterTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> String {
|
||||
println!(
|
||||
"Executing command '{}' with args {:?} on OKD node",
|
||||
command, args
|
||||
);
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
println!(
|
||||
"Downloading file from {} to {} on OKD node",
|
||||
url, destination
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadBalancerCapability for OKDHaClusterTopology {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16) {
|
||||
println!(
|
||||
"Configuring load balancer for services {:?} on port {} in OKD",
|
||||
services, port
|
||||
);
|
||||
}
|
||||
|
||||
fn get_load_balancer_status(&self) -> String {
|
||||
"OKD Load Balancer: HEALTHY".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl FirewallCapability for OKDHaClusterTopology {
|
||||
fn open_port(&self, port: u16, protocol: &str) {
|
||||
println!(
|
||||
"Opening port {} with protocol {} on OKD firewall",
|
||||
port, protocol
|
||||
);
|
||||
}
|
||||
|
||||
fn close_port(&self, port: u16, protocol: &str) {
|
||||
println!(
|
||||
"Closing port {} with protocol {} on OKD firewall",
|
||||
port, protocol
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl RouterCapability for OKDHaClusterTopology {
|
||||
fn configure_route(&self, service: &str, hostname: &str) {
|
||||
println!(
|
||||
"Configuring route for service {} with hostname {} on OKD",
|
||||
service, hostname
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct K3DTopology {
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl K3DTopology {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
cluster_name: "k3d-local".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.cluster_name
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sCapability for K3DTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
println!("Deploying K8s resource on K3D cluster: {}", resource_yaml);
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
println!("Executing kubectl command on K3D cluster: {}", command);
|
||||
"kubectl command output from K3D".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
struct LinuxTopology {
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
impl LinuxTopology {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
hostname: "linux-host".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.hostname
|
||||
}
|
||||
}
|
||||
|
||||
impl LinuxCapability for LinuxTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) -> String {
|
||||
println!(
|
||||
"Executing command '{}' with args {:?} on Linux host",
|
||||
command, args
|
||||
);
|
||||
todo!()
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
println!(
|
||||
"Downloading file from {} to {} on Linux host",
|
||||
url, destination
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Score implementations
|
||||
struct LAMPScore {
|
||||
mysql_version: String,
|
||||
php_version: String,
|
||||
apache_version: String,
|
||||
}
|
||||
|
||||
impl LAMPScore {
|
||||
fn new(mysql_version: &str, php_version: &str, apache_version: &str) -> Self {
|
||||
Self {
|
||||
mysql_version: mysql_version.to_string(),
|
||||
php_version: php_version.to_string(),
|
||||
apache_version: apache_version.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute<T: K8sCapability>(&self, topology: &T) {
|
||||
// Deploy MySQL
|
||||
topology.deploy_k8s_resource("mysql-deployment.yaml");
|
||||
|
||||
// Deploy PHP
|
||||
topology.deploy_k8s_resource("php-deployment.yaml");
|
||||
|
||||
// Deploy Apache
|
||||
topology.deploy_k8s_resource("apache-deployment.yaml");
|
||||
|
||||
// Create service
|
||||
topology.deploy_k8s_resource("lamp-service.yaml");
|
||||
|
||||
// Check deployment
|
||||
let status = topology.execute_kubectl("get pods -l app=lamp");
|
||||
println!("LAMP deployment status: {}", status);
|
||||
}
|
||||
}
|
||||
|
||||
struct BinaryScore {
|
||||
url: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl BinaryScore {
|
||||
fn new(url: &str, args: Vec<&str>) -> Self {
|
||||
Self {
|
||||
url: url.to_string(),
|
||||
args: args.iter().map(|s| s.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute<T: LinuxCapability>(&self, topology: &T) {
|
||||
let destination = "/tmp/binary";
|
||||
|
||||
match topology.download_file(&self.url, destination) {
|
||||
Ok(_) => {
|
||||
println!("Binary downloaded successfully");
|
||||
|
||||
// Convert args to slice of &str
|
||||
let args: Vec<&str> = self.args.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
// Execute the binary
|
||||
topology.execute_command(destination, &args);
|
||||
println!("Binary execution completed");
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Failed to download binary: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadBalancerScore {
|
||||
services: Vec<String>,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl LoadBalancerScore {
|
||||
fn new(services: Vec<&str>, port: u16) -> Self {
|
||||
Self {
|
||||
services: services.iter().map(|s| s.to_string()).collect(),
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
fn execute<T: LoadBalancerCapability>(&self, topology: &T) {
|
||||
println!("Configuring load balancer for services");
|
||||
|
||||
// Convert services to slice of &str
|
||||
let services: Vec<&str> = self.services.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
// Configure load balancer
|
||||
topology.configure_load_balancer(&services, self.port);
|
||||
|
||||
// Check status
|
||||
let status = topology.get_load_balancer_status();
|
||||
println!("Load balancer status: {}", status);
|
||||
}
|
||||
}
|
||||
34
adr/003-abstractions/topology2/src/main_v1.rs
Normal file
34
adr/003-abstractions/topology2/src/main_v1.rs
Normal file
@@ -0,0 +1,34 @@
|
||||
fn main() {}
|
||||
|
||||
trait Topology {}
|
||||
|
||||
struct DummyTopology {}
|
||||
|
||||
impl Topology for DummyTopology {}
|
||||
|
||||
impl Topology for LampTopology {}
|
||||
|
||||
struct LampTopology {}
|
||||
|
||||
struct Maestro {
|
||||
topology: Box<dyn Topology>,
|
||||
}
|
||||
|
||||
trait Score {
|
||||
type Topology: Topology;
|
||||
fn execute(&self, topology: &Self::Topology);
|
||||
}
|
||||
|
||||
struct K8sScore {}
|
||||
impl Score for K8sScore {
|
||||
type Topology = LampTopology;
|
||||
fn execute(&self, topology: &Box<dyn Self::Topology>) {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
|
||||
impl Maestro {
|
||||
pub fn execute<T: Topology>(&self, score: Box<dyn Score<Topology = T>>) {
|
||||
score.execute(&self.topology);
|
||||
}
|
||||
}
|
||||
76
adr/003-abstractions/topology2/src/main_v2.rs
Normal file
76
adr/003-abstractions/topology2/src/main_v2.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
fn main() {
|
||||
// Example usage
|
||||
let lamp_topology = LampTopology {};
|
||||
let k8s_score = K8sScore {};
|
||||
let docker_topology = DockerTopology{};
|
||||
|
||||
// Type-safe execution
|
||||
let maestro = Maestro::new(Box::new(docker_topology));
|
||||
maestro.execute(&k8s_score); // This will work
|
||||
|
||||
// This would fail at compile time if we tried:
|
||||
// let dummy_topology = DummyTopology {};
|
||||
// let maestro = Maestro::new(Box::new(dummy_topology));
|
||||
// maestro.execute(&k8s_score); // Error: expected LampTopology, found DummyTopology
|
||||
}
|
||||
|
||||
// Base trait for all topologies
|
||||
trait Topology {
|
||||
// Common topology methods could go here
|
||||
fn topology_type(&self) -> &str;
|
||||
}
|
||||
|
||||
struct DummyTopology {}
|
||||
impl Topology for DummyTopology {
|
||||
fn topology_type(&self) -> &str { "Dummy" }
|
||||
}
|
||||
|
||||
struct LampTopology {}
|
||||
impl Topology for LampTopology {
|
||||
fn topology_type(&self) -> &str { "LAMP" }
|
||||
}
|
||||
|
||||
struct DockerTopology {}
|
||||
|
||||
impl Topology for DockerTopology {
|
||||
fn topology_type(&self) -> &str {
|
||||
todo!("DockerTopology")
|
||||
}
|
||||
}
|
||||
|
||||
// The Score trait with an associated type for the required topology
|
||||
trait Score {
|
||||
type RequiredTopology: Topology + ?Sized;
|
||||
fn execute(&self, topology: &Self::RequiredTopology);
|
||||
fn score_type(&self) -> &str;
|
||||
}
|
||||
|
||||
// A score that requires LampTopology
|
||||
struct K8sScore {}
|
||||
impl Score for K8sScore {
|
||||
type RequiredTopology = DockerTopology;
|
||||
|
||||
fn execute(&self, topology: &Self::RequiredTopology) {
|
||||
println!("Executing K8sScore on {} topology", topology.topology_type());
|
||||
// Implementation details...
|
||||
}
|
||||
|
||||
fn score_type(&self) -> &str { "K8s" }
|
||||
}
|
||||
|
||||
// A generic maestro that can work with any topology type
|
||||
struct Maestro<T: Topology + ?Sized> {
|
||||
topology: Box<T>,
|
||||
}
|
||||
|
||||
impl<T: Topology + ?Sized> Maestro<T> {
|
||||
pub fn new(topology: Box<T>) -> Self {
|
||||
Maestro { topology }
|
||||
}
|
||||
|
||||
// Execute a score that requires this specific topology type
|
||||
pub fn execute<S: Score<RequiredTopology = T>>(&self, score: &S) {
|
||||
println!("Maestro executing {} score", score.score_type());
|
||||
score.execute(&*self.topology);
|
||||
}
|
||||
}
|
||||
360
adr/003-abstractions/topology2/src/main_v4.rs
Normal file
360
adr/003-abstractions/topology2/src/main_v4.rs
Normal file
@@ -0,0 +1,360 @@
|
||||
fn main() {
|
||||
// Create topologies
|
||||
let okd_topology = OKDHaClusterTopology::new();
|
||||
let k3d_topology = K3DTopology::new();
|
||||
let linux_topology = LinuxTopology::new();
|
||||
|
||||
// Create scores - boxing them as trait objects for dynamic dispatch
|
||||
let scores: Vec<Box<dyn Score>> = vec![
|
||||
Box::new(LAMPScore::new("MySQL 8.0", "PHP 8.1", "Apache 2.4")),
|
||||
Box::new(BinaryScore::new("https://example.com/binary", vec!["--arg1", "--arg2"])),
|
||||
Box::new(LoadBalancerScore::new(vec!["service1", "service2"], 80)),
|
||||
];
|
||||
|
||||
// Running scores on OKD topology (which has all capabilities)
|
||||
println!("\n=== Running all scores on OKD HA Cluster ===");
|
||||
for score in &scores {
|
||||
match score.execute(&okd_topology) {
|
||||
Ok(result) => println!("Score executed successfully: {}", result),
|
||||
Err(e) => println!("Failed to execute score: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
// Running scores on K3D topology (only has K8s capability)
|
||||
println!("\n=== Running scores on K3D Cluster ===");
|
||||
for score in &scores {
|
||||
match score.execute(&k3d_topology) {
|
||||
Ok(result) => println!("Score executed successfully: {}", result),
|
||||
Err(e) => println!("Failed to execute score: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
// Running scores on Linux topology (only has Linux capability)
|
||||
println!("\n=== Running scores on Linux Host ===");
|
||||
for score in &scores {
|
||||
match score.execute(&linux_topology) {
|
||||
Ok(result) => println!("Score executed successfully: {}", result),
|
||||
Err(e) => println!("Failed to execute score: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Base Topology trait
|
||||
trait Topology: Any {
|
||||
fn name(&self) -> &str;
|
||||
|
||||
// This method allows us to get type information at runtime
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
// Use Any trait for runtime type checking
|
||||
use std::any::Any;
|
||||
|
||||
// Define capabilities
|
||||
trait K8sCapability {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str);
|
||||
fn execute_kubectl(&self, command: &str) -> String;
|
||||
}
|
||||
|
||||
trait OKDCapability: K8sCapability {
|
||||
fn execute_oc(&self, command: &str) -> String;
|
||||
}
|
||||
|
||||
trait LinuxCapability {
|
||||
fn execute_command(&self, command: &str, args: &[&str]);
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
trait LoadBalancerCapability {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16);
|
||||
fn get_load_balancer_status(&self) -> String;
|
||||
}
|
||||
|
||||
// Base Score trait with dynamic dispatch
|
||||
trait Score {
|
||||
// Generic execute method that takes any topology
|
||||
fn execute(&self, topology: &dyn Topology) -> Result<String, String>;
|
||||
|
||||
// Optional method to get score type for better error messages
|
||||
fn score_type(&self) -> &str;
|
||||
}
|
||||
|
||||
// Topology implementations
|
||||
struct OKDHaClusterTopology {
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl OKDHaClusterTopology {
|
||||
fn new() -> Self {
|
||||
Self { cluster_name: "okd-ha-cluster".to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for OKDHaClusterTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.cluster_name
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sCapability for OKDHaClusterTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
println!("Deploying K8s resource on OKD cluster: {}", resource_yaml);
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
println!("Executing kubectl command on OKD cluster: {}", command);
|
||||
"kubectl command output".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl OKDCapability for OKDHaClusterTopology {
|
||||
fn execute_oc(&self, command: &str) -> String {
|
||||
println!("Executing oc command on OKD cluster: {}", command);
|
||||
"oc command output".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl LinuxCapability for OKDHaClusterTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) {
|
||||
println!("Executing command '{}' with args {:?} on OKD node", command, args);
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
println!("Downloading file from {} to {} on OKD node", url, destination);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl LoadBalancerCapability for OKDHaClusterTopology {
|
||||
fn configure_load_balancer(&self, services: &[&str], port: u16) {
|
||||
println!("Configuring load balancer for services {:?} on port {} in OKD", services, port);
|
||||
}
|
||||
|
||||
fn get_load_balancer_status(&self) -> String {
|
||||
"OKD Load Balancer: HEALTHY".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
struct K3DTopology {
|
||||
cluster_name: String,
|
||||
}
|
||||
|
||||
impl K3DTopology {
|
||||
fn new() -> Self {
|
||||
Self { cluster_name: "k3d-local".to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for K3DTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.cluster_name
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl K8sCapability for K3DTopology {
|
||||
fn deploy_k8s_resource(&self, resource_yaml: &str) {
|
||||
println!("Deploying K8s resource on K3D cluster: {}", resource_yaml);
|
||||
}
|
||||
|
||||
fn execute_kubectl(&self, command: &str) -> String {
|
||||
println!("Executing kubectl command on K3D cluster: {}", command);
|
||||
"kubectl command output from K3D".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
struct LinuxTopology {
|
||||
hostname: String,
|
||||
}
|
||||
|
||||
impl LinuxTopology {
|
||||
fn new() -> Self {
|
||||
Self { hostname: "linux-host".to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Topology for LinuxTopology {
|
||||
fn name(&self) -> &str {
|
||||
&self.hostname
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl LinuxCapability for LinuxTopology {
|
||||
fn execute_command(&self, command: &str, args: &[&str]) {
|
||||
println!("Executing command '{}' with args {:?} on Linux host", command, args);
|
||||
}
|
||||
|
||||
fn download_file(&self, url: &str, destination: &str) -> Result<(), String> {
|
||||
println!("Downloading file from {} to {} on Linux host", url, destination);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Score implementations using dynamic capability checks
|
||||
struct LAMPScore {
|
||||
mysql_version: String,
|
||||
php_version: String,
|
||||
apache_version: String,
|
||||
}
|
||||
|
||||
impl LAMPScore {
|
||||
fn new(mysql_version: &str, php_version: &str, apache_version: &str) -> Self {
|
||||
Self {
|
||||
mysql_version: mysql_version.to_string(),
|
||||
php_version: php_version.to_string(),
|
||||
apache_version: apache_version.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method for typesafe execution
|
||||
fn execute_with_k8s(&self, topology: &dyn K8sCapability) -> String {
|
||||
println!("Deploying LAMP stack with MySQL {}, PHP {}, Apache {}",
|
||||
self.mysql_version, self.php_version, self.apache_version);
|
||||
|
||||
// Deploy MySQL
|
||||
topology.deploy_k8s_resource("mysql-deployment.yaml");
|
||||
|
||||
// Deploy PHP
|
||||
topology.deploy_k8s_resource("php-deployment.yaml");
|
||||
|
||||
// Deploy Apache
|
||||
topology.deploy_k8s_resource("apache-deployment.yaml");
|
||||
|
||||
// Create service
|
||||
topology.deploy_k8s_resource("lamp-service.yaml");
|
||||
|
||||
// Check deployment
|
||||
let status = topology.execute_kubectl("get pods -l app=lamp");
|
||||
format!("LAMP deployment status: {}", status)
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for LAMPScore {
|
||||
fn execute(&self, topology: &dyn Topology) -> Result<String, String> {
|
||||
// Try to downcast to K8sCapability
|
||||
if let Some(k8s_topology) = topology.as_any().downcast_ref::<OKDHaClusterTopology>() {
|
||||
Ok(self.execute_with_k8s(k8s_topology))
|
||||
} else if let Some(k8s_topology) = topology.as_any().downcast_ref::<K3DTopology>() {
|
||||
Ok(self.execute_with_k8s(k8s_topology))
|
||||
} else {
|
||||
Err(format!("LAMPScore requires K8sCapability but topology {} doesn't provide it",
|
||||
topology.name()))
|
||||
}
|
||||
}
|
||||
|
||||
fn score_type(&self) -> &str {
|
||||
"LAMP"
|
||||
}
|
||||
}
|
||||
|
||||
struct BinaryScore {
|
||||
url: String,
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
impl BinaryScore {
|
||||
fn new(url: &str, args: Vec<&str>) -> Self {
|
||||
Self {
|
||||
url: url.to_string(),
|
||||
args: args.iter().map(|s| s.to_string()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method for typesafe execution
|
||||
fn execute_with_linux(&self, topology: &dyn LinuxCapability) -> Result<String, String> {
|
||||
let destination = "/tmp/binary";
|
||||
|
||||
// Download the binary
|
||||
println!("Preparing to run binary from {}", self.url);
|
||||
|
||||
match topology.download_file(&self.url, destination) {
|
||||
Ok(_) => {
|
||||
println!("Binary downloaded successfully");
|
||||
|
||||
// Convert args to slice of &str
|
||||
let args: Vec<&str> = self.args.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
// Execute the binary
|
||||
topology.execute_command(destination, &args);
|
||||
Ok("Binary execution completed successfully".to_string())
|
||||
},
|
||||
Err(e) => {
|
||||
Err(format!("Failed to download binary: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for BinaryScore {
|
||||
fn execute(&self, topology: &dyn Topology) -> Result<String, String> {
|
||||
// Try to downcast to LinuxCapability
|
||||
if let Some(linux_topology) = topology.as_any().downcast_ref::<OKDHaClusterTopology>() {
|
||||
self.execute_with_linux(linux_topology)
|
||||
} else if let Some(linux_topology) = topology.as_any().downcast_ref::<LinuxTopology>() {
|
||||
self.execute_with_linux(linux_topology)
|
||||
} else {
|
||||
Err(format!("BinaryScore requires LinuxCapability but topology {} doesn't provide it",
|
||||
topology.name()))
|
||||
}
|
||||
}
|
||||
|
||||
fn score_type(&self) -> &str {
|
||||
"Binary"
|
||||
}
|
||||
}
|
||||
|
||||
struct LoadBalancerScore {
|
||||
services: Vec<String>,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
impl LoadBalancerScore {
|
||||
fn new(services: Vec<&str>, port: u16) -> Self {
|
||||
Self {
|
||||
services: services.iter().map(|s| s.to_string()).collect(),
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method for typesafe execution
|
||||
fn execute_with_lb(&self, topology: &dyn LoadBalancerCapability) -> String {
|
||||
println!("Configuring load balancer for services");
|
||||
|
||||
// Convert services to slice of &str
|
||||
let services: Vec<&str> = self.services.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
// Configure load balancer
|
||||
topology.configure_load_balancer(&services, self.port);
|
||||
|
||||
// Check status
|
||||
let status = topology.get_load_balancer_status();
|
||||
format!("Load balancer configured successfully. Status: {}", status)
|
||||
}
|
||||
}
|
||||
|
||||
impl Score for LoadBalancerScore {
|
||||
fn execute(&self, topology: &dyn Topology) -> Result<String, String> {
|
||||
// Only OKDHaClusterTopology implements LoadBalancerCapability
|
||||
if let Some(lb_topology) = topology.as_any().downcast_ref::<OKDHaClusterTopology>() {
|
||||
Ok(self.execute_with_lb(lb_topology))
|
||||
} else {
|
||||
Err(format!("LoadBalancerScore requires LoadBalancerCapability but topology {} doesn't provide it",
|
||||
topology.name()))
|
||||
}
|
||||
}
|
||||
|
||||
fn score_type(&self) -> &str {
|
||||
"LoadBalancer"
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
**Architecture Decision Record: Harmony Infrastructure Abstractions**
|
||||
## Architecture Decision Record: Core Harmony Infrastructure Abstractions
|
||||
|
||||
**Status**: Proposed
|
||||
## Status
|
||||
|
||||
**Context**: Harmony is an infrastructure orchestrator written in pure Rust, aiming to provide real portability of automation across different cloud providers and infrastructure setups. To achieve this, we need to define infrastructure abstractions that are provider-agnostic and flexible enough to accommodate various use cases.
|
||||
Proposed
|
||||
|
||||
**Decision**: We will define our infrastructure abstractions using a domain-driven approach, focusing on the core logic of Harmony. These abstractions will only include the absolutely required elements for a specific resource, without referencing specific providers or implementations.
|
||||
## Context
|
||||
|
||||
**Example: Database Abstraction**
|
||||
Harmony is an infrastructure orchestrator written in pure Rust, aiming to provide real portability of automation across different cloud providers and infrastructure setups. To achieve this, we need to define infrastructure abstractions that are provider-agnostic and flexible enough to accommodate various use cases.
|
||||
|
||||
## Decision
|
||||
|
||||
We will define our infrastructure abstractions using a domain-driven approach, focusing on the core logic of Harmony. These abstractions will only include the absolutely required elements for a specific resource, without referencing specific providers or implementations.
|
||||
|
||||
### Example: Database Abstraction
|
||||
|
||||
To deploy a database to any cloud provider, we define an abstraction that includes essential elements such as:
|
||||
```rust
|
||||
|
||||
80
adr/005-interactive-project.md
Normal file
80
adr/005-interactive-project.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# Architecture Decision Record: Interactive project setup for automated delivery pipeline of various codebases
|
||||
|
||||
## Status
|
||||
|
||||
Proposal
|
||||
|
||||
## Context
|
||||
|
||||
Many categories of developers, of which we will focus on LAMP (Linux Apache, MySQL, PHP) developers at first, are underserved by modern delivery tools.
|
||||
|
||||
Most of these projects are developed with a small team, small budget, but still are mission critical to their users.
|
||||
|
||||
We believe that Harmony, with its end-to-end infrastructure orchestration approach, enables relatively easy integration for this category of projects in a modern delivery pipeline that is opinionated enough that the development team is not overwhelmed by choices, but also flexible enough to allow them to deploy their application according to their habits. This inclues local development, managed dedicated servers, virtualized environments, manual dashboards like CPanel, cloud providers, etc.
|
||||
|
||||
To enable this, we need to provide an easy way for developers to step on to the harmony pipeline without disrupting their workflow.
|
||||
|
||||
This ADR will outline the approach taken to go from a LAMP project to be standalone, to a LAMP project using harmony that can benefit from all the enterprise grade features of our opinionated delivery pipeline including :
|
||||
|
||||
- Automated environment provisionning (local, staging, uat, prod)
|
||||
- Infrastructure optimized for the delivery stage
|
||||
- Production with automated backups
|
||||
- Automated domain names for early stages, configured domain name for production
|
||||
- SSL certificates
|
||||
- Secret management
|
||||
- SSO integration
|
||||
- IDP, IDS security
|
||||
- Monitoring, logging
|
||||
- Artifact registry
|
||||
- Automated deployment and rollback
|
||||
- Dependency management (databases, configuration, scripts)
|
||||
|
||||
## Decision
|
||||
|
||||
|
||||
# Custom Rust DSL
|
||||
|
||||
We decided to develop a rust based DSL. Even though this means people might be "afraid of Rust", we believe the numerous advantages are worth the risk.
|
||||
|
||||
The main selection criterias are :
|
||||
|
||||
- Robustness : the application/infrastructure definition should not be fragile to typos or versioning. Rusts robust dependency management (cargo) and type safety are best in class for robustness
|
||||
- Flexibility : Writing the definition in a standard programming language empowers users to easily leverage the internals of harmony to adapt the code to their needs.
|
||||
- Extensibility : Once again, a standard programming language enables easily importing a configuration, or multiple configurations, create reusable bits, and build upon the different components to really take control over a complex multi-project deployment without going crazy because of a typo in a yaml definition that changed 4 years ago
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- Complete control over the syntax and semantics of the DSL, tailored specifically to our needs.
|
||||
- Potential for better performance optimizations as we can implement exactly what is required without additional abstractions.
|
||||
|
||||
### Negative
|
||||
|
||||
- Higher initial development cost due to building a new language from scratch.
|
||||
- Steeper learning curve for developers who need to use the DSL.
|
||||
- Lack of an existing community and ecosystem, which could slow down adoption.
|
||||
- Increased maintenance overhead as the DSL needs to be updated and supported internally.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
### Score spec
|
||||
|
||||
We considered integrating with the score-spec project : https://github.com/score-spec/spec
|
||||
|
||||
The idea was to benefit from an existing community and ecosystem. The motivations to consider score were the following :
|
||||
|
||||
- It is a CNCF project, which helps a lot with adoption and community building
|
||||
- It already supports important targets for us including docker-compose and k8s
|
||||
- It provides a way to define the application's infrastructure at the correct level of abstraction for us to deploy it anywhere -- that is the goal of the score-spec project
|
||||
- Once we evolve, we can simply have a score compatible provider that allows any project with a score spec to be deployed on the harmony stack
|
||||
- Score was built with enterprise use-cases in mind : Humanitec platform engineering customers
|
||||
|
||||
|
||||
Positive Consequences
|
||||
|
||||
- Score Community is growing, using harmony will be very easy for them
|
||||
|
||||
Negative Consequences
|
||||
|
||||
- Score is not that big yet, and mostly used by Humanitec's clients (I guess), which is a hard to penetrate environment
|
||||
@@ -5,6 +5,7 @@
|
||||
Proposed
|
||||
|
||||
### TODO [#3](https://git.nationtech.io/NationTech/harmony/issues/3):
|
||||
|
||||
Before accepting this proposal we need to run a POC to validate this potential issue :
|
||||
|
||||
**Keycloak Misuse**: Using Keycloak primarily as a secrets manager is inappropriate, as it's designed for identity and access management (IAM), not secrets management. This creates scalability and functionality limitations.
|
||||
|
||||
65
adr/007-default-runtime.md
Normal file
65
adr/007-default-runtime.md
Normal file
@@ -0,0 +1,65 @@
|
||||
## Architecture Decision Record: Default Runtime for Managed Workloads
|
||||
|
||||
### Status
|
||||
|
||||
Proposed
|
||||
|
||||
### Context
|
||||
|
||||
Our infrastructure orchestrator manages workloads requiring a Kubernetes-compatible runtime environment.
|
||||
|
||||
**Requirements**
|
||||
|
||||
- Cross-platform (Linux, Windows, macOS)
|
||||
- Kubernetes compatibility
|
||||
- Lightweight, easy setup with minimal dependencies
|
||||
- Clean host teardown and minimal residue
|
||||
- Well-maintained and actively supported
|
||||
|
||||
### Decision
|
||||
|
||||
We select **k3d (k3s in Docker)** as our default runtime environment across all supported platforms (Linux, Windows, macOS).
|
||||
|
||||
### Rationale
|
||||
|
||||
- **Consistency Across Platforms:**
|
||||
One solution for all platforms simplifies development, supports documentation, and reduces complexity.
|
||||
|
||||
- **Simplified Setup and Teardown:**
|
||||
k3d runs Kubernetes clusters in Docker containers, allowing quick setup, teardown, and minimal host residue.
|
||||
|
||||
- **Leveraging Existing Container Ecosystem:**
|
||||
Docker/container runtimes are widely adopted, making their presence and familiarity common among users.
|
||||
|
||||
- **Kubernetes Compatibility:**
|
||||
k3s (within k3d) is fully Kubernetes-certified, ensuring compatibility with standard Kubernetes tools and manifests.
|
||||
|
||||
- **Active Maintenance and Community:**
|
||||
k3d and k3s both have active communities and are well-maintained.
|
||||
|
||||
### Consequences
|
||||
|
||||
#### Positive
|
||||
|
||||
- **Uniform User Experience:** Users have a consistent setup experience across all platforms.
|
||||
- **Reduced Support Overhead:** Standardizing runtime simplifies support, documentation, and troubleshooting.
|
||||
- **Clean Isolation:** Containerization allows developers to easily clean up clusters without affecting host systems.
|
||||
- **Facilitates Multi-Cluster Development:** Easy creation and management of multiple clusters concurrently.
|
||||
|
||||
#### Negative
|
||||
|
||||
- **Docker Dependency:** Requires Docker (or compatible runtime) on all platforms.
|
||||
- **Potential Overhead:** Slight performance/resource overhead compared to native k3s.
|
||||
- **Docker Licensing Considerations:** Enterprise licensing of Docker Desktop could introduce additional considerations.
|
||||
|
||||
### Alternatives Considered
|
||||
|
||||
- **Native k3s (Linux) / k3d (Windows/macOS):** Original proposal. Rejected for greater simplicity and consistency.
|
||||
- **Minikube, MicroK8s, Kind:** Rejected due to complexity, resource usage, or narrower use-case focus.
|
||||
- **Docker Compose, Podman Desktop:** Rejected due to lack of orchestration or current limited k3d compatibility.
|
||||
|
||||
### Future Work
|
||||
|
||||
- Evaluate Podman Desktop or other container runtimes to avoid Docker dependency.
|
||||
- Continuously monitor k3d maturity and stability.
|
||||
- Investigate WebAssembly (WASM) runtimes as emerging alternatives for containerized workloads.
|
||||
62
adr/008-score-display-formatting.md
Normal file
62
adr/008-score-display-formatting.md
Normal file
@@ -0,0 +1,62 @@
|
||||
## Architecture Decision Record: Data Representation and UI Rendering for Score Types
|
||||
|
||||
**Status:** Proposed
|
||||
|
||||
**TL;DR:** `Score` types will be serialized (using `serde`) for presentation in UIs. This decouples data definition from presentation, improving scalability and reducing complexity for developers defining `Score` types. New UI types only need to handle existing field types, and new `Score` types don’t require UI changes as long as they use existing field types. Adding a new field type *does* require updates to all UIs.
|
||||
|
||||
**Key benefits:** Scalability, reduced complexity for `Score` authors, decoupling of data and presentation.
|
||||
|
||||
**Key trade-off:** Adding new field types requires updating all UIs.
|
||||
|
||||
---
|
||||
|
||||
**Context:**
|
||||
|
||||
Harmony is a pure Rust infrastructure orchestrator focused on compile-time safety and providing a developer-friendly, Ansible-module-like experience for defining infrastructure configurations via "Scores". These Scores (e.g., `LAMPScore`) are Rust structs composed of specific, strongly-typed fields (e.g., `VersionField`, `UrlField`, `PathField`) which are validated at compile-time using macros (`Version!`, `Url!`, etc.).
|
||||
|
||||
A key requirement is displaying the configuration defined in these Scores across various user interfaces (Web UI, TUI, potentially Mobile UI, etc.) in a consistent and type-safe manner. As the number of Score types is expected to grow significantly (hundreds or thousands), we need a scalable approach for rendering their data that avoids tightly coupling Score definitions to specific UI implementations.
|
||||
|
||||
The primary challenge is preventing the need for every `Score` struct author to implement multiple display traits (e.g., `Display`, `WebDisplay`, `TuiDisplay`) for every potential UI target. This would create an N x M complexity problem (N Scores * M UI types) and place an unreasonable burden on Score developers, hindering scalability and maintainability.
|
||||
|
||||
**Decision:**
|
||||
|
||||
1. **Mandatory Serialization:** All `Score` structs *must* implement `serde::Serialize` and `serde::Deserialize`. They *will not* be required to implement `std::fmt::Display` or any custom UI-specific display traits (e.g., `WebDisplay`, `TuiDisplay`).
|
||||
2. **Field-Level Rendering:** Responsibility for rendering data will reside within the UI components. Each UI (Web, TUI, etc.) will implement logic to display *individual field types* (e.g., `UrlField`, `VersionField`, `IpAddressField`, `SecretField`).
|
||||
3. **Data Access via Serialization:** UIs will primarily interact with `Score` data through its serialized representation (e.g., JSON obtained via `serde_json`). This provides a standardized interface for UIs to consume the data structure agnostic of the specific `Score` type. Alternatively, UIs *could* potentially use reflection or specific visitor patterns on the `Score` struct itself, but serialization is the preferred decoupling mechanism.
|
||||
|
||||
**Rationale:**
|
||||
|
||||
1. **Decoupling Data from Presentation:** This decision cleanly separates the data definition (`Score` structs and their fields) from the presentation logic (UI rendering). `Score` authors can focus solely on defining the data and its structure, while UI developers focus on how to best present known data *types*.
|
||||
2. **Scalability:** This approach scales significantly better than requiring display trait implementations on Scores:
|
||||
* Adding a *new Score type* requires *no changes* to existing UI code, provided it uses existing field types.
|
||||
* Adding a *new UI type* requires implementing rendering logic only for the defined set of *field types*, not for every individual `Score` type. This reduces the N x M complexity to N + M complexity (approximately).
|
||||
3. **Simplicity for Score Authors:** Requiring only `serde::Serialize + Deserialize` (which can often be derived automatically with `#[derive(Serialize, Deserialize)]`) is a much lower burden than implementing custom rendering logic for multiple, potentially unknown, UI targets.
|
||||
4. **Leverages Rust Ecosystem Standards:** `serde` is the de facto standard for serialization and deserialization in Rust. Relying on it aligns with common Rust practices and benefits from its robustness, performance, and extensive tooling.
|
||||
5. **Consistency for UIs:** Serialization provides a consistent, structured format (like JSON) for UIs to consume data, regardless of the underlying `Score` struct's complexity or composition.
|
||||
6. **Flexibility for UI Implementation:** UIs can choose the best way to render each field type based on their capabilities (e.g., a `UrlField` might be a clickable link in a Web UI, plain text in a TUI; a `SecretField` might be masked).
|
||||
|
||||
**Consequences:**
|
||||
|
||||
**Positive:**
|
||||
|
||||
* Greatly improved scalability for adding new Score types and UI targets.
|
||||
* Strong separation of concerns between data definition and presentation.
|
||||
* Reduced implementation burden and complexity for Score authors.
|
||||
* Consistent mechanism for UIs to access and interpret Score data.
|
||||
* Aligns well with the Hexagonal Architecture (ADR-002) by treating UIs as adapters interacting with the application core via a defined port (the serialized data contract).
|
||||
|
||||
**Negative:**
|
||||
|
||||
* Adding a *new field type* (e.g., `EmailField`) requires updates to *all* existing UI implementations to support rendering it.
|
||||
* UI components become dependent on the set of defined field types and need comprehensive logic to handle each one appropriately.
|
||||
* Potential minor overhead of serialization/deserialization compared to direct function calls (though likely negligible for UI purposes).
|
||||
* Requires careful design and management of the standard library of field types.
|
||||
|
||||
**Alternatives Considered:**
|
||||
|
||||
1. **`Score` Implements `std::fmt::Display`:**
|
||||
* _Rejected:_ Too simplistic. Only suitable for basic text rendering, doesn't cater to structured UIs (Web, etc.), and doesn't allow type-specific rendering logic (e.g., masking secrets). Doesn't scale to multiple UI formats.
|
||||
2. **`Score` Implements Multiple Custom Display Traits (`WebDisplay`, `TuiDisplay`, etc.):**
|
||||
* _Rejected:_ Leads directly to the N x M complexity problem. Tightly couples Score definitions to specific UI implementations. Places an excessive burden on Score authors, hindering adoption and scalability.
|
||||
3. **Generic Display Trait with Context (`Score` implements `DisplayWithContext<UIContext>`):**
|
||||
* _Rejected:_ More flexible than multiple traits, but still requires Score authors to implement potentially complex rendering logic within the `Score` definition itself. The `Score` would still need awareness of different UI contexts, leading to undesirable coupling. Managing context types adds complexity.
|
||||
61
adr/009-helm-and-kustomize-handling.md
Normal file
61
adr/009-helm-and-kustomize-handling.md
Normal file
@@ -0,0 +1,61 @@
|
||||
# Architecture Decision Record: Helm and Kustomize Handling
|
||||
|
||||
Initial Author: Taha Hawa
|
||||
|
||||
Initial Date: 2025-04-15
|
||||
|
||||
Last Updated Date: 2025-04-15
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
We need to find a way to handle Helm charts and deploy them to a Kubernetes cluster. Helm has a lot of extra functionality that we may or may not need. Kustomize handles Helm charts by inflating them and applying them as vanilla Kubernetes yaml. How should Harmony handle it?
|
||||
|
||||
## Decision
|
||||
|
||||
In order to move quickly and efficiently, Harmony should handle Helm charts similarly to how Kustomize does: invoke Helm to inflate/render the charts with the needed inputs, and deploy the rendered artifacts to Kubernetes as if it were vanilla manifests.
|
||||
|
||||
## Rationale
|
||||
|
||||
A lot of Helm's features aren't strictly necessary and would add unneeded overhead. This is likely the fastest way to go from zero to deployed. Other tools (e.g. Kustomize) already do this. Kustomize has tooling for patching and modifying k8s manifests before deploying, and Harmony should have that power too, even if it's not what Helm typically intends.
|
||||
|
||||
Perhaps in future also have a Kustomize resource in Harmony? Which could handle Helm charts for Harmony as well/instead.
|
||||
|
||||
## Consequences
|
||||
|
||||
**Pros**:
|
||||
|
||||
- Much easier (and faster) than implementing all of Helm's featureset
|
||||
- Can potentially re-use code from K8sResource already present in Harmony
|
||||
- Harmony retains more control over how the deployment goes after rendering (i.e. can act like Kustomize, or leverage Kustomize itself to modify deployments after rendering/inflation)
|
||||
- Reduce (unstable) surface of dealing with Helm binary
|
||||
|
||||
**Cons**:
|
||||
|
||||
- Lose some Helm functionality
|
||||
- Potentially lose some compatibility with Helm
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
- ### Implement Helm resouce/client fully in Harmony
|
||||
- **Pros**:
|
||||
- Retain full compatibility with Helm as a tool
|
||||
- Retain full functionality of Helm
|
||||
- **Cons**:
|
||||
- Longer dev time
|
||||
- More complex integration
|
||||
- Dealing with larger (unstable) surface of Helm as a binary
|
||||
- ### Leverage Kustomize to deal with Helm charts
|
||||
- **Pros**:
|
||||
- Already has a good, minimal inflation solution built
|
||||
- Powerful post-processing/patching
|
||||
- Can integrate with `kubectl`
|
||||
- **Cons**:
|
||||
- Unstable binary tool/surface to deal with
|
||||
- Still requires Helm to be installed as well as Kustomize
|
||||
- Not all Helm features supported
|
||||
|
||||
## Additional Notes
|
||||
73
adr/010-monitoring-alerting/architecture.rs
Normal file
73
adr/010-monitoring-alerting/architecture.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
pub trait MonitoringSystem {}
|
||||
|
||||
// 1. Modified AlertReceiver trait:
|
||||
// - Removed the problematic `clone` method.
|
||||
// - Added `box_clone` which returns a Box<dyn AlertReceiver>.
|
||||
pub trait AlertReceiver {
|
||||
type M: MonitoringSystem;
|
||||
fn install(&self, sender: &Self::M) -> Result<(), String>;
|
||||
// This method allows concrete types to clone themselves into a Box<dyn AlertReceiver>
|
||||
fn box_clone(&self) -> Box<dyn AlertReceiver<M = Self::M>>;
|
||||
}
|
||||
#[derive(Clone)]
|
||||
struct Prometheus{}
|
||||
impl MonitoringSystem for Prometheus {}
|
||||
|
||||
#[derive(Clone)] // Keep derive(Clone) for DiscordWebhook itself
|
||||
struct DiscordWebhook{}
|
||||
|
||||
impl AlertReceiver for DiscordWebhook {
|
||||
type M = Prometheus;
|
||||
fn install(&self, sender: &Self::M) -> Result<(), String> {
|
||||
// Placeholder for actual installation logic
|
||||
println!("DiscordWebhook installed for Prometheus monitoring.");
|
||||
Ok(())
|
||||
}
|
||||
// 2. Implement `box_clone` for DiscordWebhook:
|
||||
// This uses the derived `Clone` for DiscordWebhook to create a new boxed instance.
|
||||
fn box_clone(&self) -> Box<dyn AlertReceiver<M = Self::M>> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Implement `std::clone::Clone` for `Box<dyn AlertReceiver<M= M>>`:
|
||||
// This allows `Box<dyn AlertReceiver>` to be cloned.
|
||||
// The `+ 'static` lifetime bound is often necessary for trait objects stored in collections,
|
||||
// ensuring they live long enough.
|
||||
impl<M: MonitoringSystem + 'static> Clone for Box<dyn AlertReceiver<M= M>> {
|
||||
fn clone(&self) -> Self {
|
||||
self.box_clone() // Call the custom `box_clone` method
|
||||
}
|
||||
}
|
||||
|
||||
// MonitoringConfig can now derive Clone because its `receivers` field
|
||||
// (Vec<Box<dyn AlertReceiver<M = M>>>) is now cloneable.
|
||||
#[derive(Clone)]
|
||||
struct MonitoringConfig <M: MonitoringSystem + 'static>{
|
||||
receivers: Vec<Box<dyn AlertReceiver<M = M>>>
|
||||
}
|
||||
|
||||
// Example usage to demonstrate compilation and functionality
|
||||
fn main() {
|
||||
let prometheus_instance = Prometheus{};
|
||||
let discord_webhook_instance = DiscordWebhook{};
|
||||
|
||||
let mut config = MonitoringConfig {
|
||||
receivers: Vec::new()
|
||||
};
|
||||
|
||||
// Create a boxed alert receiver
|
||||
let boxed_receiver: Box<dyn AlertReceiver<M = Prometheus>> = Box::new(discord_webhook_instance);
|
||||
config.receivers.push(boxed_receiver);
|
||||
|
||||
// Clone the config, which will now correctly clone the boxed receiver
|
||||
let cloned_config = config.clone();
|
||||
|
||||
println!("Original config has {} receivers.", config.receivers.len());
|
||||
println!("Cloned config has {} receivers.", cloned_config.receivers.len());
|
||||
|
||||
// Example of using the installed receiver
|
||||
if let Some(receiver) = config.receivers.get(0) {
|
||||
let _ = receiver.install(&prometheus_instance);
|
||||
}
|
||||
}
|
||||
68
adr/010-monitoring-and-alerting.md
Normal file
68
adr/010-monitoring-and-alerting.md
Normal file
@@ -0,0 +1,68 @@
|
||||
# Architecture Decision Record: Monitoring and Alerting
|
||||
|
||||
Initial Author : Willem Rolleman
|
||||
Date : April 28 2025
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
A harmony user should be able to initialize a monitoring stack easily, either at the first run of Harmony, or that integrates with existing proects and infra without creating multiple instances of the monitoring stack or overwriting existing alerts/configurations.The user also needs a simple way to configure the stack so that it watches the projects. There should be reasonable defaults configured that are easily customizable for each project
|
||||
|
||||
## Decision
|
||||
|
||||
Create MonitoringStack score that creates a maestro to launch the monitoring stack or not if it is already present.
|
||||
The MonitoringStack score can be passed to the maestro in the vec! scores list
|
||||
|
||||
## Rationale
|
||||
|
||||
Having the score launch a maestro will allow the user to easily create a new monitoring stack and keeps composants grouped together. The MonitoringScore can handle all the logic for adding alerts, ensuring that the stack is running etc.
|
||||
|
||||
## Alerternatives considered
|
||||
|
||||
- ### Implement alerting and monitoring stack using existing HelmScore for each project
|
||||
- **Pros**:
|
||||
- Each project can choose to use the monitoring and alerting stack that they choose
|
||||
- Less overhead in terms of care harmony code
|
||||
- can add Box::new(grafana::grafanascore(namespace))
|
||||
- **Cons**:
|
||||
- No default solution implemented
|
||||
- Dev needs to chose what they use
|
||||
- Increases complexity of score projects
|
||||
- Each project will create a new monitoring and alerting instance rather than joining the existing one
|
||||
|
||||
|
||||
- ### Use OKD grafana and prometheus
|
||||
- **Pros**:
|
||||
- Minimal config to do in Harmony
|
||||
- **Cons**:
|
||||
- relies on OKD so will not working for local testing via k3d
|
||||
|
||||
- ### Create a monitoring and alerting crate similar to harmony tui
|
||||
- **Pros**:
|
||||
- Creates a default solution that can be implemented once by harmony
|
||||
- can create a join function that will allow a project to connect to the existing solution
|
||||
- eliminates risk of creating multiple instances of grafana or prometheus
|
||||
- **Cons**:
|
||||
- more complex than using a helm score
|
||||
- management of values files for individual functions becomes more complicated, ie how do you create alerts for one project via helm install that doesnt overwrite the other alerts
|
||||
|
||||
- ### Add monitoring to Maestro struct so whether the monitoring stack is used must be defined
|
||||
- **Pros**:
|
||||
- less for the user to define
|
||||
- may be easier to set defaults
|
||||
- **Cons**:
|
||||
- feels counterintuitive
|
||||
- would need to modify the structure of the maestro and how it operates which seems like a bad idea
|
||||
- unclear how to allow user to pass custom values/configs to the monitoring stack for subsequent projects
|
||||
|
||||
- ### Create MonitoringStack score to add to scores vec! which loads a maestro to install stack if not ready or add custom endpoints/alerts to existing stack
|
||||
- **Pros**:
|
||||
- Maestro already accepts a list of scores to initialize
|
||||
- leaving out the monitoring score simply means the user does not want monitoring
|
||||
- if the monitoring stack is already created, the MonitoringStack score doesn't necessarily need to be added to each project
|
||||
- composants of the monitoring stack are bundled together and can be expaned or modified from the same place
|
||||
- **Cons**:
|
||||
- maybe need to create
|
||||
161
adr/011-multi-tenant-cluster.md
Normal file
161
adr/011-multi-tenant-cluster.md
Normal file
@@ -0,0 +1,161 @@
|
||||
# Architecture Decision Record: Multi-Tenancy Strategy for Harmony Managed Clusters
|
||||
|
||||
Initial Author: Jean-Gabriel Gill-Couture
|
||||
|
||||
Initial Date: 2025-05-26
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
Harmony manages production OKD/Kubernetes clusters that serve multiple clients with varying trust levels and operational requirements. We need a multi-tenancy strategy that provides:
|
||||
|
||||
1. **Strong isolation** between client workloads while maintaining operational simplicity
|
||||
2. **Controlled API access** allowing clients self-service capabilities within defined boundaries
|
||||
3. **Security-first approach** protecting both the cluster infrastructure and tenant data
|
||||
4. **Harmony-native implementation** using our Score/Interpret pattern for automated tenant provisioning
|
||||
5. **Scalable management** supporting both small trusted clients and larger enterprise customers
|
||||
|
||||
The official Kubernetes multi-tenancy documentation identifies two primary models: namespace-based isolation and virtual control planes per tenant. Given Harmony's focus on operational simplicity, provider-agnostic abstractions (ADR-003), and hexagonal architecture (ADR-002), we must choose an approach that balances security, usability, and maintainability.
|
||||
|
||||
Our clients represent a hybrid tenancy model:
|
||||
- **Customer multi-tenancy**: Each client operates independently with no cross-tenant trust
|
||||
- **Team multi-tenancy**: Individual clients may have multiple team members requiring coordinated access
|
||||
- **API access requirement**: Unlike pure SaaS scenarios, clients need controlled Kubernetes API access for self-service operations
|
||||
|
||||
The official kubernetes documentation on multi tenancy heavily inspired this ADR : https://kubernetes.io/docs/concepts/security/multi-tenancy/
|
||||
|
||||
## Decision
|
||||
|
||||
Implement **namespace-based multi-tenancy** with the following architecture:
|
||||
|
||||
### 1. Network Security Model
|
||||
- **Private cluster access**: Kubernetes API and OpenShift console accessible only via WireGuard VPN
|
||||
- **No public exposure**: Control plane endpoints remain internal to prevent unauthorized access attempts
|
||||
- **VPN-based authentication**: Initial access control through WireGuard client certificates
|
||||
|
||||
### 2. Tenant Isolation Strategy
|
||||
- **Dedicated namespace per tenant**: Each client receives an isolated namespace with access limited only to the required resources and operations
|
||||
- **Complete network isolation**: NetworkPolicies prevent cross-namespace communication while allowing full egress to public internet
|
||||
- **Resource governance**: ResourceQuotas and LimitRanges enforce CPU, memory, and storage consumption limits
|
||||
- **Storage access control**: Clients can create PersistentVolumeClaims but cannot directly manipulate PersistentVolumes or access other tenants' storage
|
||||
|
||||
### 3. Access Control Framework
|
||||
- **Principle of Least Privilege**: RBAC grants only necessary permissions within tenant namespace scope
|
||||
- **Namespace-scoped**: Clients can create/modify/delete resources within their namespace
|
||||
- **Cluster-level restrictions**: No access to cluster-wide resources, other namespaces, or sensitive cluster operations
|
||||
- **Whitelisted operations**: Controlled self-service capabilities for ingress, secrets, configmaps, and workload management
|
||||
|
||||
### 4. Identity Management Evolution
|
||||
- **Phase 1**: Manual provisioning of VPN access and Kubernetes ServiceAccounts/Users
|
||||
- **Phase 2**: Migration to Keycloak-based identity management (aligning with ADR-006) for centralized authentication and lifecycle management
|
||||
|
||||
### 5. Harmony Integration
|
||||
- **TenantScore implementation**: Declarative tenant provisioning using Harmony's Score/Interpret pattern
|
||||
- **Topology abstraction**: Tenant configuration abstracted from underlying Kubernetes implementation details
|
||||
- **Automated deployment**: Complete tenant setup automated through Harmony's orchestration capabilities
|
||||
|
||||
## Rationale
|
||||
|
||||
### Network Security Through VPN Access
|
||||
- **Defense in depth**: VPN requirement adds critical security layer preventing unauthorized cluster access
|
||||
- **Simplified firewall rules**: No need for complex public endpoint protections or rate limiting
|
||||
- **Audit capability**: VPN access provides clear audit trail of cluster connections
|
||||
- **Aligns with enterprise practices**: Most enterprise customers already use VPN infrastructure
|
||||
|
||||
### Namespace Isolation vs Virtual Control Planes
|
||||
Following Kubernetes official guidance, namespace isolation provides:
|
||||
- **Lower resource overhead**: Virtual control planes require dedicated etcd, API server, and controller manager per tenant
|
||||
- **Operational simplicity**: Single control plane to maintain, upgrade, and monitor
|
||||
- **Cross-tenant service integration**: Enables future controlled cross-tenant communication if required
|
||||
- **Proven stability**: Namespace-based isolation is well-tested and widely deployed
|
||||
- **Cost efficiency**: Significantly lower infrastructure costs compared to dedicated control planes
|
||||
|
||||
### Hybrid Tenancy Model Suitability
|
||||
Our approach addresses both customer and team multi-tenancy requirements:
|
||||
- **Customer isolation**: Strong network and RBAC boundaries prevent cross-tenant interference
|
||||
- **Team collaboration**: Multiple team members can share namespace access through group-based RBAC
|
||||
- **Self-service balance**: Controlled API access enables client autonomy without compromising security
|
||||
|
||||
### Harmony Architecture Alignment
|
||||
- **Provider agnostic**: TenantScore abstracts multi-tenancy concepts, enabling future support for other Kubernetes distributions
|
||||
- **Hexagonal architecture**: Tenant management becomes an infrastructure capability accessed through well-defined ports
|
||||
- **Declarative automation**: Tenant lifecycle fully managed through Harmony's Score execution model
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive Consequences
|
||||
- **Strong security posture**: VPN + namespace isolation provides robust tenant separation
|
||||
- **Operational efficiency**: Single cluster management with automated tenant provisioning
|
||||
- **Client autonomy**: Self-service capabilities reduce operational support burden
|
||||
- **Scalable architecture**: Can support hundreds of tenants per cluster without architectural changes
|
||||
- **Future flexibility**: Foundation supports evolution to more sophisticated multi-tenancy models
|
||||
- **Cost optimization**: Shared infrastructure maximizes resource utilization
|
||||
|
||||
### Negative Consequences
|
||||
- **VPN operational overhead**: Requires VPN infrastructure management
|
||||
- **Manual provisioning complexity**: Phase 1 manual user management creates administrative burden
|
||||
- **Network policy dependency**: Requires CNI with NetworkPolicy support (OVN-Kubernetes provides this and is the OKD/Openshift default)
|
||||
- **Cluster-wide resource limitations**: Some advanced Kubernetes features require cluster-wide access
|
||||
- **Single point of failure**: Cluster outage affects all tenants simultaneously
|
||||
|
||||
### Migration Challenges
|
||||
- **Legacy client integration**: Existing clients may need VPN client setup and credential migration
|
||||
- **Monitoring complexity**: Per-tenant observability requires careful metric and log segmentation
|
||||
- **Backup considerations**: Tenant data backup must respect isolation boundaries
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### Alternative 1: Virtual Control Plane Per Tenant
|
||||
**Pros**: Complete control plane isolation, full Kubernetes API access per tenant
|
||||
**Cons**: 3-5x higher resource usage, complex cross-tenant networking, operational complexity scales linearly with tenants
|
||||
|
||||
**Rejected**: Resource overhead incompatible with cost-effective multi-tenancy goals
|
||||
|
||||
### Alternative 2: Dedicated Clusters Per Tenant
|
||||
**Pros**: Maximum isolation, independent upgrade cycles, simplified security model
|
||||
**Cons**: Exponential operational complexity, prohibitive costs, resource waste
|
||||
|
||||
**Rejected**: Operational overhead makes this approach unsustainable for multiple clients
|
||||
|
||||
### Alternative 3: Public API with Advanced Authentication
|
||||
**Pros**: No VPN requirement, potentially simpler client access
|
||||
**Cons**: Larger attack surface, complex rate limiting and DDoS protection, increased security monitoring requirements
|
||||
|
||||
**Rejected**: Risk/benefit analysis favors VPN-based access control
|
||||
|
||||
### Alternative 4: Service Mesh Based Isolation
|
||||
**Pros**: Fine-grained traffic control, encryption, advanced observability
|
||||
**Cons**: Significant operational complexity, performance overhead, steep learning curve
|
||||
|
||||
**Rejected**: Complexity overhead outweighs benefits for current requirements; remains option for future enhancement
|
||||
|
||||
## Additional Notes
|
||||
|
||||
### Implementation Roadmap
|
||||
1. **Phase 1**: Implement VPN access and manual tenant provisioning
|
||||
2. **Phase 2**: Deploy TenantScore automation for namespace, RBAC, and NetworkPolicy management
|
||||
4. **Phase 3**: Work on privilege escalation from pods, audit for weaknesses, enforce security policies on pod runtimes
|
||||
3. **Phase 4**: Integrate Keycloak for centralized identity management
|
||||
4. **Phase 5**: Add advanced monitoring and per-tenant observability
|
||||
|
||||
### TenantScore Structure Preview
|
||||
```rust
|
||||
pub struct TenantScore {
|
||||
pub tenant_config: TenantConfig,
|
||||
pub resource_quotas: ResourceQuotaConfig,
|
||||
pub network_isolation: NetworkIsolationPolicy,
|
||||
pub storage_access: StorageAccessConfig,
|
||||
pub rbac_config: RBACConfig,
|
||||
}
|
||||
```
|
||||
|
||||
### Future Enhancements
|
||||
- **Cross-tenant service mesh**: For approved inter-tenant communication
|
||||
- **Advanced monitoring**: Per-tenant Prometheus/Grafana instances
|
||||
- **Backup automation**: Tenant-scoped backup policies
|
||||
- **Cost allocation**: Detailed per-tenant resource usage tracking
|
||||
|
||||
This ADR establishes the foundation for secure, scalable multi-tenancy in Harmony-managed clusters while maintaining operational simplicity and cost effectiveness. A follow-up ADR will detail the Tenant abstraction and user management mechanisms within the Harmony framework.
|
||||
41
adr/011-tenant/NetworkPolicy.yaml
Normal file
41
adr/011-tenant/NetworkPolicy.yaml
Normal file
@@ -0,0 +1,41 @@
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata:
|
||||
name: tenant-isolation-policy
|
||||
namespace: testtenant
|
||||
spec:
|
||||
podSelector: {} # Selects all pods in the namespace
|
||||
policyTypes:
|
||||
- Ingress
|
||||
- Egress
|
||||
ingress:
|
||||
- from:
|
||||
- podSelector: {} # Allow from all pods in the same namespace
|
||||
egress:
|
||||
- to:
|
||||
- podSelector: {} # Allow to all pods in the same namespace
|
||||
- to:
|
||||
- podSelector: {}
|
||||
namespaceSelector:
|
||||
matchLabels:
|
||||
kubernetes.io/metadata.name: openshift-dns # Target the openshift-dns namespace
|
||||
# Note, only opening port 53 is not enough, will have to dig deeper into this one eventually
|
||||
# ports:
|
||||
# - protocol: UDP
|
||||
# port: 53
|
||||
# - protocol: TCP
|
||||
# port: 53
|
||||
# Allow egress to public internet only
|
||||
- to:
|
||||
- ipBlock:
|
||||
cidr: 0.0.0.0/0
|
||||
except:
|
||||
- 10.0.0.0/8 # RFC1918
|
||||
- 172.16.0.0/12 # RFC1918
|
||||
- 192.168.0.0/16 # RFC1918
|
||||
- 169.254.0.0/16 # Link-local
|
||||
- 127.0.0.0/8 # Loopback
|
||||
- 224.0.0.0/4 # Multicast
|
||||
- 240.0.0.0/4 # Reserved
|
||||
- 100.64.0.0/10 # Carrier-grade NAT
|
||||
- 0.0.0.0/8 # Reserved
|
||||
95
adr/011-tenant/TestDeployment.yaml
Normal file
95
adr/011-tenant/TestDeployment.yaml
Normal file
@@ -0,0 +1,95 @@
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: testtenant
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Namespace
|
||||
metadata:
|
||||
name: testtenant2
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: test-web
|
||||
namespace: testtenant
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: test-web
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: test-web
|
||||
spec:
|
||||
containers:
|
||||
- name: nginx
|
||||
image: nginxinc/nginx-unprivileged
|
||||
ports:
|
||||
- containerPort: 80
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: test-web
|
||||
namespace: testtenant
|
||||
spec:
|
||||
selector:
|
||||
app: test-web
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: test-client
|
||||
namespace: testtenant
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: test-client
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: test-client
|
||||
spec:
|
||||
containers:
|
||||
- name: curl
|
||||
image: curlimages/curl:latest
|
||||
command: ["/bin/sh", "-c", "sleep 3600"]
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: test-web
|
||||
namespace: testtenant2
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: test-web
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: test-web
|
||||
spec:
|
||||
containers:
|
||||
- name: nginx
|
||||
image: nginxinc/nginx-unprivileged
|
||||
ports:
|
||||
- containerPort: 80
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: test-web
|
||||
namespace: testtenant2
|
||||
spec:
|
||||
selector:
|
||||
app: test-web
|
||||
ports:
|
||||
- port: 80
|
||||
targetPort: 8080
|
||||
63
adr/012-project-delivery-automation.md
Normal file
63
adr/012-project-delivery-automation.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Architecture Decision Record: \<Title\>
|
||||
|
||||
Initial Author: Jean-Gabriel Gill-Couture
|
||||
|
||||
Initial Date: 2025-06-04
|
||||
|
||||
Last Updated Date: 2025-06-04
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
As Harmony's goal is to make software delivery easier, we must provide an easy way for developers to express their app's semantics and dependencies with great abstractions, in a similar fashion to what the score.dev project is doing.
|
||||
|
||||
Thus, we started working on ways to package common types of applications such as LAMP, which we started working on with `LAMPScore`.
|
||||
|
||||
Now is time for the next step : we want to pave the way towards complete lifecycle automation. To do this, we will start with a way to execute Harmony's modules easily from anywhere, starting with locally and in CI environments.
|
||||
|
||||
## Decision
|
||||
|
||||
To achieve easy, portable execution of Harmony, we will follow this architecture :
|
||||
|
||||
- Host a basic harmony release that is compiled with the CLI by our gitea/github server
|
||||
- This binary will do the following : check if there is a `harmony` folder in the current path
|
||||
- If yes
|
||||
- Check if cargo is available locally and compile the harmony binary, or compile the harmony binary using a rust docker container, if neither cargo or a container runtime is available, output a message explaining the situation
|
||||
- Run the newly compiled binary. (Ideally using pid handoff like exec does but some research around this should be done. I think handing off the process is to help with OS interaction such as terminal apps, signals, exit codes, process handling, etc but there might be some side effects)
|
||||
- If not
|
||||
- Suggest initializing a project by auto detecting what the project looks like
|
||||
- When the project type cannot be auto detected, provide links to Harmony's documentation on how to set up a project, a link to the examples folder, and a ask the user if he wants to initialize an empty Harmony project in the current folder
|
||||
- harmony/Cargo.toml with dependencies set
|
||||
- harmony/src/main.rs with an example LAMPScore setup and ready to run
|
||||
- This same binary can be used in a CI environment to run the target project's Harmony module. By default, we provide these opinionated steps :
|
||||
1. **An empty check step.** The purpose of this step is to run all tests and checks against the codebase. For complex projects this could involve a very complex pipeline of test environments setup and execution but this is out of scope for now. This is not handled by harmony. For projects with automatic setup, we can fill this step with something like `cargo fmt --check; cargo test; cargo build` but Harmony is not directly involved in the execution of this step.
|
||||
2. **Package and publish.** Once all checks have passed, the production ready container is built and pushed to a registry. This is done by Harmony.
|
||||
3. **Deploy to staging automatically.**
|
||||
4. **Run a sanity check on staging.** As Harmony is responsible for deploying, Harmony should have all the knowledge of how to perform a sanity check on the staging environment. This will, most of the time, be a simple verification of the kubernetes health of all deployed components, and a poke on the public endpoint when there is one.
|
||||
5. **Deploy to production automatically.** Many projects will require manual approval here, this can be easily set up in the CI afterwards, but our opinion is that
|
||||
6. **Run a sanity check on production.** Same check as staging, but on production.
|
||||
|
||||
*Note on providing a base pipeline :* Having a complete pipeline set up automatically will encourage development teams to build upon these by adding tests where they belong. The goal here is to provide an opiniated solution that works for most small and large projects. Of course, many orgnizations will need to add steps such as deploying to sandbox environments, requiring more advanced approvals, more complex publication and coordination with other projects. But this here encompasses the basics required to build and deploy software reliably at any scale.
|
||||
|
||||
### Environment setup
|
||||
|
||||
TBD : For now, environments (tenants) will be set up and configured manually. Harmony will rely on the kubeconfig provided in the environment where it is running to deploy in the namespace.
|
||||
|
||||
For the CD tool such as Argo or Flux they will be activated by default by Harmony when using application level Scores such as LAMPScore in a similar way that the container is automatically built. Then, CI deployment steps will be notifying the CD tool using its API of the new release to deploy.
|
||||
|
||||
## Rationale
|
||||
|
||||
Reasoning behind the decision
|
||||
|
||||
## Consequences
|
||||
|
||||
Pros/Cons of chosen solution
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
Pros/Cons of various proposed solutions considered
|
||||
|
||||
## Additional Notes
|
||||
78
adr/013-monitoring-notifications.md
Normal file
78
adr/013-monitoring-notifications.md
Normal file
@@ -0,0 +1,78 @@
|
||||
# Architecture Decision Record: Monitoring Notifications
|
||||
|
||||
Initial Author: Taha Hawa
|
||||
|
||||
Initial Date: 2025-06-26
|
||||
|
||||
Last Updated Date: 2025-06-26
|
||||
|
||||
## Status
|
||||
|
||||
Proposed
|
||||
|
||||
## Context
|
||||
|
||||
We need to send notifications (typically from AlertManager/Prometheus) and we need to receive said notifications on mobile devices for sure in some way, whether it's push messages, SMS, phone call, email, etc or all of the above.
|
||||
|
||||
## Decision
|
||||
|
||||
We should go with https://ntfy.sh except host it ourselves.
|
||||
|
||||
`ntfy` is an open source solution written in Go that has the features we need.
|
||||
|
||||
## Rationale
|
||||
|
||||
`ntfy` has pretty much everything we need (push notifications, email forwarding, receives via webhook), and nothing/not much we don't. Good fit, lightweight.
|
||||
|
||||
## Consequences
|
||||
|
||||
Pros:
|
||||
|
||||
- topics, with ACLs
|
||||
- lightweight
|
||||
- reliable
|
||||
- easy to configure
|
||||
- mobile app
|
||||
- the mobile app can listen via websocket, poll, or receive via Firebase/GCM on Android, or similar on iOS.
|
||||
- Forward to email
|
||||
- Text-to-Speech phone call messages using Twilio integration
|
||||
- Operates based on simple HTTP requests/Webhooks, easily usable via AlertManager
|
||||
|
||||
Cons:
|
||||
|
||||
- No SMS pushes
|
||||
- SQLite DB, makes it harder to HA/scale
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
[AWS SNS](https://aws.amazon.com/sns/):
|
||||
Pros:
|
||||
|
||||
- highly reliable
|
||||
- no hosting needed
|
||||
|
||||
Cons:
|
||||
|
||||
- no control, not self hosted
|
||||
- costs (per usage)
|
||||
|
||||
[Apprise](https://github.com/caronc/apprise):
|
||||
Pros:
|
||||
|
||||
- Way more ways of sending notifications
|
||||
- Can use ntfy as one of the backends/ways of sending
|
||||
|
||||
Cons:
|
||||
|
||||
- Way too overkill for what we need in terms of features
|
||||
|
||||
[Gotify](https://github.com/gotify/server):
|
||||
Pros:
|
||||
|
||||
- simple, lightweight, golang, etc
|
||||
|
||||
Cons:
|
||||
|
||||
- Pushes topics are per-user
|
||||
|
||||
## Additional Notes
|
||||
5
check.sh
Executable file
5
check.sh
Executable file
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
cargo check --all-targets --all-features --keep-going
|
||||
cargo fmt --check
|
||||
cargo test
|
||||
1
data/watchguard/pxe-http-files/.gitattributes
vendored
Normal file
1
data/watchguard/pxe-http-files/.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
||||
slitaz/* filter=lfs diff=lfs merge=lfs -text
|
||||
6
data/watchguard/pxe-http-files/boot.ipxe
Normal file
6
data/watchguard/pxe-http-files/boot.ipxe
Normal file
@@ -0,0 +1,6 @@
|
||||
#!ipxe
|
||||
|
||||
set base-url http://192.168.33.1:8080
|
||||
set hostfile ${base-url}/byMAC/01-${mac:hexhyp}.ipxe
|
||||
|
||||
chain ${hostfile} || chain ${base-url}/default.ipxe
|
||||
@@ -0,0 +1,35 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Boot to Slitaz - old linux for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/nvme0n1
|
||||
set ignition-file ncd0/master.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
@@ -0,0 +1,35 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Boot to Slitaz - old linux for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/nvme0n1
|
||||
set ignition-file ncd0/master.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
@@ -0,0 +1,35 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Slitaz - an old linux image for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/sda
|
||||
set ignition-file ncd0/worker.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
@@ -0,0 +1,35 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Boot to Slitaz - old linux for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/nvme0n1
|
||||
set ignition-file ncd0/master.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
@@ -0,0 +1,35 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Slitaz - an old linux image for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/sda
|
||||
set ignition-file ncd0/worker.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
@@ -0,0 +1,37 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item okdinstallation Install OKD
|
||||
item slitaz Slitaz - an old linux image for debugging
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
# This is the bootstrap node
|
||||
# it will become wk2
|
||||
|
||||
#################################
|
||||
# okdinstallation
|
||||
#################################
|
||||
:okdinstallation
|
||||
set base-url http://192.168.33.1:8080
|
||||
set kernel-image fcos/fedora-coreos-39.20231101.3.0-live-kernel-x86_64
|
||||
set live-rootfs fcos/fedora-coreos-39.20231101.3.0-live-rootfs.x86_64.img
|
||||
set live-initramfs fcos/fedora-coreos-39.20231101.3.0-live-initramfs.x86_64.img
|
||||
set install-disk /dev/sda
|
||||
set ignition-file ncd0/worker.ign
|
||||
|
||||
kernel ${base-url}/${kernel-image} initrd=main coreos.live.rootfs_url=${base-url}/${live-rootfs} coreos.inst.install_dev=${install-disk} coreos.inst.ignition_url=${base-url}/${ignition-file} ip=enp1s0:dhcp
|
||||
initrd --name main ${base-url}/${live-initramfs}
|
||||
boot
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
71
data/watchguard/pxe-http-files/default.ipxe
Normal file
71
data/watchguard/pxe-http-files/default.ipxe
Normal file
@@ -0,0 +1,71 @@
|
||||
#!ipxe
|
||||
menu PXE Boot Menu - [${mac}]
|
||||
item local Boot from Hard Disk
|
||||
item slitaz Boot slitaz live environment [tux|root:root]
|
||||
#item ubuntu-server Ubuntu 24.04.1 live server
|
||||
#item ubuntu-desktop Ubuntu 24.04.1 desktop
|
||||
#item systemrescue System Rescue 11.03
|
||||
item memtest memtest
|
||||
#choose --default local --timeout 5000 selected
|
||||
choose selected
|
||||
|
||||
goto ${selected}
|
||||
|
||||
:local
|
||||
exit
|
||||
|
||||
#################################
|
||||
# slitaz
|
||||
#################################
|
||||
:slitaz
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/slitaz
|
||||
kernel ${base_url}/vmlinuz-2.6.37-slitaz rw root=/dev/null vga=788 initrd=rootfs.gz
|
||||
initrd ${base_url}/rootfs.gz
|
||||
boot
|
||||
|
||||
#################################
|
||||
# Ubuntu Server
|
||||
#################################
|
||||
:ubuntu-server
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/ubuntu/live-server-24.04.1
|
||||
|
||||
kernel ${base_url}/vmlinuz ip=dhcp url=${base_url}/ubuntu-24.04.1-live-server-amd64.iso autoinstall ds=nocloud
|
||||
initrd ${base_url}/initrd
|
||||
boot
|
||||
|
||||
#################################
|
||||
# Ubuntu Desktop
|
||||
#################################
|
||||
:ubuntu-desktop
|
||||
set server_ip 192.168.33.1:8080
|
||||
set base_url http://${server_ip}/ubuntu/desktop-24.04.1
|
||||
|
||||
kernel ${base_url}/vmlinuz ip=dhcp url=${base_url}/ubuntu-24.04.1-desktop-amd64.iso autoinstall ds=nocloud
|
||||
initrd ${base_url}/initrd
|
||||
boot
|
||||
|
||||
#################################
|
||||
# System Rescue
|
||||
#################################
|
||||
:systemrescue
|
||||
set base-url http://192.168.33.1:8080/systemrescue
|
||||
|
||||
kernel ${base-url}/vmlinuz initrd=sysresccd.img boot=systemrescue docache
|
||||
initrd ${base-url}/sysresccd.img
|
||||
boot
|
||||
|
||||
#################################
|
||||
# MemTest86 (BIOS/UEFI)
|
||||
#################################
|
||||
:memtest
|
||||
iseq ${platform} efi && goto memtest_efi || goto memtest_bios
|
||||
|
||||
:memtest_efi
|
||||
kernel http://192.168.33.1:8080/memtest/memtest64.efi
|
||||
boot
|
||||
|
||||
:memtest_bios
|
||||
kernel http://192.168.33.1:8080/memtest/memtest64.bin
|
||||
boot
|
||||
BIN
data/watchguard/pxe-http-files/memtest86/memtest32.bin
Normal file
BIN
data/watchguard/pxe-http-files/memtest86/memtest32.bin
Normal file
Binary file not shown.
BIN
data/watchguard/pxe-http-files/memtest86/memtest32.efi
Normal file
BIN
data/watchguard/pxe-http-files/memtest86/memtest32.efi
Normal file
Binary file not shown.
BIN
data/watchguard/pxe-http-files/memtest86/memtest64.bin
Normal file
BIN
data/watchguard/pxe-http-files/memtest86/memtest64.bin
Normal file
Binary file not shown.
BIN
data/watchguard/pxe-http-files/memtest86/memtest64.efi
Normal file
BIN
data/watchguard/pxe-http-files/memtest86/memtest64.efi
Normal file
Binary file not shown.
BIN
data/watchguard/pxe-http-files/memtest86/memtestla64.efi
Normal file
BIN
data/watchguard/pxe-http-files/memtest86/memtestla64.efi
Normal file
Binary file not shown.
@@ -1 +0,0 @@
|
||||
hey i am paul
|
||||
BIN
data/watchguard/pxe-http-files/slitaz/rootfs.gz
(Stored with Git LFS)
Normal file
BIN
data/watchguard/pxe-http-files/slitaz/rootfs.gz
(Stored with Git LFS)
Normal file
Binary file not shown.
BIN
data/watchguard/pxe-http-files/slitaz/vmlinuz-2.6.37-slitaz
(Stored with Git LFS)
Normal file
BIN
data/watchguard/pxe-http-files/slitaz/vmlinuz-2.6.37-slitaz
(Stored with Git LFS)
Normal file
Binary file not shown.
BIN
data/watchguard/tftpboot/ipxe.efi
Normal file
BIN
data/watchguard/tftpboot/ipxe.efi
Normal file
Binary file not shown.
BIN
data/watchguard/tftpboot/undionly.kpxe
Normal file
BIN
data/watchguard/tftpboot/undionly.kpxe
Normal file
Binary file not shown.
1
docs/README.md
Normal file
1
docs/README.md
Normal file
@@ -0,0 +1 @@
|
||||
Not much here yet, see the `adr` folder for now. More to come in time!
|
||||
13
docs/cyborg-metaphor.md
Normal file
13
docs/cyborg-metaphor.md
Normal file
@@ -0,0 +1,13 @@
|
||||
## Conceptual metaphor : The Cyborg and the Central Nervous System
|
||||
|
||||
At the heart of Harmony lies a core belief: in modern, decentralized systems, **software and infrastructure are not separate entities.** They are a single, symbiotic organism—a cyborg.
|
||||
|
||||
The software is the electronics, the "mind"; the infrastructure is the biological host, the "body". They live or die, thrive or sink together.
|
||||
|
||||
Traditional approaches attempt to manage this complex organism with fragmented tools: static YAML for configuration, brittle scripts for automation, and separate Infrastructure as Code (IaC) for provisioning. This creates a disjointed system that struggles to scale or heal itself, making it inadequate for the demands of fully automated, enterprise-grade clusters.
|
||||
|
||||
Harmony's goal is to provide the **central nervous system for this cyborg**. We aim to achieve the full automation of complex, decentralized clouds by managing this integrated entity holistically.
|
||||
|
||||
To achieve this, a tool must be both robust and powerful. It must manage the entire lifecycle—deployment, upgrades, failure recovery, and decommissioning—with precision. This requires full control over application packaging and a deep, intrinsic integration between the software and the infrastructure it inhabits.
|
||||
|
||||
This is why Harmony uses a powerful, living language like Rust. It replaces static, lifeless configuration files with a dynamic, breathing codebase. It allows us to express the complex relationships and behaviors of a modern distributed system, enabling the creation of truly automated, resilient, and powerful platforms that can thrive.
|
||||
4
docs/diagrams/Harmony_Core_Architecture.drawio.svg
Normal file
4
docs/diagrams/Harmony_Core_Architecture.drawio.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 1.1 MiB |
19
examples/cli/Cargo.toml
Normal file
19
examples/cli/Cargo.toml
Normal file
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "example-cli"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
assert_cmd = "2.0.16"
|
||||
20
examples/cli/src/main.rs
Normal file
20
examples/cli/src/main.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::dummy::{ErrorScore, PanicScore, SuccessScore},
|
||||
topology::LocalhostTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let inventory = Inventory::autoload();
|
||||
let topology = LocalhostTopology::new();
|
||||
let mut maestro = Maestro::initialize(inventory, topology).await.unwrap();
|
||||
|
||||
maestro.register_all(vec![
|
||||
Box::new(SuccessScore {}),
|
||||
Box::new(ErrorScore {}),
|
||||
Box::new(PanicScore {}),
|
||||
]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
@@ -14,7 +14,8 @@ harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
kube = "0.98.0"
|
||||
k8s-openapi = { version = "0.24.0", features = [ "v1_30" ] }
|
||||
kube = "1.1.0"
|
||||
k8s-openapi = { version = "0.25.0", features = ["v1_30"] }
|
||||
http = "1.2.0"
|
||||
serde_yaml = "0.9.34"
|
||||
inquire.workspace = true
|
||||
|
||||
@@ -1,20 +1,32 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use harmony_macros::yaml;
|
||||
use inquire::Confirm;
|
||||
use k8s_openapi::{
|
||||
api::{
|
||||
apps::v1::{Deployment, DeploymentSpec},
|
||||
core::v1::{Container, Node, Pod, PodSpec, PodTemplateSpec},
|
||||
core::v1::{Container, PodSpec, PodTemplateSpec},
|
||||
},
|
||||
apimachinery::pkg::apis::meta::v1::LabelSelector,
|
||||
};
|
||||
use kube::{
|
||||
Api, Client, Config, ResourceExt,
|
||||
api::{ListParams, ObjectMeta, PostParams},
|
||||
Api, Client, ResourceExt,
|
||||
api::{ObjectMeta, PostParams},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let confirmation = Confirm::new(
|
||||
"This will install various ressources to your default kubernetes cluster. Are you sure?",
|
||||
)
|
||||
.with_default(false)
|
||||
.prompt()
|
||||
.expect("Unexpected prompt error");
|
||||
|
||||
if !confirmation {
|
||||
return;
|
||||
}
|
||||
|
||||
let client = Client::try_default()
|
||||
.await
|
||||
.expect("Should instanciate client from defaults");
|
||||
@@ -42,8 +54,7 @@ async fn main() {
|
||||
// println!("found node {} status {:?}", n.name_any(), n.status.unwrap())
|
||||
// }
|
||||
|
||||
let nginxdeployment = nginx_deployment_2();
|
||||
let nginxdeployment = nginx_deployment_serde();
|
||||
assert_eq!(nginx_deployment(), nginx_macro());
|
||||
assert_eq!(nginx_deployment_2(), nginx_macro());
|
||||
assert_eq!(nginx_deployment_serde(), nginx_macro());
|
||||
let nginxdeployment = nginx_macro();
|
||||
@@ -149,6 +160,7 @@ fn nginx_deployment_2() -> Deployment {
|
||||
|
||||
deployment
|
||||
}
|
||||
|
||||
fn nginx_deployment() -> Deployment {
|
||||
let deployment = Deployment {
|
||||
metadata: ObjectMeta {
|
||||
|
||||
18
examples/lamp/Cargo.toml
Normal file
18
examples/lamp/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "example-lamp"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
85
examples/lamp/php/index.php
Normal file
85
examples/lamp/php/index.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
ini_set('display_errors', 1);
|
||||
error_reporting(E_ALL);
|
||||
|
||||
$host = getenv('MYSQL_HOST') ?: '';
|
||||
$user = getenv('MYSQL_USER') ?: 'root';
|
||||
$pass = getenv('MYSQL_PASSWORD') ?: '';
|
||||
$db = 'testfill';
|
||||
$charset = 'utf8mb4';
|
||||
|
||||
$dsn = "mysql:host=$host;charset=$charset";
|
||||
$options = [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
];
|
||||
|
||||
try {
|
||||
$pdo = new PDO($dsn, $user, $pass, $options);
|
||||
$pdo->exec("CREATE DATABASE IF NOT EXISTS `$db`");
|
||||
$pdo->exec("USE `$db`");
|
||||
$pdo->exec("
|
||||
CREATE TABLE IF NOT EXISTS filler (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
data LONGBLOB
|
||||
)
|
||||
");
|
||||
} catch (\PDOException $e) {
|
||||
die("❌ DB connection failed: " . $e->getMessage());
|
||||
}
|
||||
|
||||
function getDbStats($pdo, $db) {
|
||||
$stmt = $pdo->query("
|
||||
SELECT
|
||||
ROUND(SUM(data_length + index_length) / 1024 / 1024 / 1024, 2) AS total_size_gb,
|
||||
SUM(table_rows) AS total_rows
|
||||
FROM information_schema.tables
|
||||
WHERE table_schema = '$db'
|
||||
");
|
||||
$result = $stmt->fetch();
|
||||
$sizeGb = $result['total_size_gb'] ?? '0';
|
||||
$rows = $result['total_rows'] ?? '0';
|
||||
$avgMb = ($rows > 0) ? round(($sizeGb * 1024) / $rows, 2) : 0;
|
||||
return [$sizeGb, $rows, $avgMb];
|
||||
}
|
||||
|
||||
list($dbSize, $rowCount, $avgRowMb) = getDbStats($pdo, $db);
|
||||
|
||||
$message = '';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fill'])) {
|
||||
$iterations = 1024;
|
||||
$data = str_repeat(random_bytes(1024), 1024); // 1MB
|
||||
$stmt = $pdo->prepare("INSERT INTO filler (data) VALUES (:data)");
|
||||
|
||||
for ($i = 0; $i < $iterations; $i++) {
|
||||
$stmt->execute([':data' => $data]);
|
||||
}
|
||||
|
||||
list($dbSize, $rowCount, $avgRowMb) = getDbStats($pdo, $db);
|
||||
|
||||
$message = "<p style='color: green;'>✅ 1GB inserted into MariaDB successfully.</p>";
|
||||
}
|
||||
?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>MariaDB Filler</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>MariaDB Storage Filler</h1>
|
||||
<?= $message ?>
|
||||
<ul>
|
||||
<li><strong>📦 MariaDB Used Size:</strong> <?= $dbSize ?> GB</li>
|
||||
<li><strong>📊 Total Rows:</strong> <?= $rowCount ?></li>
|
||||
<li><strong>📐 Average Row Size:</strong> <?= $avgRowMb ?> MB</li>
|
||||
</ul>
|
||||
|
||||
<form method="post">
|
||||
<button name="fill" value="1" type="submit">Insert 1GB into DB</button>
|
||||
</form>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
57
examples/lamp/src/main.rs
Normal file
57
examples/lamp/src/main.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use harmony::{
|
||||
data::Version,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::lamp::{LAMPConfig, LAMPScore},
|
||||
topology::{K8sAnywhereTopology, Url},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// This here is the whole configuration to
|
||||
// - setup a local K3D cluster
|
||||
// - Build a docker image with the PHP project builtin and production grade settings
|
||||
// - Deploy a mariadb database using a production grade helm chart
|
||||
// - Deploy the new container using a kubernetes deployment
|
||||
// - Configure networking between the PHP container and the database
|
||||
// - Provision a public route and an SSL certificate automatically on production environments
|
||||
//
|
||||
// Enjoy :)
|
||||
let lamp_stack = LAMPScore {
|
||||
name: "harmony-lamp-demo".to_string(),
|
||||
domain: Url::Url(url::Url::parse("https://lampdemo.harmony.nationtech.io").unwrap()),
|
||||
php_version: Version::from("8.4.4").unwrap(),
|
||||
// This config can be extended as needed for more complicated configurations
|
||||
config: LAMPConfig {
|
||||
project_root: "./php".into(),
|
||||
database_size: format!("4Gi").into(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
//let monitoring = MonitoringAlertingScore {
|
||||
// alert_receivers: vec![Box::new(DiscordWebhook {
|
||||
// url: Url::Url(url::Url::parse("https://discord.idonotexist.com").unwrap()),
|
||||
// // TODO write url macro
|
||||
// // url: url!("https://discord.idonotexist.com"),
|
||||
// })],
|
||||
// alert_rules: vec![],
|
||||
// scrape_targets: vec![],
|
||||
//};
|
||||
|
||||
// You can choose the type of Topology you want, we suggest starting with the
|
||||
// K8sAnywhereTopology as it is the most automatic one that enables you to easily deploy
|
||||
// locally, to development environment from a CI, to staging, and to production with settings
|
||||
// that automatically adapt to each environment grade.
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
maestro.register_all(vec![Box::new(lamp_stack)]);
|
||||
// Here we bootstrap the CLI, this gives some nice features if you need them
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
// That's it, end of the infra as code.
|
||||
13
examples/monitoring/Cargo.toml
Normal file
13
examples/monitoring/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "example-monitoring"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harmony = { version = "0.1.0", path = "../../harmony" }
|
||||
harmony_cli = { version = "0.1.0", path = "../../harmony_cli" }
|
||||
harmony_macros = { version = "0.1.0", path = "../../harmony_macros" }
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
86
examples/monitoring/src/main.rs
Normal file
86
examples/monitoring/src/main.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
monitoring::{
|
||||
alert_channel::discord_alert_channel::DiscordWebhook,
|
||||
alert_rule::prometheus_alert_rule::AlertManagerRuleGroup,
|
||||
kube_prometheus::{
|
||||
helm_prometheus_alert_score::HelmPrometheusAlertingScore,
|
||||
types::{
|
||||
HTTPScheme, MatchExpression, Operator, Selector, ServiceMonitor,
|
||||
ServiceMonitorEndpoint,
|
||||
},
|
||||
},
|
||||
},
|
||||
prometheus::alerts::{
|
||||
infra::dell_server::{
|
||||
alert_global_storage_status_critical, alert_global_storage_status_non_recoverable,
|
||||
global_storage_status_degraded_non_critical,
|
||||
},
|
||||
k8s::pvc::high_pvc_fill_rate_over_two_days,
|
||||
},
|
||||
},
|
||||
topology::{K8sAnywhereTopology, Url},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let discord_receiver = DiscordWebhook {
|
||||
name: "test-discord".to_string(),
|
||||
url: Url::Url(url::Url::parse("https://discord.doesnt.exist.com").unwrap()),
|
||||
};
|
||||
|
||||
let high_pvc_fill_rate_over_two_days_alert = high_pvc_fill_rate_over_two_days();
|
||||
let dell_system_storage_degraded = global_storage_status_degraded_non_critical();
|
||||
let alert_global_storage_status_critical = alert_global_storage_status_critical();
|
||||
let alert_global_storage_status_non_recoverable = alert_global_storage_status_non_recoverable();
|
||||
|
||||
let additional_rules =
|
||||
AlertManagerRuleGroup::new("pvc-alerts", vec![high_pvc_fill_rate_over_two_days_alert]);
|
||||
let additional_rules2 = AlertManagerRuleGroup::new(
|
||||
"dell-server-alerts",
|
||||
vec![
|
||||
dell_system_storage_degraded,
|
||||
alert_global_storage_status_critical,
|
||||
alert_global_storage_status_non_recoverable,
|
||||
],
|
||||
);
|
||||
|
||||
let service_monitor_endpoint = ServiceMonitorEndpoint {
|
||||
port: Some("80".to_string()),
|
||||
path: "/metrics".to_string(),
|
||||
scheme: HTTPScheme::HTTP,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let service_monitor = ServiceMonitor {
|
||||
name: "test-service-monitor".to_string(),
|
||||
selector: Selector {
|
||||
match_labels: HashMap::new(),
|
||||
match_expressions: vec![MatchExpression {
|
||||
key: "test".to_string(),
|
||||
operator: Operator::In,
|
||||
values: vec!["test-service".to_string()],
|
||||
}],
|
||||
},
|
||||
endpoints: vec![service_monitor_endpoint],
|
||||
..Default::default()
|
||||
};
|
||||
let alerting_score = HelmPrometheusAlertingScore {
|
||||
receivers: vec![Box::new(discord_receiver)],
|
||||
rules: vec![Box::new(additional_rules), Box::new(additional_rules2)],
|
||||
service_monitors: vec![service_monitor],
|
||||
};
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
maestro.register_all(vec![Box::new(alerting_score)]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
13
examples/monitoring_with_tenant/Cargo.toml
Normal file
13
examples/monitoring_with_tenant/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "example-monitoring-with-tenant"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
cidr.workspace = true
|
||||
harmony = { version = "0.1.0", path = "../../harmony" }
|
||||
harmony_cli = { version = "0.1.0", path = "../../harmony_cli" }
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
90
examples/monitoring_with_tenant/src/main.rs
Normal file
90
examples/monitoring_with_tenant/src/main.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use harmony::{
|
||||
data::Id,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{
|
||||
monitoring::{
|
||||
alert_channel::discord_alert_channel::DiscordWebhook,
|
||||
alert_rule::prometheus_alert_rule::AlertManagerRuleGroup,
|
||||
kube_prometheus::{
|
||||
helm_prometheus_alert_score::HelmPrometheusAlertingScore,
|
||||
types::{
|
||||
HTTPScheme, MatchExpression, Operator, Selector, ServiceMonitor,
|
||||
ServiceMonitorEndpoint,
|
||||
},
|
||||
},
|
||||
},
|
||||
prometheus::alerts::k8s::pvc::high_pvc_fill_rate_over_two_days,
|
||||
tenant::TenantScore,
|
||||
},
|
||||
topology::{
|
||||
K8sAnywhereTopology, Url,
|
||||
tenant::{ResourceLimits, TenantConfig, TenantNetworkPolicy},
|
||||
},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let tenant = TenantScore {
|
||||
config: TenantConfig {
|
||||
id: Id::from_string("1234".to_string()),
|
||||
name: "test-tenant".to_string(),
|
||||
resource_limits: ResourceLimits {
|
||||
cpu_request_cores: 6.0,
|
||||
cpu_limit_cores: 4.0,
|
||||
memory_request_gb: 4.0,
|
||||
memory_limit_gb: 4.0,
|
||||
storage_total_gb: 10.0,
|
||||
},
|
||||
network_policy: TenantNetworkPolicy::default(),
|
||||
},
|
||||
};
|
||||
|
||||
let discord_receiver = DiscordWebhook {
|
||||
name: "test-discord".to_string(),
|
||||
url: Url::Url(url::Url::parse("https://discord.doesnt.exist.com").unwrap()),
|
||||
};
|
||||
|
||||
let high_pvc_fill_rate_over_two_days_alert = high_pvc_fill_rate_over_two_days();
|
||||
|
||||
let additional_rules =
|
||||
AlertManagerRuleGroup::new("pvc-alerts", vec![high_pvc_fill_rate_over_two_days_alert]);
|
||||
|
||||
let service_monitor_endpoint = ServiceMonitorEndpoint {
|
||||
port: Some("80".to_string()),
|
||||
path: "/metrics".to_string(),
|
||||
scheme: HTTPScheme::HTTP,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let service_monitor = ServiceMonitor {
|
||||
name: "test-service-monitor".to_string(),
|
||||
selector: Selector {
|
||||
match_labels: HashMap::new(),
|
||||
match_expressions: vec![MatchExpression {
|
||||
key: "test".to_string(),
|
||||
operator: Operator::In,
|
||||
values: vec!["test-service".to_string()],
|
||||
}],
|
||||
},
|
||||
endpoints: vec![service_monitor_endpoint],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let alerting_score = HelmPrometheusAlertingScore {
|
||||
receivers: vec![Box::new(discord_receiver)],
|
||||
rules: vec![Box::new(additional_rules)],
|
||||
service_monitors: vec![service_monitor],
|
||||
};
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
maestro.register_all(vec![Box::new(tenant), Box::new(alerting_score)]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/bash
|
||||
|
||||
helm install --create-namespace --namespace rook-ceph rook-ceph-cluster \
|
||||
--set operatorNamespace=rook-ceph rook-release/rook-ceph-cluster -f values.yaml
|
||||
721
examples/nanodc/rook-cephcluster/values.yaml
Normal file
721
examples/nanodc/rook-cephcluster/values.yaml
Normal file
@@ -0,0 +1,721 @@
|
||||
# Default values for a single rook-ceph cluster
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
# -- Namespace of the main rook operator
|
||||
operatorNamespace: rook-ceph
|
||||
|
||||
# -- The metadata.name of the CephCluster CR
|
||||
# @default -- The same as the namespace
|
||||
clusterName:
|
||||
|
||||
# -- Optional override of the target kubernetes version
|
||||
kubeVersion:
|
||||
|
||||
# -- Cluster ceph.conf override
|
||||
configOverride:
|
||||
# configOverride: |
|
||||
# [global]
|
||||
# mon_allow_pool_delete = true
|
||||
# osd_pool_default_size = 3
|
||||
# osd_pool_default_min_size = 2
|
||||
|
||||
# Installs a debugging toolbox deployment
|
||||
toolbox:
|
||||
# -- Enable Ceph debugging pod deployment. See [toolbox](../Troubleshooting/ceph-toolbox.md)
|
||||
enabled: true
|
||||
# -- Toolbox image, defaults to the image used by the Ceph cluster
|
||||
image: #quay.io/ceph/ceph:v19.2.2
|
||||
# -- Toolbox tolerations
|
||||
tolerations: []
|
||||
# -- Toolbox affinity
|
||||
affinity: {}
|
||||
# -- Toolbox container security context
|
||||
containerSecurityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 2016
|
||||
runAsGroup: 2016
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
# -- Toolbox resources
|
||||
resources:
|
||||
limits:
|
||||
memory: "1Gi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "128Mi"
|
||||
# -- Set the priority class for the toolbox if desired
|
||||
priorityClassName:
|
||||
|
||||
monitoring:
|
||||
# -- Enable Prometheus integration, will also create necessary RBAC rules to allow Operator to create ServiceMonitors.
|
||||
# Monitoring requires Prometheus to be pre-installed
|
||||
enabled: false
|
||||
# -- Whether to disable the metrics reported by Ceph. If false, the prometheus mgr module and Ceph exporter are enabled
|
||||
metricsDisabled: false
|
||||
# -- Whether to create the Prometheus rules for Ceph alerts
|
||||
createPrometheusRules: false
|
||||
# -- The namespace in which to create the prometheus rules, if different from the rook cluster namespace.
|
||||
# If you have multiple rook-ceph clusters in the same k8s cluster, choose the same namespace (ideally, namespace with prometheus
|
||||
# deployed) to set rulesNamespaceOverride for all the clusters. Otherwise, you will get duplicate alerts with multiple alert definitions.
|
||||
rulesNamespaceOverride:
|
||||
# Monitoring settings for external clusters:
|
||||
# externalMgrEndpoints: <list of endpoints>
|
||||
# externalMgrPrometheusPort: <port>
|
||||
# Scrape interval for prometheus
|
||||
# interval: 10s
|
||||
# allow adding custom labels and annotations to the prometheus rule
|
||||
prometheusRule:
|
||||
# -- Labels applied to PrometheusRule
|
||||
labels: {}
|
||||
# -- Annotations applied to PrometheusRule
|
||||
annotations: {}
|
||||
|
||||
# -- Create & use PSP resources. Set this to the same value as the rook-ceph chart.
|
||||
pspEnable: false
|
||||
|
||||
# imagePullSecrets option allow to pull docker images from private docker registry. Option will be passed to all service accounts.
|
||||
# imagePullSecrets:
|
||||
# - name: my-registry-secret
|
||||
|
||||
# All values below are taken from the CephCluster CRD
|
||||
# -- Cluster configuration.
|
||||
# @default -- See [below](#ceph-cluster-spec)
|
||||
cephClusterSpec:
|
||||
# This cluster spec example is for a converged cluster where all the Ceph daemons are running locally,
|
||||
# as in the host-based example (cluster.yaml). For a different configuration such as a
|
||||
# PVC-based cluster (cluster-on-pvc.yaml), external cluster (cluster-external.yaml),
|
||||
# or stretch cluster (cluster-stretched.yaml), replace this entire `cephClusterSpec`
|
||||
# with the specs from those examples.
|
||||
|
||||
# For more details, check https://rook.io/docs/rook/v1.10/CRDs/Cluster/ceph-cluster-crd/
|
||||
cephVersion:
|
||||
# The container image used to launch the Ceph daemon pods (mon, mgr, osd, mds, rgw).
|
||||
# v18 is Reef, v19 is Squid
|
||||
# RECOMMENDATION: In production, use a specific version tag instead of the general v18 flag, which pulls the latest release and could result in different
|
||||
# versions running within the cluster. See tags available at https://hub.docker.com/r/ceph/ceph/tags/.
|
||||
# If you want to be more precise, you can always use a timestamp tag such as quay.io/ceph/ceph:v19.2.2-20250409
|
||||
# This tag might not contain a new Ceph version, just security fixes from the underlying operating system, which will reduce vulnerabilities
|
||||
image: quay.io/ceph/ceph:v19.2.2
|
||||
# Whether to allow unsupported versions of Ceph. Currently Reef and Squid are supported.
|
||||
# Future versions such as Tentacle (v20) would require this to be set to `true`.
|
||||
# Do not set to true in production.
|
||||
allowUnsupported: false
|
||||
|
||||
# The path on the host where configuration files will be persisted. Must be specified. If there are multiple clusters, the directory must be unique for each cluster.
|
||||
# Important: if you reinstall the cluster, make sure you delete this directory from each host or else the mons will fail to start on the new cluster.
|
||||
# In Minikube, the '/data' directory is configured to persist across reboots. Use "/data/rook" in Minikube environment.
|
||||
dataDirHostPath: /var/lib/rook
|
||||
|
||||
# Whether or not upgrade should continue even if a check fails
|
||||
# This means Ceph's status could be degraded and we don't recommend upgrading but you might decide otherwise
|
||||
# Use at your OWN risk
|
||||
# To understand Rook's upgrade process of Ceph, read https://rook.io/docs/rook/v1.10/Upgrade/ceph-upgrade/
|
||||
skipUpgradeChecks: false
|
||||
|
||||
# Whether or not continue if PGs are not clean during an upgrade
|
||||
continueUpgradeAfterChecksEvenIfNotHealthy: false
|
||||
|
||||
# WaitTimeoutForHealthyOSDInMinutes defines the time (in minutes) the operator would wait before an OSD can be stopped for upgrade or restart.
|
||||
# If the timeout exceeds and OSD is not ok to stop, then the operator would skip upgrade for the current OSD and proceed with the next one
|
||||
# if `continueUpgradeAfterChecksEvenIfNotHealthy` is `false`. If `continueUpgradeAfterChecksEvenIfNotHealthy` is `true`, then operator would
|
||||
# continue with the upgrade of an OSD even if its not ok to stop after the timeout. This timeout won't be applied if `skipUpgradeChecks` is `true`.
|
||||
# The default wait timeout is 10 minutes.
|
||||
waitTimeoutForHealthyOSDInMinutes: 10
|
||||
|
||||
# Whether or not requires PGs are clean before an OSD upgrade. If set to `true` OSD upgrade process won't start until PGs are healthy.
|
||||
# This configuration will be ignored if `skipUpgradeChecks` is `true`.
|
||||
# Default is false.
|
||||
upgradeOSDRequiresHealthyPGs: false
|
||||
|
||||
mon:
|
||||
# Set the number of mons to be started. Generally recommended to be 3.
|
||||
# For highest availability, an odd number of mons should be specified.
|
||||
count: 3
|
||||
# The mons should be on unique nodes. For production, at least 3 nodes are recommended for this reason.
|
||||
# Mons should only be allowed on the same node for test environments where data loss is acceptable.
|
||||
allowMultiplePerNode: false
|
||||
|
||||
mgr:
|
||||
# When higher availability of the mgr is needed, increase the count to 2.
|
||||
# In that case, one mgr will be active and one in standby. When Ceph updates which
|
||||
# mgr is active, Rook will update the mgr services to match the active mgr.
|
||||
count: 2
|
||||
allowMultiplePerNode: false
|
||||
modules:
|
||||
# List of modules to optionally enable or disable.
|
||||
# Note the "dashboard" and "monitoring" modules are already configured by other settings in the cluster CR.
|
||||
# - name: rook
|
||||
# enabled: true
|
||||
|
||||
# enable the ceph dashboard for viewing cluster status
|
||||
dashboard:
|
||||
enabled: true
|
||||
# serve the dashboard under a subpath (useful when you are accessing the dashboard via a reverse proxy)
|
||||
# urlPrefix: /ceph-dashboard
|
||||
# serve the dashboard at the given port.
|
||||
# port: 8443
|
||||
# Serve the dashboard using SSL (if using ingress to expose the dashboard and `ssl: true` you need to set
|
||||
# the corresponding "backend protocol" annotation(s) for your ingress controller of choice)
|
||||
ssl: true
|
||||
|
||||
# Network configuration, see: https://github.com/rook/rook/blob/master/Documentation/CRDs/Cluster/ceph-cluster-crd.md#network-configuration-settings
|
||||
network:
|
||||
connections:
|
||||
# Whether to encrypt the data in transit across the wire to prevent eavesdropping the data on the network.
|
||||
# The default is false. When encryption is enabled, all communication between clients and Ceph daemons, or between Ceph daemons will be encrypted.
|
||||
# When encryption is not enabled, clients still establish a strong initial authentication and data integrity is still validated with a crc check.
|
||||
# IMPORTANT: Encryption requires the 5.11 kernel for the latest nbd and cephfs drivers. Alternatively for testing only,
|
||||
# you can set the "mounter: rbd-nbd" in the rbd storage class, or "mounter: fuse" in the cephfs storage class.
|
||||
# The nbd and fuse drivers are *not* recommended in production since restarting the csi driver pod will disconnect the volumes.
|
||||
encryption:
|
||||
enabled: false
|
||||
# Whether to compress the data in transit across the wire. The default is false.
|
||||
# The kernel requirements above for encryption also apply to compression.
|
||||
compression:
|
||||
enabled: false
|
||||
# Whether to require communication over msgr2. If true, the msgr v1 port (6789) will be disabled
|
||||
# and clients will be required to connect to the Ceph cluster with the v2 port (3300).
|
||||
# Requires a kernel that supports msgr v2 (kernel 5.11 or CentOS 8.4 or newer).
|
||||
requireMsgr2: false
|
||||
# # enable host networking
|
||||
# provider: host
|
||||
# # EXPERIMENTAL: enable the Multus network provider
|
||||
# provider: multus
|
||||
# selectors:
|
||||
# # The selector keys are required to be `public` and `cluster`.
|
||||
# # Based on the configuration, the operator will do the following:
|
||||
# # 1. if only the `public` selector key is specified both public_network and cluster_network Ceph settings will listen on that interface
|
||||
# # 2. if both `public` and `cluster` selector keys are specified the first one will point to 'public_network' flag and the second one to 'cluster_network'
|
||||
# #
|
||||
# # In order to work, each selector value must match a NetworkAttachmentDefinition object in Multus
|
||||
# #
|
||||
# # public: public-conf --> NetworkAttachmentDefinition object name in Multus
|
||||
# # cluster: cluster-conf --> NetworkAttachmentDefinition object name in Multus
|
||||
# # Provide internet protocol version. IPv6, IPv4 or empty string are valid options. Empty string would mean IPv4
|
||||
# ipFamily: "IPv6"
|
||||
# # Ceph daemons to listen on both IPv4 and Ipv6 networks
|
||||
# dualStack: false
|
||||
|
||||
# enable the crash collector for ceph daemon crash collection
|
||||
crashCollector:
|
||||
disable: false
|
||||
# Uncomment daysToRetain to prune ceph crash entries older than the
|
||||
# specified number of days.
|
||||
# daysToRetain: 30
|
||||
|
||||
# enable log collector, daemons will log on files and rotate
|
||||
logCollector:
|
||||
enabled: true
|
||||
periodicity: daily # one of: hourly, daily, weekly, monthly
|
||||
maxLogSize: 500M # SUFFIX may be 'M' or 'G'. Must be at least 1M.
|
||||
|
||||
# automate [data cleanup process](https://github.com/rook/rook/blob/master/Documentation/Storage-Configuration/ceph-teardown.md#delete-the-data-on-hosts) in cluster destruction.
|
||||
cleanupPolicy:
|
||||
# Since cluster cleanup is destructive to data, confirmation is required.
|
||||
# To destroy all Rook data on hosts during uninstall, confirmation must be set to "yes-really-destroy-data".
|
||||
# This value should only be set when the cluster is about to be deleted. After the confirmation is set,
|
||||
# Rook will immediately stop configuring the cluster and only wait for the delete command.
|
||||
# If the empty string is set, Rook will not destroy any data on hosts during uninstall.
|
||||
confirmation: ""
|
||||
# sanitizeDisks represents settings for sanitizing OSD disks on cluster deletion
|
||||
sanitizeDisks:
|
||||
# method indicates if the entire disk should be sanitized or simply ceph's metadata
|
||||
# in both case, re-install is possible
|
||||
# possible choices are 'complete' or 'quick' (default)
|
||||
method: quick
|
||||
# dataSource indicate where to get random bytes from to write on the disk
|
||||
# possible choices are 'zero' (default) or 'random'
|
||||
# using random sources will consume entropy from the system and will take much more time then the zero source
|
||||
dataSource: zero
|
||||
# iteration overwrite N times instead of the default (1)
|
||||
# takes an integer value
|
||||
iteration: 1
|
||||
# allowUninstallWithVolumes defines how the uninstall should be performed
|
||||
# If set to true, cephCluster deletion does not wait for the PVs to be deleted.
|
||||
allowUninstallWithVolumes: false
|
||||
|
||||
# To control where various services will be scheduled by kubernetes, use the placement configuration sections below.
|
||||
# The example under 'all' would have all services scheduled on kubernetes nodes labeled with 'role=storage-node' and
|
||||
# tolerate taints with a key of 'storage-node'.
|
||||
# placement:
|
||||
# all:
|
||||
# nodeAffinity:
|
||||
# requiredDuringSchedulingIgnoredDuringExecution:
|
||||
# nodeSelectorTerms:
|
||||
# - matchExpressions:
|
||||
# - key: role
|
||||
# operator: In
|
||||
# values:
|
||||
# - storage-node
|
||||
# podAffinity:
|
||||
# podAntiAffinity:
|
||||
# topologySpreadConstraints:
|
||||
# tolerations:
|
||||
# - key: storage-node
|
||||
# operator: Exists
|
||||
# # The above placement information can also be specified for mon, osd, and mgr components
|
||||
# mon:
|
||||
# # Monitor deployments may contain an anti-affinity rule for avoiding monitor
|
||||
# # collocation on the same node. This is a required rule when host network is used
|
||||
# # or when AllowMultiplePerNode is false. Otherwise this anti-affinity rule is a
|
||||
# # preferred rule with weight: 50.
|
||||
# osd:
|
||||
# mgr:
|
||||
# cleanup:
|
||||
|
||||
# annotations:
|
||||
# all:
|
||||
# mon:
|
||||
# osd:
|
||||
# cleanup:
|
||||
# prepareosd:
|
||||
# # If no mgr annotations are set, prometheus scrape annotations will be set by default.
|
||||
# mgr:
|
||||
# dashboard:
|
||||
|
||||
# labels:
|
||||
# all:
|
||||
# mon:
|
||||
# osd:
|
||||
# cleanup:
|
||||
# mgr:
|
||||
# prepareosd:
|
||||
# # monitoring is a list of key-value pairs. It is injected into all the monitoring resources created by operator.
|
||||
# # These labels can be passed as LabelSelector to Prometheus
|
||||
# monitoring:
|
||||
# dashboard:
|
||||
|
||||
resources:
|
||||
mgr:
|
||||
limits:
|
||||
memory: "1Gi"
|
||||
requests:
|
||||
cpu: "500m"
|
||||
memory: "512Mi"
|
||||
mon:
|
||||
limits:
|
||||
memory: "2Gi"
|
||||
requests:
|
||||
cpu: "1000m"
|
||||
memory: "1Gi"
|
||||
osd:
|
||||
limits:
|
||||
memory: "4Gi"
|
||||
requests:
|
||||
cpu: "1000m"
|
||||
memory: "4Gi"
|
||||
prepareosd:
|
||||
# limits: It is not recommended to set limits on the OSD prepare job
|
||||
# since it's a one-time burst for memory that must be allowed to
|
||||
# complete without an OOM kill. Note however that if a k8s
|
||||
# limitRange guardrail is defined external to Rook, the lack of
|
||||
# a limit here may result in a sync failure, in which case a
|
||||
# limit should be added. 1200Mi may suffice for up to 15Ti
|
||||
# OSDs ; for larger devices 2Gi may be required.
|
||||
# cf. https://github.com/rook/rook/pull/11103
|
||||
requests:
|
||||
cpu: "500m"
|
||||
memory: "50Mi"
|
||||
mgr-sidecar:
|
||||
limits:
|
||||
memory: "100Mi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "40Mi"
|
||||
crashcollector:
|
||||
limits:
|
||||
memory: "60Mi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "60Mi"
|
||||
logcollector:
|
||||
limits:
|
||||
memory: "1Gi"
|
||||
requests:
|
||||
cpu: "100m"
|
||||
memory: "100Mi"
|
||||
cleanup:
|
||||
limits:
|
||||
memory: "1Gi"
|
||||
requests:
|
||||
cpu: "500m"
|
||||
memory: "100Mi"
|
||||
exporter:
|
||||
limits:
|
||||
memory: "128Mi"
|
||||
requests:
|
||||
cpu: "50m"
|
||||
memory: "50Mi"
|
||||
|
||||
# The option to automatically remove OSDs that are out and are safe to destroy.
|
||||
removeOSDsIfOutAndSafeToRemove: false
|
||||
|
||||
# priority classes to apply to ceph resources
|
||||
priorityClassNames:
|
||||
mon: system-node-critical
|
||||
osd: system-node-critical
|
||||
mgr: system-cluster-critical
|
||||
|
||||
storage: # cluster level storage configuration and selection
|
||||
useAllNodes: true
|
||||
useAllDevices: true
|
||||
# deviceFilter:
|
||||
# config:
|
||||
# crushRoot: "custom-root" # specify a non-default root label for the CRUSH map
|
||||
# metadataDevice: "md0" # specify a non-rotational storage so ceph-volume will use it as block db device of bluestore.
|
||||
# databaseSizeMB: "1024" # uncomment if the disks are smaller than 100 GB
|
||||
# osdsPerDevice: "1" # this value can be overridden at the node or device level
|
||||
# encryptedDevice: "true" # the default value for this option is "false"
|
||||
# # Individual nodes and their config can be specified as well, but 'useAllNodes' above must be set to false. Then, only the named
|
||||
# # nodes below will be used as storage resources. Each node's 'name' field should match their 'kubernetes.io/hostname' label.
|
||||
# nodes:
|
||||
# - name: "172.17.4.201"
|
||||
# devices: # specific devices to use for storage can be specified for each node
|
||||
# - name: "sdb"
|
||||
# - name: "nvme01" # multiple osds can be created on high performance devices
|
||||
# config:
|
||||
# osdsPerDevice: "5"
|
||||
# - name: "/dev/disk/by-id/ata-ST4000DM004-XXXX" # devices can be specified using full udev paths
|
||||
# config: # configuration can be specified at the node level which overrides the cluster level config
|
||||
# - name: "172.17.4.301"
|
||||
# deviceFilter: "^sd."
|
||||
|
||||
# The section for configuring management of daemon disruptions during upgrade or fencing.
|
||||
disruptionManagement:
|
||||
# If true, the operator will create and manage PodDisruptionBudgets for OSD, Mon, RGW, and MDS daemons. OSD PDBs are managed dynamically
|
||||
# via the strategy outlined in the [design](https://github.com/rook/rook/blob/master/design/ceph/ceph-managed-disruptionbudgets.md). The operator will
|
||||
# block eviction of OSDs by default and unblock them safely when drains are detected.
|
||||
managePodBudgets: true
|
||||
# A duration in minutes that determines how long an entire failureDomain like `region/zone/host` will be held in `noout` (in addition to the
|
||||
# default DOWN/OUT interval) when it is draining. This is only relevant when `managePodBudgets` is `true`. The default value is `30` minutes.
|
||||
osdMaintenanceTimeout: 30
|
||||
|
||||
# Configure the healthcheck and liveness probes for ceph pods.
|
||||
# Valid values for daemons are 'mon', 'osd', 'status'
|
||||
healthCheck:
|
||||
daemonHealth:
|
||||
mon:
|
||||
disabled: false
|
||||
interval: 45s
|
||||
osd:
|
||||
disabled: false
|
||||
interval: 60s
|
||||
status:
|
||||
disabled: false
|
||||
interval: 60s
|
||||
# Change pod liveness probe, it works for all mon, mgr, and osd pods.
|
||||
livenessProbe:
|
||||
mon:
|
||||
disabled: false
|
||||
mgr:
|
||||
disabled: false
|
||||
osd:
|
||||
disabled: false
|
||||
|
||||
ingress:
|
||||
# -- Enable an ingress for the ceph-dashboard
|
||||
dashboard:
|
||||
# {}
|
||||
# labels:
|
||||
# external-dns/private: "true"
|
||||
annotations:
|
||||
"route.openshift.io/termination": "passthrough"
|
||||
# external-dns.alpha.kubernetes.io/hostname: dashboard.example.com
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /ceph-dashboard/$2
|
||||
# If the dashboard has ssl: true the following will make sure the NGINX Ingress controller can expose the dashboard correctly
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
|
||||
# nginx.ingress.kubernetes.io/server-snippet: |
|
||||
# proxy_ssl_verify off;
|
||||
host:
|
||||
name: ceph.apps.ncd0.harmony.mcd
|
||||
path: null # TODO the chart does not allow removing the path, and it causes openshift to fail creating a route, because path is not supported with termination mode passthrough
|
||||
pathType: ImplementationSpecific
|
||||
tls:
|
||||
- {}
|
||||
# secretName: testsecret-tls
|
||||
# Note: Only one of ingress class annotation or the `ingressClassName:` can be used at a time
|
||||
# to set the ingress class
|
||||
# ingressClassName: openshift-default
|
||||
# labels:
|
||||
# external-dns/private: "true"
|
||||
# annotations:
|
||||
# external-dns.alpha.kubernetes.io/hostname: dashboard.example.com
|
||||
# nginx.ingress.kubernetes.io/rewrite-target: /ceph-dashboard/$2
|
||||
# If the dashboard has ssl: true the following will make sure the NGINX Ingress controller can expose the dashboard correctly
|
||||
# nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"
|
||||
# nginx.ingress.kubernetes.io/server-snippet: |
|
||||
# proxy_ssl_verify off;
|
||||
# host:
|
||||
# name: dashboard.example.com
|
||||
# path: "/ceph-dashboard(/|$)(.*)"
|
||||
# pathType: Prefix
|
||||
# tls:
|
||||
# - hosts:
|
||||
# - dashboard.example.com
|
||||
# secretName: testsecret-tls
|
||||
## Note: Only one of ingress class annotation or the `ingressClassName:` can be used at a time
|
||||
## to set the ingress class
|
||||
# ingressClassName: nginx
|
||||
|
||||
# -- A list of CephBlockPool configurations to deploy
|
||||
# @default -- See [below](#ceph-block-pools)
|
||||
cephBlockPools:
|
||||
- name: ceph-blockpool
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/CRDs/Block-Storage/ceph-block-pool-crd.md#spec for available configuration
|
||||
spec:
|
||||
failureDomain: host
|
||||
replicated:
|
||||
size: 3
|
||||
# Enables collecting RBD per-image IO statistics by enabling dynamic OSD performance counters. Defaults to false.
|
||||
# For reference: https://docs.ceph.com/docs/latest/mgr/prometheus/#rbd-io-statistics
|
||||
# enableRBDStats: true
|
||||
storageClass:
|
||||
enabled: true
|
||||
name: ceph-block
|
||||
annotations: {}
|
||||
labels: {}
|
||||
isDefault: true
|
||||
reclaimPolicy: Delete
|
||||
allowVolumeExpansion: true
|
||||
volumeBindingMode: "Immediate"
|
||||
mountOptions: []
|
||||
# see https://kubernetes.io/docs/concepts/storage/storage-classes/#allowed-topologies
|
||||
allowedTopologies: []
|
||||
# - matchLabelExpressions:
|
||||
# - key: rook-ceph-role
|
||||
# values:
|
||||
# - storage-node
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/Storage-Configuration/Block-Storage-RBD/block-storage.md#provision-storage for available configuration
|
||||
parameters:
|
||||
# (optional) mapOptions is a comma-separated list of map options.
|
||||
# For krbd options refer
|
||||
# https://docs.ceph.com/docs/latest/man/8/rbd/#kernel-rbd-krbd-options
|
||||
# For nbd options refer
|
||||
# https://docs.ceph.com/docs/latest/man/8/rbd-nbd/#options
|
||||
# mapOptions: lock_on_read,queue_depth=1024
|
||||
|
||||
# (optional) unmapOptions is a comma-separated list of unmap options.
|
||||
# For krbd options refer
|
||||
# https://docs.ceph.com/docs/latest/man/8/rbd/#kernel-rbd-krbd-options
|
||||
# For nbd options refer
|
||||
# https://docs.ceph.com/docs/latest/man/8/rbd-nbd/#options
|
||||
# unmapOptions: force
|
||||
|
||||
# RBD image format. Defaults to "2".
|
||||
imageFormat: "2"
|
||||
|
||||
# RBD image features, equivalent to OR'd bitfield value: 63
|
||||
# Available for imageFormat: "2". Older releases of CSI RBD
|
||||
# support only the `layering` feature. The Linux kernel (KRBD) supports the
|
||||
# full feature complement as of 5.4
|
||||
imageFeatures: layering
|
||||
|
||||
# These secrets contain Ceph admin credentials.
|
||||
csi.storage.k8s.io/provisioner-secret-name: rook-csi-rbd-provisioner
|
||||
csi.storage.k8s.io/provisioner-secret-namespace: "{{ .Release.Namespace }}"
|
||||
csi.storage.k8s.io/controller-expand-secret-name: rook-csi-rbd-provisioner
|
||||
csi.storage.k8s.io/controller-expand-secret-namespace: "{{ .Release.Namespace }}"
|
||||
csi.storage.k8s.io/node-stage-secret-name: rook-csi-rbd-node
|
||||
csi.storage.k8s.io/node-stage-secret-namespace: "{{ .Release.Namespace }}"
|
||||
# Specify the filesystem type of the volume. If not specified, csi-provisioner
|
||||
# will set default as `ext4`. Note that `xfs` is not recommended due to potential deadlock
|
||||
# in hyperconverged settings where the volume is mounted on the same node as the osds.
|
||||
csi.storage.k8s.io/fstype: ext4
|
||||
|
||||
# -- A list of CephFileSystem configurations to deploy
|
||||
# @default -- See [below](#ceph-file-systems)
|
||||
cephFileSystems:
|
||||
- name: ceph-filesystem
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/CRDs/Shared-Filesystem/ceph-filesystem-crd.md#filesystem-settings for available configuration
|
||||
spec:
|
||||
metadataPool:
|
||||
replicated:
|
||||
size: 3
|
||||
dataPools:
|
||||
- failureDomain: host
|
||||
replicated:
|
||||
size: 3
|
||||
# Optional and highly recommended, 'data0' by default, see https://github.com/rook/rook/blob/master/Documentation/CRDs/Shared-Filesystem/ceph-filesystem-crd.md#pools
|
||||
name: data0
|
||||
metadataServer:
|
||||
activeCount: 1
|
||||
activeStandby: true
|
||||
resources:
|
||||
limits:
|
||||
memory: "4Gi"
|
||||
requests:
|
||||
cpu: "1000m"
|
||||
memory: "4Gi"
|
||||
priorityClassName: system-cluster-critical
|
||||
storageClass:
|
||||
enabled: true
|
||||
isDefault: false
|
||||
name: ceph-filesystem
|
||||
# (Optional) specify a data pool to use, must be the name of one of the data pools above, 'data0' by default
|
||||
pool: data0
|
||||
reclaimPolicy: Delete
|
||||
allowVolumeExpansion: true
|
||||
volumeBindingMode: "Immediate"
|
||||
annotations: {}
|
||||
labels: {}
|
||||
mountOptions: []
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/Storage-Configuration/Shared-Filesystem-CephFS/filesystem-storage.md#provision-storage for available configuration
|
||||
parameters:
|
||||
# The secrets contain Ceph admin credentials.
|
||||
csi.storage.k8s.io/provisioner-secret-name: rook-csi-cephfs-provisioner
|
||||
csi.storage.k8s.io/provisioner-secret-namespace: "{{ .Release.Namespace }}"
|
||||
csi.storage.k8s.io/controller-expand-secret-name: rook-csi-cephfs-provisioner
|
||||
csi.storage.k8s.io/controller-expand-secret-namespace: "{{ .Release.Namespace }}"
|
||||
csi.storage.k8s.io/node-stage-secret-name: rook-csi-cephfs-node
|
||||
csi.storage.k8s.io/node-stage-secret-namespace: "{{ .Release.Namespace }}"
|
||||
# Specify the filesystem type of the volume. If not specified, csi-provisioner
|
||||
# will set default as `ext4`. Note that `xfs` is not recommended due to potential deadlock
|
||||
# in hyperconverged settings where the volume is mounted on the same node as the osds.
|
||||
csi.storage.k8s.io/fstype: ext4
|
||||
|
||||
# -- Settings for the filesystem snapshot class
|
||||
# @default -- See [CephFS Snapshots](../Storage-Configuration/Ceph-CSI/ceph-csi-snapshot.md#cephfs-snapshots)
|
||||
cephFileSystemVolumeSnapshotClass:
|
||||
enabled: false
|
||||
name: ceph-filesystem
|
||||
isDefault: true
|
||||
deletionPolicy: Delete
|
||||
annotations: {}
|
||||
labels: {}
|
||||
# see https://rook.io/docs/rook/v1.10/Storage-Configuration/Ceph-CSI/ceph-csi-snapshot/#cephfs-snapshots for available configuration
|
||||
parameters: {}
|
||||
|
||||
# -- Settings for the block pool snapshot class
|
||||
# @default -- See [RBD Snapshots](../Storage-Configuration/Ceph-CSI/ceph-csi-snapshot.md#rbd-snapshots)
|
||||
cephBlockPoolsVolumeSnapshotClass:
|
||||
enabled: false
|
||||
name: ceph-block
|
||||
isDefault: false
|
||||
deletionPolicy: Delete
|
||||
annotations: {}
|
||||
labels: {}
|
||||
# see https://rook.io/docs/rook/v1.10/Storage-Configuration/Ceph-CSI/ceph-csi-snapshot/#rbd-snapshots for available configuration
|
||||
parameters: {}
|
||||
|
||||
# -- A list of CephObjectStore configurations to deploy
|
||||
# @default -- See [below](#ceph-object-stores)
|
||||
cephObjectStores:
|
||||
- name: ceph-objectstore
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/CRDs/Object-Storage/ceph-object-store-crd.md#object-store-settings for available configuration
|
||||
spec:
|
||||
metadataPool:
|
||||
failureDomain: host
|
||||
replicated:
|
||||
size: 3
|
||||
dataPool:
|
||||
failureDomain: host
|
||||
erasureCoded:
|
||||
dataChunks: 2
|
||||
codingChunks: 1
|
||||
parameters:
|
||||
bulk: "true"
|
||||
preservePoolsOnDelete: true
|
||||
gateway:
|
||||
port: 80
|
||||
resources:
|
||||
limits:
|
||||
memory: "2Gi"
|
||||
requests:
|
||||
cpu: "1000m"
|
||||
memory: "1Gi"
|
||||
# securePort: 443
|
||||
# sslCertificateRef:
|
||||
instances: 1
|
||||
priorityClassName: system-cluster-critical
|
||||
# opsLogSidecar:
|
||||
# resources:
|
||||
# limits:
|
||||
# memory: "100Mi"
|
||||
# requests:
|
||||
# cpu: "100m"
|
||||
# memory: "40Mi"
|
||||
storageClass:
|
||||
enabled: true
|
||||
name: ceph-bucket
|
||||
reclaimPolicy: Delete
|
||||
volumeBindingMode: "Immediate"
|
||||
annotations: {}
|
||||
labels: {}
|
||||
# see https://github.com/rook/rook/blob/master/Documentation/Storage-Configuration/Object-Storage-RGW/ceph-object-bucket-claim.md#storageclass for available configuration
|
||||
parameters:
|
||||
# note: objectStoreNamespace and objectStoreName are configured by the chart
|
||||
region: us-east-1
|
||||
ingress:
|
||||
# Enable an ingress for the ceph-objectstore
|
||||
enabled: true
|
||||
# The ingress port by default will be the object store's "securePort" (if set), or the gateway "port".
|
||||
# To override those defaults, set this ingress port to the desired port.
|
||||
# port: 80
|
||||
# annotations: {}
|
||||
host:
|
||||
name: objectstore.apps.ncd0.harmony.mcd
|
||||
path: /
|
||||
pathType: Prefix
|
||||
# tls:
|
||||
# - hosts:
|
||||
# - objectstore.example.com
|
||||
# secretName: ceph-objectstore-tls
|
||||
# ingressClassName: nginx
|
||||
## cephECBlockPools are disabled by default, please remove the comments and set desired values to enable it
|
||||
## For erasure coded a replicated metadata pool is required.
|
||||
## https://rook.io/docs/rook/latest/CRDs/Shared-Filesystem/ceph-filesystem-crd/#erasure-coded
|
||||
#cephECBlockPools:
|
||||
# - name: ec-pool
|
||||
# spec:
|
||||
# metadataPool:
|
||||
# replicated:
|
||||
# size: 2
|
||||
# dataPool:
|
||||
# failureDomain: osd
|
||||
# erasureCoded:
|
||||
# dataChunks: 2
|
||||
# codingChunks: 1
|
||||
# deviceClass: hdd
|
||||
#
|
||||
# parameters:
|
||||
# # clusterID is the namespace where the rook cluster is running
|
||||
# # If you change this namespace, also change the namespace below where the secret namespaces are defined
|
||||
# clusterID: rook-ceph # namespace:cluster
|
||||
# # (optional) mapOptions is a comma-separated list of map options.
|
||||
# # For krbd options refer
|
||||
# # https://docs.ceph.com/docs/latest/man/8/rbd/#kernel-rbd-krbd-options
|
||||
# # For nbd options refer
|
||||
# # https://docs.ceph.com/docs/latest/man/8/rbd-nbd/#options
|
||||
# # mapOptions: lock_on_read,queue_depth=1024
|
||||
#
|
||||
# # (optional) unmapOptions is a comma-separated list of unmap options.
|
||||
# # For krbd options refer
|
||||
# # https://docs.ceph.com/docs/latest/man/8/rbd/#kernel-rbd-krbd-options
|
||||
# # For nbd options refer
|
||||
# # https://docs.ceph.com/docs/latest/man/8/rbd-nbd/#options
|
||||
# # unmapOptions: force
|
||||
#
|
||||
# # RBD image format. Defaults to "2".
|
||||
# imageFormat: "2"
|
||||
#
|
||||
# # RBD image features, equivalent to OR'd bitfield value: 63
|
||||
# # Available for imageFormat: "2". Older releases of CSI RBD
|
||||
# # support only the `layering` feature. The Linux kernel (KRBD) supports the
|
||||
# # full feature complement as of 5.4
|
||||
# # imageFeatures: layering,fast-diff,object-map,deep-flatten,exclusive-lock
|
||||
# imageFeatures: layering
|
||||
#
|
||||
# storageClass:
|
||||
# provisioner: rook-ceph.rbd.csi.ceph.com # csi-provisioner-name
|
||||
# enabled: true
|
||||
# name: rook-ceph-block
|
||||
# isDefault: false
|
||||
# annotations: { }
|
||||
# labels: { }
|
||||
# allowVolumeExpansion: true
|
||||
# reclaimPolicy: Delete
|
||||
|
||||
# -- CSI driver name prefix for cephfs, rbd and nfs.
|
||||
# @default -- `namespace name where rook-ceph operator is deployed`
|
||||
csiDriverNamePrefix:
|
||||
3
examples/nanodc/rook-operator/install-rook-operator.sh
Normal file
3
examples/nanodc/rook-operator/install-rook-operator.sh
Normal file
@@ -0,0 +1,3 @@
|
||||
#!/bin/bash
|
||||
helm repo add rook-release https://charts.rook.io/release
|
||||
helm install --create-namespace --namespace rook-ceph rook-ceph rook-release/rook-ceph -f values.yaml
|
||||
674
examples/nanodc/rook-operator/values.yaml
Normal file
674
examples/nanodc/rook-operator/values.yaml
Normal file
@@ -0,0 +1,674 @@
|
||||
# Default values for rook-ceph-operator
|
||||
# This is a YAML-formatted file.
|
||||
# Declare variables to be passed into your templates.
|
||||
|
||||
image:
|
||||
# -- Image
|
||||
repository: docker.io/rook/ceph
|
||||
# -- Image tag
|
||||
# @default -- `master`
|
||||
tag: v1.17.1
|
||||
# -- Image pull policy
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
crds:
|
||||
# -- Whether the helm chart should create and update the CRDs. If false, the CRDs must be
|
||||
# managed independently with deploy/examples/crds.yaml.
|
||||
# **WARNING** Only set during first deployment. If later disabled the cluster may be DESTROYED.
|
||||
# If the CRDs are deleted in this case, see
|
||||
# [the disaster recovery guide](https://rook.io/docs/rook/latest/Troubleshooting/disaster-recovery/#restoring-crds-after-deletion)
|
||||
# to restore them.
|
||||
enabled: true
|
||||
|
||||
# -- Pod resource requests & limits
|
||||
resources:
|
||||
limits:
|
||||
memory: 512Mi
|
||||
requests:
|
||||
cpu: 200m
|
||||
memory: 128Mi
|
||||
|
||||
# -- Kubernetes [`nodeSelector`](https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector) to add to the Deployment.
|
||||
nodeSelector: {}
|
||||
# Constraint rook-ceph-operator Deployment to nodes with label `disktype: ssd`.
|
||||
# For more info, see https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector
|
||||
# disktype: ssd
|
||||
|
||||
# -- List of Kubernetes [`tolerations`](https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/) to add to the Deployment.
|
||||
tolerations: []
|
||||
|
||||
# -- Delay to use for the `node.kubernetes.io/unreachable` pod failure toleration to override
|
||||
# the Kubernetes default of 5 minutes
|
||||
unreachableNodeTolerationSeconds: 5
|
||||
|
||||
# -- Whether the operator should watch cluster CRD in its own namespace or not
|
||||
currentNamespaceOnly: false
|
||||
|
||||
# -- Custom pod labels for the operator
|
||||
operatorPodLabels: {}
|
||||
|
||||
# -- Pod annotations
|
||||
annotations: {}
|
||||
|
||||
# -- Global log level for the operator.
|
||||
# Options: `ERROR`, `WARNING`, `INFO`, `DEBUG`
|
||||
logLevel: INFO
|
||||
|
||||
# -- If true, create & use RBAC resources
|
||||
rbacEnable: true
|
||||
|
||||
rbacAggregate:
|
||||
# -- If true, create a ClusterRole aggregated to [user facing roles](https://kubernetes.io/docs/reference/access-authn-authz/rbac/#user-facing-roles) for objectbucketclaims
|
||||
enableOBCs: false
|
||||
|
||||
# -- If true, create & use PSP resources
|
||||
pspEnable: false
|
||||
|
||||
# -- Set the priority class for the rook operator deployment if desired
|
||||
priorityClassName:
|
||||
|
||||
# -- Set the container security context for the operator
|
||||
containerSecurityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 2016
|
||||
runAsGroup: 2016
|
||||
capabilities:
|
||||
drop: ["ALL"]
|
||||
# -- If true, loop devices are allowed to be used for osds in test clusters
|
||||
allowLoopDevices: false
|
||||
|
||||
# Settings for whether to disable the drivers or other daemons if they are not
|
||||
# needed
|
||||
csi:
|
||||
# -- Enable Ceph CSI RBD driver
|
||||
enableRbdDriver: true
|
||||
# -- Enable Ceph CSI CephFS driver
|
||||
enableCephfsDriver: true
|
||||
# -- Disable the CSI driver.
|
||||
disableCsiDriver: "false"
|
||||
|
||||
# -- Enable host networking for CSI CephFS and RBD nodeplugins. This may be necessary
|
||||
# in some network configurations where the SDN does not provide access to an external cluster or
|
||||
# there is significant drop in read/write performance
|
||||
enableCSIHostNetwork: true
|
||||
# -- Enable Snapshotter in CephFS provisioner pod
|
||||
enableCephfsSnapshotter: true
|
||||
# -- Enable Snapshotter in NFS provisioner pod
|
||||
enableNFSSnapshotter: true
|
||||
# -- Enable Snapshotter in RBD provisioner pod
|
||||
enableRBDSnapshotter: true
|
||||
# -- Enable Host mount for `/etc/selinux` directory for Ceph CSI nodeplugins
|
||||
enablePluginSelinuxHostMount: false
|
||||
# -- Enable Ceph CSI PVC encryption support
|
||||
enableCSIEncryption: false
|
||||
|
||||
# -- Enable volume group snapshot feature. This feature is
|
||||
# enabled by default as long as the necessary CRDs are available in the cluster.
|
||||
enableVolumeGroupSnapshot: true
|
||||
# -- PriorityClassName to be set on csi driver plugin pods
|
||||
pluginPriorityClassName: system-node-critical
|
||||
|
||||
# -- PriorityClassName to be set on csi driver provisioner pods
|
||||
provisionerPriorityClassName: system-cluster-critical
|
||||
|
||||
# -- Policy for modifying a volume's ownership or permissions when the RBD PVC is being mounted.
|
||||
# supported values are documented at https://kubernetes-csi.github.io/docs/support-fsgroup.html
|
||||
rbdFSGroupPolicy: "File"
|
||||
|
||||
# -- Policy for modifying a volume's ownership or permissions when the CephFS PVC is being mounted.
|
||||
# supported values are documented at https://kubernetes-csi.github.io/docs/support-fsgroup.html
|
||||
cephFSFSGroupPolicy: "File"
|
||||
|
||||
# -- Policy for modifying a volume's ownership or permissions when the NFS PVC is being mounted.
|
||||
# supported values are documented at https://kubernetes-csi.github.io/docs/support-fsgroup.html
|
||||
nfsFSGroupPolicy: "File"
|
||||
|
||||
# -- OMAP generator generates the omap mapping between the PV name and the RBD image
|
||||
# which helps CSI to identify the rbd images for CSI operations.
|
||||
# `CSI_ENABLE_OMAP_GENERATOR` needs to be enabled when we are using rbd mirroring feature.
|
||||
# By default OMAP generator is disabled and when enabled, it will be deployed as a
|
||||
# sidecar with CSI provisioner pod, to enable set it to true.
|
||||
enableOMAPGenerator: false
|
||||
|
||||
# -- Set CephFS Kernel mount options to use https://docs.ceph.com/en/latest/man/8/mount.ceph/#options.
|
||||
# Set to "ms_mode=secure" when connections.encrypted is enabled in CephCluster CR
|
||||
cephFSKernelMountOptions:
|
||||
|
||||
# -- Enable adding volume metadata on the CephFS subvolumes and RBD images.
|
||||
# Not all users might be interested in getting volume/snapshot details as metadata on CephFS subvolume and RBD images.
|
||||
# Hence enable metadata is false by default
|
||||
enableMetadata: false
|
||||
|
||||
# -- Set replicas for csi provisioner deployment
|
||||
provisionerReplicas: 2
|
||||
|
||||
# -- Cluster name identifier to set as metadata on the CephFS subvolume and RBD images. This will be useful
|
||||
# in cases like for example, when two container orchestrator clusters (Kubernetes/OCP) are using a single ceph cluster
|
||||
clusterName:
|
||||
|
||||
# -- Set logging level for cephCSI containers maintained by the cephCSI.
|
||||
# Supported values from 0 to 5. 0 for general useful logs, 5 for trace level verbosity.
|
||||
logLevel: 0
|
||||
|
||||
# -- Set logging level for Kubernetes-csi sidecar containers.
|
||||
# Supported values from 0 to 5. 0 for general useful logs (the default), 5 for trace level verbosity.
|
||||
# @default -- `0`
|
||||
sidecarLogLevel:
|
||||
|
||||
# -- CSI driver name prefix for cephfs, rbd and nfs.
|
||||
# @default -- `namespace name where rook-ceph operator is deployed`
|
||||
csiDriverNamePrefix:
|
||||
|
||||
# -- CSI RBD plugin daemonset update strategy, supported values are OnDelete and RollingUpdate
|
||||
# @default -- `RollingUpdate`
|
||||
rbdPluginUpdateStrategy:
|
||||
|
||||
# -- A maxUnavailable parameter of CSI RBD plugin daemonset update strategy.
|
||||
# @default -- `1`
|
||||
rbdPluginUpdateStrategyMaxUnavailable:
|
||||
|
||||
# -- CSI CephFS plugin daemonset update strategy, supported values are OnDelete and RollingUpdate
|
||||
# @default -- `RollingUpdate`
|
||||
cephFSPluginUpdateStrategy:
|
||||
|
||||
# -- A maxUnavailable parameter of CSI cephFS plugin daemonset update strategy.
|
||||
# @default -- `1`
|
||||
cephFSPluginUpdateStrategyMaxUnavailable:
|
||||
|
||||
# -- CSI NFS plugin daemonset update strategy, supported values are OnDelete and RollingUpdate
|
||||
# @default -- `RollingUpdate`
|
||||
nfsPluginUpdateStrategy:
|
||||
|
||||
# -- Set GRPC timeout for csi containers (in seconds). It should be >= 120. If this value is not set or is invalid, it defaults to 150
|
||||
grpcTimeoutInSeconds: 150
|
||||
|
||||
# -- Burst to use while communicating with the kubernetes apiserver.
|
||||
kubeApiBurst:
|
||||
|
||||
# -- QPS to use while communicating with the kubernetes apiserver.
|
||||
kubeApiQPS:
|
||||
|
||||
# -- The volume of the CephCSI RBD plugin DaemonSet
|
||||
csiRBDPluginVolume:
|
||||
# - name: lib-modules
|
||||
# hostPath:
|
||||
# path: /run/booted-system/kernel-modules/lib/modules/
|
||||
# - name: host-nix
|
||||
# hostPath:
|
||||
# path: /nix
|
||||
|
||||
# -- The volume mounts of the CephCSI RBD plugin DaemonSet
|
||||
csiRBDPluginVolumeMount:
|
||||
# - name: host-nix
|
||||
# mountPath: /nix
|
||||
# readOnly: true
|
||||
|
||||
# -- The volume of the CephCSI CephFS plugin DaemonSet
|
||||
csiCephFSPluginVolume:
|
||||
# - name: lib-modules
|
||||
# hostPath:
|
||||
# path: /run/booted-system/kernel-modules/lib/modules/
|
||||
# - name: host-nix
|
||||
# hostPath:
|
||||
# path: /nix
|
||||
|
||||
# -- The volume mounts of the CephCSI CephFS plugin DaemonSet
|
||||
csiCephFSPluginVolumeMount:
|
||||
# - name: host-nix
|
||||
# mountPath: /nix
|
||||
# readOnly: true
|
||||
|
||||
# -- CEPH CSI RBD provisioner resource requirement list
|
||||
# csi-omap-generator resources will be applied only if `enableOMAPGenerator` is set to `true`
|
||||
# @default -- see values.yaml
|
||||
csiRBDProvisionerResource: |
|
||||
- name : csi-provisioner
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-resizer
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-attacher
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-snapshotter
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-rbdplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : csi-omap-generator
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : liveness-prometheus
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
|
||||
# -- CEPH CSI RBD plugin resource requirement list
|
||||
# @default -- see values.yaml
|
||||
csiRBDPluginResource: |
|
||||
- name : driver-registrar
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-rbdplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : liveness-prometheus
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
|
||||
# -- CEPH CSI CephFS provisioner resource requirement list
|
||||
# @default -- see values.yaml
|
||||
csiCephFSProvisionerResource: |
|
||||
- name : csi-provisioner
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-resizer
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-attacher
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-snapshotter
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-cephfsplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : liveness-prometheus
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
|
||||
# -- CEPH CSI CephFS plugin resource requirement list
|
||||
# @default -- see values.yaml
|
||||
csiCephFSPluginResource: |
|
||||
- name : driver-registrar
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-cephfsplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : liveness-prometheus
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
|
||||
# -- CEPH CSI NFS provisioner resource requirement list
|
||||
# @default -- see values.yaml
|
||||
csiNFSProvisionerResource: |
|
||||
- name : csi-provisioner
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 100m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-nfsplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
- name : csi-attacher
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
|
||||
# -- CEPH CSI NFS plugin resource requirement list
|
||||
# @default -- see values.yaml
|
||||
csiNFSPluginResource: |
|
||||
- name : driver-registrar
|
||||
resource:
|
||||
requests:
|
||||
memory: 128Mi
|
||||
cpu: 50m
|
||||
limits:
|
||||
memory: 256Mi
|
||||
- name : csi-nfsplugin
|
||||
resource:
|
||||
requests:
|
||||
memory: 512Mi
|
||||
cpu: 250m
|
||||
limits:
|
||||
memory: 1Gi
|
||||
|
||||
# Set provisionerTolerations and provisionerNodeAffinity for provisioner pod.
|
||||
# The CSI provisioner would be best to start on the same nodes as other ceph daemons.
|
||||
|
||||
# -- Array of tolerations in YAML format which will be added to CSI provisioner deployment
|
||||
provisionerTolerations:
|
||||
# - key: key
|
||||
# operator: Exists
|
||||
# effect: NoSchedule
|
||||
|
||||
# -- The node labels for affinity of the CSI provisioner deployment [^1]
|
||||
provisionerNodeAffinity: #key1=value1,value2; key2=value3
|
||||
# Set pluginTolerations and pluginNodeAffinity for plugin daemonset pods.
|
||||
# The CSI plugins need to be started on all the nodes where the clients need to mount the storage.
|
||||
|
||||
# -- Array of tolerations in YAML format which will be added to CephCSI plugin DaemonSet
|
||||
pluginTolerations:
|
||||
# - key: key
|
||||
# operator: Exists
|
||||
# effect: NoSchedule
|
||||
|
||||
# -- The node labels for affinity of the CephCSI RBD plugin DaemonSet [^1]
|
||||
pluginNodeAffinity: # key1=value1,value2; key2=value3
|
||||
|
||||
# -- Enable Ceph CSI Liveness sidecar deployment
|
||||
enableLiveness: false
|
||||
|
||||
# -- CSI CephFS driver metrics port
|
||||
# @default -- `9081`
|
||||
cephfsLivenessMetricsPort:
|
||||
|
||||
# -- CSI Addons server port
|
||||
# @default -- `9070`
|
||||
csiAddonsPort:
|
||||
# -- CSI Addons server port for the RBD provisioner
|
||||
# @default -- `9070`
|
||||
csiAddonsRBDProvisionerPort:
|
||||
# -- CSI Addons server port for the Ceph FS provisioner
|
||||
# @default -- `9070`
|
||||
csiAddonsCephFSProvisionerPort:
|
||||
|
||||
# -- Enable Ceph Kernel clients on kernel < 4.17. If your kernel does not support quotas for CephFS
|
||||
# you may want to disable this setting. However, this will cause an issue during upgrades
|
||||
# with the FUSE client. See the [upgrade guide](https://rook.io/docs/rook/v1.2/ceph-upgrade.html)
|
||||
forceCephFSKernelClient: true
|
||||
|
||||
# -- Ceph CSI RBD driver metrics port
|
||||
# @default -- `8080`
|
||||
rbdLivenessMetricsPort:
|
||||
|
||||
serviceMonitor:
|
||||
# -- Enable ServiceMonitor for Ceph CSI drivers
|
||||
enabled: false
|
||||
# -- Service monitor scrape interval
|
||||
interval: 10s
|
||||
# -- ServiceMonitor additional labels
|
||||
labels: {}
|
||||
# -- Use a different namespace for the ServiceMonitor
|
||||
namespace:
|
||||
|
||||
# -- Kubelet root directory path (if the Kubelet uses a different path for the `--root-dir` flag)
|
||||
# @default -- `/var/lib/kubelet`
|
||||
kubeletDirPath:
|
||||
|
||||
# -- Duration in seconds that non-leader candidates will wait to force acquire leadership.
|
||||
# @default -- `137s`
|
||||
csiLeaderElectionLeaseDuration:
|
||||
|
||||
# -- Deadline in seconds that the acting leader will retry refreshing leadership before giving up.
|
||||
# @default -- `107s`
|
||||
csiLeaderElectionRenewDeadline:
|
||||
|
||||
# -- Retry period in seconds the LeaderElector clients should wait between tries of actions.
|
||||
# @default -- `26s`
|
||||
csiLeaderElectionRetryPeriod:
|
||||
|
||||
cephcsi:
|
||||
# -- Ceph CSI image repository
|
||||
repository: quay.io/cephcsi/cephcsi
|
||||
# -- Ceph CSI image tag
|
||||
tag: v3.14.0
|
||||
|
||||
registrar:
|
||||
# -- Kubernetes CSI registrar image repository
|
||||
repository: registry.k8s.io/sig-storage/csi-node-driver-registrar
|
||||
# -- Registrar image tag
|
||||
tag: v2.13.0
|
||||
|
||||
provisioner:
|
||||
# -- Kubernetes CSI provisioner image repository
|
||||
repository: registry.k8s.io/sig-storage/csi-provisioner
|
||||
# -- Provisioner image tag
|
||||
tag: v5.1.0
|
||||
|
||||
snapshotter:
|
||||
# -- Kubernetes CSI snapshotter image repository
|
||||
repository: registry.k8s.io/sig-storage/csi-snapshotter
|
||||
# -- Snapshotter image tag
|
||||
tag: v8.2.0
|
||||
|
||||
attacher:
|
||||
# -- Kubernetes CSI Attacher image repository
|
||||
repository: registry.k8s.io/sig-storage/csi-attacher
|
||||
# -- Attacher image tag
|
||||
tag: v4.8.0
|
||||
|
||||
resizer:
|
||||
# -- Kubernetes CSI resizer image repository
|
||||
repository: registry.k8s.io/sig-storage/csi-resizer
|
||||
# -- Resizer image tag
|
||||
tag: v1.13.1
|
||||
|
||||
# -- Image pull policy
|
||||
imagePullPolicy: IfNotPresent
|
||||
|
||||
# -- Labels to add to the CSI CephFS Deployments and DaemonSets Pods
|
||||
cephfsPodLabels: #"key1=value1,key2=value2"
|
||||
|
||||
# -- Labels to add to the CSI NFS Deployments and DaemonSets Pods
|
||||
nfsPodLabels: #"key1=value1,key2=value2"
|
||||
|
||||
# -- Labels to add to the CSI RBD Deployments and DaemonSets Pods
|
||||
rbdPodLabels: #"key1=value1,key2=value2"
|
||||
|
||||
csiAddons:
|
||||
# -- Enable CSIAddons
|
||||
enabled: false
|
||||
# -- CSIAddons sidecar image repository
|
||||
repository: quay.io/csiaddons/k8s-sidecar
|
||||
# -- CSIAddons sidecar image tag
|
||||
tag: v0.12.0
|
||||
|
||||
nfs:
|
||||
# -- Enable the nfs csi driver
|
||||
enabled: false
|
||||
|
||||
topology:
|
||||
# -- Enable topology based provisioning
|
||||
enabled: false
|
||||
# NOTE: the value here serves as an example and needs to be
|
||||
# updated with node labels that define domains of interest
|
||||
# -- domainLabels define which node labels to use as domains
|
||||
# for CSI nodeplugins to advertise their domains
|
||||
domainLabels:
|
||||
# - kubernetes.io/hostname
|
||||
# - topology.kubernetes.io/zone
|
||||
# - topology.rook.io/rack
|
||||
|
||||
# -- Whether to skip any attach operation altogether for CephFS PVCs. See more details
|
||||
# [here](https://kubernetes-csi.github.io/docs/skip-attach.html#skip-attach-with-csi-driver-object).
|
||||
# If cephFSAttachRequired is set to false it skips the volume attachments and makes the creation
|
||||
# of pods using the CephFS PVC fast. **WARNING** It's highly discouraged to use this for
|
||||
# CephFS RWO volumes. Refer to this [issue](https://github.com/kubernetes/kubernetes/issues/103305) for more details.
|
||||
cephFSAttachRequired: true
|
||||
# -- Whether to skip any attach operation altogether for RBD PVCs. See more details
|
||||
# [here](https://kubernetes-csi.github.io/docs/skip-attach.html#skip-attach-with-csi-driver-object).
|
||||
# If set to false it skips the volume attachments and makes the creation of pods using the RBD PVC fast.
|
||||
# **WARNING** It's highly discouraged to use this for RWO volumes as it can cause data corruption.
|
||||
# csi-addons operations like Reclaimspace and PVC Keyrotation will also not be supported if set
|
||||
# to false since we'll have no VolumeAttachments to determine which node the PVC is mounted on.
|
||||
# Refer to this [issue](https://github.com/kubernetes/kubernetes/issues/103305) for more details.
|
||||
rbdAttachRequired: true
|
||||
# -- Whether to skip any attach operation altogether for NFS PVCs. See more details
|
||||
# [here](https://kubernetes-csi.github.io/docs/skip-attach.html#skip-attach-with-csi-driver-object).
|
||||
# If cephFSAttachRequired is set to false it skips the volume attachments and makes the creation
|
||||
# of pods using the NFS PVC fast. **WARNING** It's highly discouraged to use this for
|
||||
# NFS RWO volumes. Refer to this [issue](https://github.com/kubernetes/kubernetes/issues/103305) for more details.
|
||||
nfsAttachRequired: true
|
||||
|
||||
# -- Enable discovery daemon
|
||||
enableDiscoveryDaemon: false
|
||||
# -- Set the discovery daemon device discovery interval (default to 60m)
|
||||
discoveryDaemonInterval: 60m
|
||||
|
||||
# -- The timeout for ceph commands in seconds
|
||||
cephCommandsTimeoutSeconds: "15"
|
||||
|
||||
# -- If true, run rook operator on the host network
|
||||
useOperatorHostNetwork:
|
||||
|
||||
# -- If true, scale down the rook operator.
|
||||
# This is useful for administrative actions where the rook operator must be scaled down, while using gitops style tooling
|
||||
# to deploy your helm charts.
|
||||
scaleDownOperator: false
|
||||
|
||||
## Rook Discover configuration
|
||||
## toleration: NoSchedule, PreferNoSchedule or NoExecute
|
||||
## tolerationKey: Set this to the specific key of the taint to tolerate
|
||||
## tolerations: Array of tolerations in YAML format which will be added to agent deployment
|
||||
## nodeAffinity: Set to labels of the node to match
|
||||
|
||||
discover:
|
||||
# -- Toleration for the discover pods.
|
||||
# Options: `NoSchedule`, `PreferNoSchedule` or `NoExecute`
|
||||
toleration:
|
||||
# -- The specific key of the taint to tolerate
|
||||
tolerationKey:
|
||||
# -- Array of tolerations in YAML format which will be added to discover deployment
|
||||
tolerations:
|
||||
# - key: key
|
||||
# operator: Exists
|
||||
# effect: NoSchedule
|
||||
# -- The node labels for affinity of `discover-agent` [^1]
|
||||
nodeAffinity:
|
||||
# key1=value1,value2; key2=value3
|
||||
#
|
||||
# or
|
||||
#
|
||||
# requiredDuringSchedulingIgnoredDuringExecution:
|
||||
# nodeSelectorTerms:
|
||||
# - matchExpressions:
|
||||
# - key: storage-node
|
||||
# operator: Exists
|
||||
# -- Labels to add to the discover pods
|
||||
podLabels: # "key1=value1,key2=value2"
|
||||
# -- Add resources to discover daemon pods
|
||||
resources:
|
||||
# - limits:
|
||||
# memory: 512Mi
|
||||
# - requests:
|
||||
# cpu: 100m
|
||||
# memory: 128Mi
|
||||
|
||||
# -- Custom label to identify node hostname. If not set `kubernetes.io/hostname` will be used
|
||||
customHostnameLabel:
|
||||
|
||||
# -- Runs Ceph Pods as privileged to be able to write to `hostPaths` in OpenShift with SELinux restrictions.
|
||||
hostpathRequiresPrivileged: false
|
||||
|
||||
# -- Whether to create all Rook pods to run on the host network, for example in environments where a CNI is not enabled
|
||||
enforceHostNetwork: false
|
||||
|
||||
# -- Disable automatic orchestration when new devices are discovered.
|
||||
disableDeviceHotplug: false
|
||||
|
||||
# -- The revision history limit for all pods created by Rook. If blank, the K8s default is 10.
|
||||
revisionHistoryLimit:
|
||||
|
||||
# -- Blacklist certain disks according to the regex provided.
|
||||
discoverDaemonUdev:
|
||||
|
||||
# -- imagePullSecrets option allow to pull docker images from private docker registry. Option will be passed to all service accounts.
|
||||
imagePullSecrets:
|
||||
# - name: my-registry-secret
|
||||
|
||||
# -- Whether the OBC provisioner should watch on the operator namespace or not, if not the namespace of the cluster will be used
|
||||
enableOBCWatchOperatorNamespace: true
|
||||
|
||||
# -- Specify the prefix for the OBC provisioner in place of the cluster namespace
|
||||
# @default -- `ceph cluster namespace`
|
||||
obcProvisionerNamePrefix:
|
||||
|
||||
# -- Many OBC additional config fields may be risky for administrators to allow users control over.
|
||||
# The safe and default-allowed fields are 'maxObjects' and 'maxSize'.
|
||||
# Other fields should be considered risky. To allow all additional configs, use this value:
|
||||
# "maxObjects,maxSize,bucketMaxObjects,bucketMaxSize,bucketPolicy,bucketLifecycle,bucketOwner"
|
||||
# @default -- "maxObjects,maxSize"
|
||||
obcAllowAdditionalConfigFields: "maxObjects,maxSize"
|
||||
|
||||
monitoring:
|
||||
# -- Enable monitoring. Requires Prometheus to be pre-installed.
|
||||
# Enabling will also create RBAC rules to allow Operator to create ServiceMonitors
|
||||
enabled: false
|
||||
@@ -1,20 +1,145 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use cidr::Ipv4Cidr;
|
||||
use harmony::{
|
||||
hardware::{FirewallGroup, HostCategory, Location, PhysicalHost, SwitchGroup},
|
||||
infra::opnsense::OPNSenseManagementInterface,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{dummy::{ErrorScore, PanicScore, SuccessScore}, k8s::deployment::K8sDeploymentScore},
|
||||
topology::HAClusterTopology,
|
||||
modules::{
|
||||
http::HttpScore,
|
||||
ipxe::IpxeScore,
|
||||
okd::{
|
||||
bootstrap_dhcp::OKDBootstrapDhcpScore,
|
||||
bootstrap_load_balancer::OKDBootstrapLoadBalancerScore, dhcp::OKDDhcpScore,
|
||||
dns::OKDDnsScore,
|
||||
},
|
||||
tftp::TftpScore,
|
||||
},
|
||||
topology::{LogicalHost, UnmanagedRouter, Url},
|
||||
};
|
||||
use harmony_macros::{ip, mac_address};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let inventory = Inventory::autoload();
|
||||
let topology = HAClusterTopology::autoload();
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
let firewall = harmony::topology::LogicalHost {
|
||||
ip: ip!("192.168.33.1"),
|
||||
name: String::from("fw0"),
|
||||
};
|
||||
|
||||
let opnsense = Arc::new(
|
||||
harmony::infra::opnsense::OPNSenseFirewall::new(firewall, None, "root", "opnsense").await,
|
||||
);
|
||||
let lan_subnet = Ipv4Addr::new(192, 168, 33, 0);
|
||||
let gateway_ipv4 = Ipv4Addr::new(192, 168, 33, 1);
|
||||
let gateway_ip = IpAddr::V4(gateway_ipv4);
|
||||
let topology = harmony::topology::HAClusterTopology {
|
||||
domain_name: "ncd0.harmony.mcd".to_string(), // TODO this must be set manually correctly
|
||||
// when setting up the opnsense firewall
|
||||
router: Arc::new(UnmanagedRouter::new(
|
||||
gateway_ip,
|
||||
Ipv4Cidr::new(lan_subnet, 24).unwrap(),
|
||||
)),
|
||||
load_balancer: opnsense.clone(),
|
||||
firewall: opnsense.clone(),
|
||||
tftp_server: opnsense.clone(),
|
||||
http_server: opnsense.clone(),
|
||||
dhcp_server: opnsense.clone(),
|
||||
dns_server: opnsense.clone(),
|
||||
control_plane: vec![
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.20"),
|
||||
name: "cp0".to_string(),
|
||||
},
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.21"),
|
||||
name: "cp1".to_string(),
|
||||
},
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.22"),
|
||||
name: "cp2".to_string(),
|
||||
},
|
||||
],
|
||||
bootstrap_host: LogicalHost {
|
||||
ip: ip!("192.168.33.66"),
|
||||
name: "bootstrap".to_string(),
|
||||
},
|
||||
workers: vec![
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.30"),
|
||||
name: "wk0".to_string(),
|
||||
},
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.31"),
|
||||
name: "wk1".to_string(),
|
||||
},
|
||||
LogicalHost {
|
||||
ip: ip!("192.168.33.32"),
|
||||
name: "wk2".to_string(),
|
||||
},
|
||||
],
|
||||
switch: vec![],
|
||||
};
|
||||
|
||||
let inventory = Inventory {
|
||||
location: Location::new("I am mobile".to_string(), "earth".to_string()),
|
||||
switch: SwitchGroup::from([]),
|
||||
firewall: FirewallGroup::from([PhysicalHost::empty(HostCategory::Firewall)
|
||||
.management(Arc::new(OPNSenseManagementInterface::new()))]),
|
||||
storage_host: vec![],
|
||||
worker_host: vec![
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:02:61:0F")),
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:02:61:26")),
|
||||
// thisone
|
||||
// Then create the ipxe file
|
||||
// set the dns static leases
|
||||
// bootstrap nodes
|
||||
// start ceph cluster
|
||||
// try installation of lampscore
|
||||
// bingo?
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:02:61:70")),
|
||||
],
|
||||
control_plane_host: vec![
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:02:60:FA")),
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:02:61:1A")),
|
||||
PhysicalHost::empty(HostCategory::Server)
|
||||
.mac_address(mac_address!("C4:62:37:01:BC:68")),
|
||||
],
|
||||
};
|
||||
|
||||
// TODO regroup smaller scores in a larger one such as this
|
||||
// let okd_boostrap_preparation();
|
||||
|
||||
let bootstrap_dhcp_score = OKDBootstrapDhcpScore::new(&topology, &inventory);
|
||||
let bootstrap_load_balancer_score = OKDBootstrapLoadBalancerScore::new(&topology);
|
||||
let dhcp_score = OKDDhcpScore::new(&topology, &inventory);
|
||||
let dns_score = OKDDnsScore::new(&topology);
|
||||
let load_balancer_score =
|
||||
harmony::modules::okd::load_balancer::OKDLoadBalancerScore::new(&topology);
|
||||
|
||||
let tftp_score = TftpScore::new(Url::LocalFolder("./data/watchguard/tftpboot".to_string()));
|
||||
let http_score = HttpScore::new(Url::LocalFolder(
|
||||
"./data/watchguard/pxe-http-files".to_string(),
|
||||
));
|
||||
let ipxe_score = IpxeScore::new();
|
||||
let mut maestro = Maestro::initialize(inventory, topology).await.unwrap();
|
||||
maestro.register_all(vec![
|
||||
Box::new(SuccessScore {}),
|
||||
Box::new(ErrorScore {}),
|
||||
Box::new(PanicScore {}),
|
||||
Box::new(dns_score),
|
||||
Box::new(bootstrap_dhcp_score),
|
||||
Box::new(bootstrap_load_balancer_score),
|
||||
Box::new(load_balancer_score),
|
||||
Box::new(tftp_score),
|
||||
Box::new(http_score),
|
||||
Box::new(ipxe_score),
|
||||
Box::new(dhcp_score),
|
||||
]);
|
||||
harmony_tui::init(maestro).await.unwrap();
|
||||
}
|
||||
|
||||
12
examples/ntfy/Cargo.toml
Normal file
12
examples/ntfy/Cargo.toml
Normal file
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "example-ntfy"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harmony = { version = "0.1.0", path = "../../harmony" }
|
||||
harmony_cli = { version = "0.1.0", path = "../../harmony_cli" }
|
||||
tokio.workspace = true
|
||||
url.workspace = true
|
||||
19
examples/ntfy/src/main.rs
Normal file
19
examples/ntfy/src/main.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use harmony::{
|
||||
inventory::Inventory, maestro::Maestro, modules::monitoring::ntfy::ntfy::NtfyScore,
|
||||
topology::K8sAnywhereTopology,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
maestro.register_all(vec![Box::new(NtfyScore {
|
||||
namespace: "monitoring".to_string(),
|
||||
})]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
@@ -12,7 +12,7 @@ use harmony::{
|
||||
modules::{
|
||||
dummy::{ErrorScore, PanicScore, SuccessScore},
|
||||
http::HttpScore,
|
||||
okd::{dhcp::OKDDhcpScore, dns::OKDDnsScore},
|
||||
okd::{dhcp::OKDDhcpScore, dns::OKDDnsScore, load_balancer::OKDLoadBalancerScore},
|
||||
opnsense::OPNsenseShellCommandScore,
|
||||
tftp::TftpScore,
|
||||
},
|
||||
@@ -78,14 +78,13 @@ async fn main() {
|
||||
|
||||
let dhcp_score = OKDDhcpScore::new(&topology, &inventory);
|
||||
let dns_score = OKDDnsScore::new(&topology);
|
||||
let load_balancer_score =
|
||||
harmony::modules::okd::load_balancer::OKDLoadBalancerScore::new(&topology);
|
||||
let load_balancer_score = OKDLoadBalancerScore::new(&topology);
|
||||
|
||||
let tftp_score = TftpScore::new(Url::LocalFolder("./data/watchguard/tftpboot".to_string()));
|
||||
let http_score = HttpScore::new(Url::LocalFolder(
|
||||
"./data/watchguard/pxe-http-files".to_string(),
|
||||
));
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
let mut maestro = Maestro::initialize(inventory, topology).await.unwrap();
|
||||
maestro.register_all(vec![
|
||||
Box::new(dns_score),
|
||||
Box::new(dhcp_score),
|
||||
|
||||
10
examples/postgres/Cargo.toml
Normal file
10
examples/postgres/Cargo.toml
Normal file
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "example-postgres"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
async-trait = "0.1.80"
|
||||
84
examples/postgres/src/main.rs
Normal file
84
examples/postgres/src/main.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony::{
|
||||
data::{PostgresDatabase, PostgresUser},
|
||||
interpret::InterpretError,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::postgres::PostgresScore,
|
||||
topology::{PostgresServer, Topology},
|
||||
};
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct MockTopology;
|
||||
|
||||
#[async_trait]
|
||||
impl Topology for MockTopology {
|
||||
fn name(&self) -> &str {
|
||||
"MockTopology"
|
||||
}
|
||||
|
||||
async fn ensure_ready(&self) -> Result<harmony::interpret::Outcome, InterpretError> {
|
||||
Ok(harmony::interpret::Outcome::new(
|
||||
harmony::interpret::InterpretStatus::SUCCESS,
|
||||
"Mock topology is always ready".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PostgresServer for MockTopology {
|
||||
async fn ensure_users_exist(&self, users: Vec<PostgresUser>) -> Result<(), InterpretError> {
|
||||
println!("Ensuring users exist:");
|
||||
for user in users {
|
||||
println!(" - {}: {}", user.name, user.password);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ensure_databases_exist(
|
||||
&self,
|
||||
databases: Vec<PostgresDatabase>,
|
||||
) -> Result<(), InterpretError> {
|
||||
println!("Ensuring databases exist:");
|
||||
for db in databases {
|
||||
println!(" - {}: owner={}", db.name, db.owner);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let users = vec![
|
||||
PostgresUser {
|
||||
name: "admin".to_string(),
|
||||
password: "password".to_string(),
|
||||
},
|
||||
PostgresUser {
|
||||
name: "user".to_string(),
|
||||
password: "password".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let databases = vec![
|
||||
PostgresDatabase {
|
||||
name: "app_db".to_string(),
|
||||
owner: "admin".to_string(),
|
||||
},
|
||||
PostgresDatabase {
|
||||
name: "user_db".to_string(),
|
||||
owner: "user".to_string(),
|
||||
},
|
||||
];
|
||||
|
||||
let postgres_score = PostgresScore::new(users, databases);
|
||||
|
||||
let inventory = Inventory::empty();
|
||||
let topology = MockTopology;
|
||||
let maestro = Maestro::new(inventory, topology);
|
||||
|
||||
maestro.interpret(Box::new(postgres_score)).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
14
examples/rust/Cargo.toml
Normal file
14
examples/rust/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "example-rust"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
tokio = { workspace = true }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
20
examples/rust/src/main.rs
Normal file
20
examples/rust/src/main.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::application::{RustWebappScore, features::ContinuousDelivery},
|
||||
topology::{K8sAnywhereTopology, Url},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = RustWebappScore {
|
||||
name: "Example Rust Webapp".to_string(),
|
||||
domain: Url::Url(url::Url::parse("https://rustapp.harmony.example.com").unwrap()),
|
||||
features: vec![Box::new(ContinuousDelivery {})],
|
||||
};
|
||||
|
||||
let topology = K8sAnywhereTopology::from_env();
|
||||
let mut maestro = Maestro::new(Inventory::autoload(), topology);
|
||||
maestro.register_all(vec![Box::new(app)]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
18
examples/tenant/Cargo.toml
Normal file
18
examples/tenant/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "example-tenant"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_cli = { path = "../../harmony_cli" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
41
examples/tenant/src/main.rs
Normal file
41
examples/tenant/src/main.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use harmony::{
|
||||
data::Id,
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::tenant::TenantScore,
|
||||
topology::{K8sAnywhereTopology, tenant::TenantConfig},
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let tenant = TenantScore {
|
||||
config: TenantConfig {
|
||||
id: Id::from_str("test-tenant-id"),
|
||||
name: "testtenant".to_string(),
|
||||
..Default::default()
|
||||
},
|
||||
};
|
||||
|
||||
let mut maestro = Maestro::<K8sAnywhereTopology>::initialize(
|
||||
Inventory::autoload(),
|
||||
K8sAnywhereTopology::from_env(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
maestro.register_all(vec![Box::new(tenant)]);
|
||||
harmony_cli::init(maestro, None).await.unwrap();
|
||||
}
|
||||
|
||||
// TODO write tests
|
||||
// - Create Tenant with default config mostly, make sure namespace is created
|
||||
// - deploy sample client/server app with nginx unprivileged and a service
|
||||
// - exec in the client pod and validate the following
|
||||
// - can reach internet
|
||||
// - can reach server pod
|
||||
// - can resolve dns queries to internet
|
||||
// - can resolve dns queries to services
|
||||
// - cannot reach services and pods in other namespaces
|
||||
// - Create Tenant with specific cpu/ram/storage requests / limits and make sure they are enforced by trying to
|
||||
// deploy a pod with lower requests/limits (accepted) and higher requests/limits (rejected)
|
||||
// - Create TenantCredentials and make sure they give only access to the correct tenant
|
||||
@@ -10,9 +10,9 @@ publish = false
|
||||
harmony = { path = "../../harmony" }
|
||||
harmony_tui = { path = "../../harmony_tui" }
|
||||
harmony_types = { path = "../../harmony_types" }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
cidr = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
harmony_macros = { path = "../../harmony_macros" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
@@ -1,20 +1,70 @@
|
||||
use std::net::{SocketAddr, SocketAddrV4};
|
||||
|
||||
use harmony::{
|
||||
inventory::Inventory,
|
||||
maestro::Maestro,
|
||||
modules::{dummy::{ErrorScore, PanicScore, SuccessScore}, k8s::deployment::K8sDeploymentScore},
|
||||
topology::HAClusterTopology,
|
||||
modules::{
|
||||
dns::DnsScore,
|
||||
dummy::{ErrorScore, PanicScore, SuccessScore},
|
||||
load_balancer::LoadBalancerScore,
|
||||
},
|
||||
topology::{
|
||||
BackendServer, DummyInfra, HealthCheck, HttpMethod, HttpStatusCode, LoadBalancerService,
|
||||
},
|
||||
};
|
||||
use harmony_macros::ipv4;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let inventory = Inventory::autoload();
|
||||
let topology = HAClusterTopology::autoload();
|
||||
let mut maestro = Maestro::new(inventory, topology);
|
||||
let topology = DummyInfra {};
|
||||
let mut maestro = Maestro::initialize(inventory, topology).await.unwrap();
|
||||
|
||||
maestro.register_all(vec![
|
||||
Box::new(SuccessScore {}),
|
||||
Box::new(ErrorScore {}),
|
||||
Box::new(PanicScore {}),
|
||||
Box::new(DnsScore::new(vec![], None)),
|
||||
Box::new(build_large_score()),
|
||||
]);
|
||||
harmony_tui::init(maestro).await.unwrap();
|
||||
}
|
||||
|
||||
fn build_large_score() -> LoadBalancerScore {
|
||||
let backend_server = BackendServer {
|
||||
address: "192.168.0.0".to_string(),
|
||||
port: 342,
|
||||
};
|
||||
let lb_service = LoadBalancerService {
|
||||
backend_servers: vec![
|
||||
backend_server.clone(),
|
||||
backend_server.clone(),
|
||||
backend_server.clone(),
|
||||
],
|
||||
listening_port: SocketAddr::V4(SocketAddrV4::new(ipv4!("192.168.0.0"), 49387)),
|
||||
health_check: Some(HealthCheck::HTTP(
|
||||
"/some_long_ass_path_to_see_how_it_is_displayed_but_it_has_to_be_even_longer"
|
||||
.to_string(),
|
||||
HttpMethod::GET,
|
||||
HttpStatusCode::Success2xx,
|
||||
)),
|
||||
};
|
||||
LoadBalancerScore {
|
||||
public_services: vec![
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
],
|
||||
private_services: vec![
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
lb_service.clone(),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,26 +6,54 @@ readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rand = "0.9"
|
||||
hex = "0.4"
|
||||
libredfish = "0.1.1"
|
||||
reqwest = {version = "0.11", features = ["blocking", "json"] }
|
||||
reqwest = { version = "0.11", features = ["blocking", "json"] }
|
||||
russh = "0.45.0"
|
||||
rust-ipmi = "0.1.1"
|
||||
semver = "1.0.23"
|
||||
serde = { version = "1.0.209", features = ["derive"] }
|
||||
serde_json = "1.0.127"
|
||||
tokio = { workspace = true }
|
||||
derive-new = { workspace = true }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
cidr = { workspace = true }
|
||||
tokio.workspace = true
|
||||
derive-new.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
async-trait.workspace = true
|
||||
cidr.workspace = true
|
||||
opnsense-config = { path = "../opnsense-config" }
|
||||
opnsense-config-xml = { path = "../opnsense-config-xml" }
|
||||
harmony_macros = { path = "../harmony_macros" }
|
||||
harmony_types = { path = "../harmony_types" }
|
||||
uuid = { workspace = true }
|
||||
url = { workspace = true }
|
||||
kube = { workspace = true }
|
||||
k8s-openapi = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
http = { workspace = true }
|
||||
uuid.workspace = true
|
||||
url.workspace = true
|
||||
kube.workspace = true
|
||||
k8s-openapi.workspace = true
|
||||
serde_yaml.workspace = true
|
||||
http.workspace = true
|
||||
serde-value.workspace = true
|
||||
inquire.workspace = true
|
||||
helm-wrapper-rs = "0.4.0"
|
||||
non-blank-string-rs = "1.0.4"
|
||||
k3d-rs = { path = "../k3d" }
|
||||
directories = "6.0.0"
|
||||
lazy_static = "1.5.0"
|
||||
dockerfile_builder = "0.1.5"
|
||||
temp-file = "0.1.9"
|
||||
convert_case.workspace = true
|
||||
email_address = "0.2.9"
|
||||
chrono.workspace = true
|
||||
fqdn = { version = "0.4.6", features = [
|
||||
"domain-label-cannot-start-or-end-with-hyphen",
|
||||
"domain-label-length-limited-to-63",
|
||||
"domain-name-without-special-chars",
|
||||
"domain-name-length-limited-to-255",
|
||||
"punycode",
|
||||
"serde",
|
||||
] }
|
||||
temp-dir = "0.1.14"
|
||||
dyn-clone = "1.0.19"
|
||||
similar.workspace = true
|
||||
futures-util = "0.3.31"
|
||||
tokio-util = "0.7.15"
|
||||
strum = { version = "0.27.1", features = ["derive"] }
|
||||
|
||||
15
harmony/src/domain/config.rs
Normal file
15
harmony/src/domain/config.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use lazy_static::lazy_static;
|
||||
use std::path::PathBuf;
|
||||
|
||||
lazy_static! {
|
||||
pub static ref HARMONY_CONFIG_DIR: PathBuf = directories::BaseDirs::new()
|
||||
.unwrap()
|
||||
.data_dir()
|
||||
.join("harmony");
|
||||
pub static ref REGISTRY_URL: String =
|
||||
std::env::var("HARMONY_REGISTRY_URL").unwrap_or_else(|_| "hub.nationtech.io".to_string());
|
||||
pub static ref REGISTRY_PROJECT: String =
|
||||
std::env::var("HARMONY_REGISTRY_PROJECT").unwrap_or_else(|_| "harmony".to_string());
|
||||
pub static ref DRY_RUN: bool =
|
||||
std::env::var("HARMONY_DRY_RUN").map_or(true, |value| value.parse().unwrap_or(true));
|
||||
}
|
||||
@@ -1,6 +1,24 @@
|
||||
use rand::distr::Alphanumeric;
|
||||
use rand::distr::SampleString;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
/// A unique identifier designed for ease of use.
|
||||
///
|
||||
/// You can pass it any String to use and Id, or you can use the default format with `Id::default()`
|
||||
///
|
||||
/// The default format looks like this
|
||||
///
|
||||
/// `462d4c_g2COgai`
|
||||
///
|
||||
/// The first part is the unix timesamp in hexadecimal which makes Id easily sorted by creation time.
|
||||
/// Second part is a serie of 7 random characters.
|
||||
///
|
||||
/// **It is not meant to be very secure or unique**, it is suitable to generate up to 10 000 items per
|
||||
/// second with a reasonable collision rate of 0,000014 % as calculated by this calculator : https://kevingal.com/apps/collision.html
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Id {
|
||||
value: String,
|
||||
}
|
||||
@@ -9,4 +27,31 @@ impl Id {
|
||||
pub fn from_string(value: String) -> Self {
|
||||
Self { value }
|
||||
}
|
||||
|
||||
pub fn from_str(value: &str) -> Self {
|
||||
Self::from_string(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Id {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(&self.value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Id {
|
||||
fn default() -> Self {
|
||||
let start = SystemTime::now();
|
||||
let since_the_epoch = start
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("Time went backwards");
|
||||
let timestamp = since_the_epoch.as_secs();
|
||||
|
||||
let hex_timestamp = format!("{:x}", timestamp & 0xffffff);
|
||||
|
||||
let random_part: String = Alphanumeric.sample_string(&mut rand::rng(), 7);
|
||||
|
||||
let value = format!("{}_{}", hex_timestamp, random_part);
|
||||
Self { value }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,3 +2,6 @@ mod id;
|
||||
mod version;
|
||||
pub use id::*;
|
||||
pub use version::*;
|
||||
|
||||
mod postgres;
|
||||
pub use postgres::*;
|
||||
|
||||
13
harmony/src/domain/data/postgres.rs
Normal file
13
harmony/src/domain/data/postgres.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PostgresUser {
|
||||
pub name: String,
|
||||
pub password: String, // In a real scenario, this should be a secret type
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PostgresDatabase {
|
||||
pub name: String,
|
||||
pub owner: String,
|
||||
}
|
||||
@@ -2,6 +2,8 @@ use std::sync::Arc;
|
||||
|
||||
use derive_new::new;
|
||||
use harmony_types::net::MacAddress;
|
||||
use serde::{Serialize, Serializer, ser::SerializeStruct};
|
||||
use serde_value::Value;
|
||||
|
||||
pub type HostGroup = Vec<PhysicalHost>;
|
||||
pub type SwitchGroup = Vec<Switch>;
|
||||
@@ -75,10 +77,7 @@ impl PhysicalHost {
|
||||
}
|
||||
|
||||
pub fn label(mut self, name: String, value: String) -> Self {
|
||||
self.labels.push(Label {
|
||||
_name: name,
|
||||
_value: value,
|
||||
});
|
||||
self.labels.push(Label { name, value });
|
||||
self
|
||||
}
|
||||
|
||||
@@ -88,7 +87,49 @@ impl PhysicalHost {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(new)]
|
||||
// Custom Serialize implementation for PhysicalHost
|
||||
impl Serialize for PhysicalHost {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
// Determine the number of fields
|
||||
let mut num_fields = 5; // category, network, storage, labels, management
|
||||
if self.memory_size.is_some() {
|
||||
num_fields += 1;
|
||||
}
|
||||
if self.cpu_count.is_some() {
|
||||
num_fields += 1;
|
||||
}
|
||||
|
||||
// Create a serialization structure
|
||||
let mut state = serializer.serialize_struct("PhysicalHost", num_fields)?;
|
||||
|
||||
// Serialize the standard fields
|
||||
state.serialize_field("category", &self.category)?;
|
||||
state.serialize_field("network", &self.network)?;
|
||||
state.serialize_field("storage", &self.storage)?;
|
||||
state.serialize_field("labels", &self.labels)?;
|
||||
|
||||
// Serialize optional fields
|
||||
if let Some(memory) = self.memory_size {
|
||||
state.serialize_field("memory_size", &memory)?;
|
||||
}
|
||||
if let Some(cpu) = self.cpu_count {
|
||||
state.serialize_field("cpu_count", &cpu)?;
|
||||
}
|
||||
|
||||
let mgmt_data = self.management.serialize_management();
|
||||
// pub management: Arc<dyn ManagementInterface>,
|
||||
|
||||
// Handle management interface - either as a field or flattened
|
||||
state.serialize_field("management", &mgmt_data)?;
|
||||
|
||||
state.end()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(new, Serialize)]
|
||||
pub struct ManualManagementInterface;
|
||||
|
||||
impl ManagementInterface for ManualManagementInterface {
|
||||
@@ -97,11 +138,12 @@ impl ManagementInterface for ManualManagementInterface {
|
||||
}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
todo!()
|
||||
// todo!()
|
||||
"none".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ManagementInterface: Send + Sync {
|
||||
pub trait ManagementInterface: Send + Sync + SerializableManagement {
|
||||
fn boot_to_pxe(&self);
|
||||
fn get_supported_protocol_names(&self) -> String;
|
||||
}
|
||||
@@ -115,21 +157,49 @@ impl std::fmt::Debug for dyn ManagementInterface {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
// Define a trait for serializing management interfaces
|
||||
pub trait SerializableManagement {
|
||||
fn serialize_management(&self) -> Value;
|
||||
}
|
||||
|
||||
// Provide a blanket implementation for all types that implement both ManagementInterface and Serialize
|
||||
impl<T> SerializableManagement for T
|
||||
where
|
||||
T: ManagementInterface + Serialize,
|
||||
{
|
||||
fn serialize_management(&self) -> Value {
|
||||
serde_value::to_value(self).expect("ManagementInterface should serialize successfully")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum HostCategory {
|
||||
Server,
|
||||
Firewall,
|
||||
Switch,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
#[derive(Debug, new, Clone, Serialize)]
|
||||
pub struct NetworkInterface {
|
||||
pub name: Option<String>,
|
||||
pub mac_address: MacAddress,
|
||||
pub speed: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
#[cfg(test)]
|
||||
use harmony_macros::mac_address;
|
||||
#[cfg(test)]
|
||||
impl NetworkInterface {
|
||||
pub fn dummy() -> Self {
|
||||
Self {
|
||||
name: Some(String::new()),
|
||||
mac_address: mac_address!("00:00:00:00:00:00"),
|
||||
speed: Some(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone, Serialize)]
|
||||
pub enum StorageConnectionType {
|
||||
Sata3g,
|
||||
Sata6g,
|
||||
@@ -137,13 +207,13 @@ pub enum StorageConnectionType {
|
||||
Sas12g,
|
||||
PCIE,
|
||||
}
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub enum StorageKind {
|
||||
SSD,
|
||||
NVME,
|
||||
HDD,
|
||||
}
|
||||
#[derive(Debug, new, Clone)]
|
||||
#[derive(Debug, new, Clone, Serialize)]
|
||||
pub struct Storage {
|
||||
pub connection: StorageConnectionType,
|
||||
pub kind: StorageKind,
|
||||
@@ -151,20 +221,33 @@ pub struct Storage {
|
||||
pub serial: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg(test)]
|
||||
impl Storage {
|
||||
pub fn dummy() -> Self {
|
||||
Self {
|
||||
connection: StorageConnectionType::Sata3g,
|
||||
kind: StorageKind::SSD,
|
||||
size: 0,
|
||||
serial: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Switch {
|
||||
_interface: Vec<NetworkInterface>,
|
||||
_management_interface: NetworkInterface,
|
||||
}
|
||||
|
||||
#[derive(Debug, new, Clone)]
|
||||
#[derive(Debug, new, Clone, Serialize)]
|
||||
pub struct Label {
|
||||
_name: String,
|
||||
_value: String,
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
pub type Address = String;
|
||||
|
||||
#[derive(new, Debug)]
|
||||
#[derive(new, Debug, Serialize)]
|
||||
pub struct Location {
|
||||
pub address: Address,
|
||||
pub name: String,
|
||||
@@ -178,3 +261,158 @@ impl Location {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
// Mock implementation of ManagementInterface
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct MockHPIlo {
|
||||
ip: String,
|
||||
username: String,
|
||||
password: String,
|
||||
firmware_version: String,
|
||||
}
|
||||
|
||||
impl ManagementInterface for MockHPIlo {
|
||||
fn boot_to_pxe(&self) {}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
// Another mock implementation
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
struct MockDellIdrac {
|
||||
hostname: String,
|
||||
port: u16,
|
||||
api_token: String,
|
||||
}
|
||||
|
||||
impl ManagementInterface for MockDellIdrac {
|
||||
fn boot_to_pxe(&self) {}
|
||||
|
||||
fn get_supported_protocol_names(&self) -> String {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_physical_host_with_hp_ilo() {
|
||||
// Create a PhysicalHost with HP iLO management
|
||||
let host = PhysicalHost {
|
||||
category: HostCategory::Server,
|
||||
network: vec![NetworkInterface::dummy()],
|
||||
management: Arc::new(MockHPIlo {
|
||||
ip: "192.168.1.100".to_string(),
|
||||
username: "admin".to_string(),
|
||||
password: "password123".to_string(),
|
||||
firmware_version: "2.5.0".to_string(),
|
||||
}),
|
||||
storage: vec![Storage::dummy()],
|
||||
labels: vec![Label::new("datacenter".to_string(), "us-east".to_string())],
|
||||
memory_size: Some(64_000_000),
|
||||
cpu_count: Some(16),
|
||||
};
|
||||
|
||||
// Serialize to JSON
|
||||
let json = serde_json::to_string(&host).expect("Failed to serialize host");
|
||||
|
||||
// Check that the serialized JSON contains the HP iLO details
|
||||
assert!(json.contains("192.168.1.100"));
|
||||
assert!(json.contains("admin"));
|
||||
assert!(json.contains("password123"));
|
||||
assert!(json.contains("firmware_version"));
|
||||
assert!(json.contains("2.5.0"));
|
||||
|
||||
// Parse back to verify structure (not the exact management interface)
|
||||
let parsed: serde_json::Value = serde_json::from_str(&json).expect("Failed to parse JSON");
|
||||
|
||||
// Verify basic structure
|
||||
assert_eq!(parsed["cpu_count"], 16);
|
||||
assert_eq!(parsed["memory_size"], 64_000_000);
|
||||
assert_eq!(parsed["network"][0]["name"], "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serialize_physical_host_with_dell_idrac() {
|
||||
// Create a PhysicalHost with Dell iDRAC management
|
||||
let host = PhysicalHost {
|
||||
category: HostCategory::Server,
|
||||
network: vec![NetworkInterface::dummy()],
|
||||
management: Arc::new(MockDellIdrac {
|
||||
hostname: "idrac-server01".to_string(),
|
||||
port: 443,
|
||||
api_token: "abcdef123456".to_string(),
|
||||
}),
|
||||
storage: vec![Storage::dummy()],
|
||||
labels: vec![Label::new("env".to_string(), "production".to_string())],
|
||||
memory_size: Some(128_000_000),
|
||||
cpu_count: Some(32),
|
||||
};
|
||||
|
||||
// Serialize to JSON
|
||||
let json = serde_json::to_string(&host).expect("Failed to serialize host");
|
||||
|
||||
// Check that the serialized JSON contains the Dell iDRAC details
|
||||
assert!(json.contains("idrac-server01"));
|
||||
assert!(json.contains("443"));
|
||||
assert!(json.contains("abcdef123456"));
|
||||
|
||||
// Parse back to verify structure
|
||||
let parsed: serde_json::Value = serde_json::from_str(&json).expect("Failed to parse JSON");
|
||||
|
||||
// Verify basic structure
|
||||
assert_eq!(parsed["cpu_count"], 32);
|
||||
assert_eq!(parsed["memory_size"], 128_000_000);
|
||||
assert_eq!(parsed["storage"][0]["path"], serde_json::Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_different_management_implementations_produce_valid_json() {
|
||||
// Create hosts with different management implementations
|
||||
let host1 = PhysicalHost {
|
||||
category: HostCategory::Server,
|
||||
network: vec![],
|
||||
management: Arc::new(MockHPIlo {
|
||||
ip: "10.0.0.1".to_string(),
|
||||
username: "root".to_string(),
|
||||
password: "secret".to_string(),
|
||||
firmware_version: "3.0.0".to_string(),
|
||||
}),
|
||||
storage: vec![],
|
||||
labels: vec![],
|
||||
memory_size: None,
|
||||
cpu_count: None,
|
||||
};
|
||||
|
||||
let host2 = PhysicalHost {
|
||||
category: HostCategory::Server,
|
||||
network: vec![],
|
||||
management: Arc::new(MockDellIdrac {
|
||||
hostname: "server02-idrac".to_string(),
|
||||
port: 8443,
|
||||
api_token: "token123".to_string(),
|
||||
}),
|
||||
storage: vec![],
|
||||
labels: vec![],
|
||||
memory_size: None,
|
||||
cpu_count: None,
|
||||
};
|
||||
|
||||
// Both should serialize successfully
|
||||
let json1 = serde_json::to_string(&host1).expect("Failed to serialize host1");
|
||||
let json2 = serde_json::to_string(&host2).expect("Failed to serialize host2");
|
||||
|
||||
// Both JSONs should be valid and parseable
|
||||
let _: serde_json::Value = serde_json::from_str(&json1).expect("Invalid JSON for host1");
|
||||
let _: serde_json::Value = serde_json::from_str(&json2).expect("Invalid JSON for host2");
|
||||
|
||||
// The JSONs should be different because they contain different management interfaces
|
||||
assert_ne!(json1, json2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ use super::{
|
||||
data::{Id, Version},
|
||||
executors::ExecutorError,
|
||||
inventory::Inventory,
|
||||
topology::HAClusterTopology,
|
||||
};
|
||||
|
||||
pub enum InterpretName {
|
||||
@@ -16,9 +15,14 @@ pub enum InterpretName {
|
||||
LoadBalancer,
|
||||
Tftp,
|
||||
Http,
|
||||
Ipxe,
|
||||
Dummy,
|
||||
Panic,
|
||||
OPNSense,
|
||||
K3dInstallation,
|
||||
TenantInterpret,
|
||||
Application,
|
||||
Postgres,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InterpretName {
|
||||
@@ -29,20 +33,22 @@ impl std::fmt::Display for InterpretName {
|
||||
InterpretName::LoadBalancer => f.write_str("LoadBalancer"),
|
||||
InterpretName::Tftp => f.write_str("Tftp"),
|
||||
InterpretName::Http => f.write_str("Http"),
|
||||
InterpretName::Ipxe => f.write_str("iPXE"),
|
||||
InterpretName::Dummy => f.write_str("Dummy"),
|
||||
InterpretName::Panic => f.write_str("Panic"),
|
||||
InterpretName::OPNSense => f.write_str("OPNSense"),
|
||||
InterpretName::K3dInstallation => f.write_str("K3dInstallation"),
|
||||
InterpretName::TenantInterpret => f.write_str("Tenant"),
|
||||
InterpretName::Application => f.write_str("Application"),
|
||||
InterpretName::Postgres => f.write_str("Postgres"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Interpret: std::fmt::Debug + Send {
|
||||
async fn execute(
|
||||
&self,
|
||||
inventory: &Inventory,
|
||||
topology: &HAClusterTopology,
|
||||
) -> Result<Outcome, InterpretError>;
|
||||
pub trait Interpret<T>: std::fmt::Debug + Send {
|
||||
async fn execute(&self, inventory: &Inventory, topology: &T)
|
||||
-> Result<Outcome, InterpretError>;
|
||||
fn get_name(&self) -> InterpretName;
|
||||
fn get_version(&self) -> Version;
|
||||
fn get_status(&self) -> InterpretStatus;
|
||||
@@ -122,3 +128,11 @@ impl From<kube::Error> for InterpretError {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for InterpretError {
|
||||
fn from(value: String) -> Self {
|
||||
Self {
|
||||
msg: format!("InterpretError : {value}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,17 @@ pub struct Inventory {
|
||||
}
|
||||
|
||||
impl Inventory {
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
location: Location::new("Empty".to_string(), "location".to_string()),
|
||||
switch: vec![],
|
||||
firewall: vec![],
|
||||
worker_host: vec![],
|
||||
storage_host: vec![],
|
||||
control_plane_host: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn autoload() -> Self {
|
||||
Self {
|
||||
location: Location::test_building(),
|
||||
|
||||
@@ -1,41 +1,82 @@
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use log::info;
|
||||
use log::{info, warn};
|
||||
|
||||
use super::{
|
||||
interpret::{Interpret, InterpretError, Outcome},
|
||||
interpret::{InterpretError, InterpretStatus, Outcome},
|
||||
inventory::Inventory,
|
||||
score::Score,
|
||||
topology::HAClusterTopology,
|
||||
topology::Topology,
|
||||
};
|
||||
|
||||
type ScoreVec = Vec<Box<dyn Score>>;
|
||||
type ScoreVec<T> = Vec<Box<dyn Score<T>>>;
|
||||
|
||||
pub struct Maestro {
|
||||
pub struct Maestro<T: Topology> {
|
||||
inventory: Inventory,
|
||||
topology: HAClusterTopology,
|
||||
scores: Arc<RwLock<ScoreVec>>,
|
||||
topology: T,
|
||||
scores: Arc<RwLock<ScoreVec<T>>>,
|
||||
topology_preparation_result: Mutex<Option<Outcome>>,
|
||||
}
|
||||
|
||||
impl Maestro {
|
||||
pub fn new(inventory: Inventory, topology: HAClusterTopology) -> Self {
|
||||
impl<T: Topology> Maestro<T> {
|
||||
pub fn new(inventory: Inventory, topology: T) -> Self {
|
||||
Self {
|
||||
inventory,
|
||||
topology,
|
||||
scores: Arc::new(RwLock::new(Vec::new())),
|
||||
topology_preparation_result: None.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
info!("Starting Maestro");
|
||||
pub async fn initialize(inventory: Inventory, topology: T) -> Result<Self, InterpretError> {
|
||||
let instance = Self::new(inventory, topology);
|
||||
instance.prepare_topology().await?;
|
||||
Ok(instance)
|
||||
}
|
||||
|
||||
pub fn register_all(&mut self, mut scores: ScoreVec) {
|
||||
/// Ensures the associated Topology is ready for operations.
|
||||
/// Delegates the readiness check and potential setup actions to the Topology.
|
||||
pub async fn prepare_topology(&self) -> Result<Outcome, InterpretError> {
|
||||
info!("Ensuring topology '{}' is ready...", self.topology.name());
|
||||
let outcome = self.topology.ensure_ready().await?;
|
||||
info!(
|
||||
"Topology '{}' readiness check complete: {}",
|
||||
self.topology.name(),
|
||||
outcome.status
|
||||
);
|
||||
|
||||
self.topology_preparation_result
|
||||
.lock()
|
||||
.unwrap()
|
||||
.replace(outcome.clone());
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
pub fn register_all(&mut self, mut scores: ScoreVec<T>) {
|
||||
let mut score_mut = self.scores.write().expect("Should acquire lock");
|
||||
score_mut.append(&mut scores);
|
||||
}
|
||||
|
||||
pub async fn interpret(&self, score: Box<dyn Score>) -> Result<Outcome, InterpretError> {
|
||||
fn is_topology_initialized(&self) -> bool {
|
||||
let result = self.topology_preparation_result.lock().unwrap();
|
||||
if let Some(outcome) = result.as_ref() {
|
||||
match outcome.status {
|
||||
InterpretStatus::SUCCESS => return true,
|
||||
_ => return false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn interpret(&self, score: Box<dyn Score<T>>) -> Result<Outcome, InterpretError> {
|
||||
if !self.is_topology_initialized() {
|
||||
warn!(
|
||||
"Launching interpret for score {} but Topology {} is not fully initialized!",
|
||||
score.name(),
|
||||
self.topology.name(),
|
||||
);
|
||||
}
|
||||
info!("Running score {score:?}");
|
||||
let interpret = score.create_interpret();
|
||||
info!("Launching interpret {interpret:?}");
|
||||
@@ -44,7 +85,7 @@ impl Maestro {
|
||||
result
|
||||
}
|
||||
|
||||
pub fn scores(&self) -> Arc<RwLock<ScoreVec>> {
|
||||
pub fn scores(&self) -> Arc<RwLock<ScoreVec<T>>> {
|
||||
self.scores.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod config;
|
||||
pub mod data;
|
||||
pub mod executors;
|
||||
pub mod filter;
|
||||
|
||||
@@ -1,7 +1,231 @@
|
||||
use super::interpret::Interpret;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub trait Score: std::fmt::Debug + Send + Sync {
|
||||
fn create_interpret(&self) -> Box<dyn Interpret>;
|
||||
use serde::Serialize;
|
||||
use serde_value::Value;
|
||||
|
||||
use super::{interpret::Interpret, topology::Topology};
|
||||
|
||||
pub trait Score<T: Topology>:
|
||||
std::fmt::Debug + ScoreToString<T> + Send + Sync + CloneBoxScore<T> + SerializeScore<T>
|
||||
{
|
||||
fn create_interpret(&self) -> Box<dyn Interpret<T>>;
|
||||
fn name(&self) -> String;
|
||||
fn clone_box(&self) -> Box<dyn Score>;
|
||||
}
|
||||
|
||||
pub trait SerializeScore<T: Topology> {
|
||||
fn serialize(&self) -> Value;
|
||||
}
|
||||
|
||||
impl<'de, S, T> SerializeScore<T> for S
|
||||
where
|
||||
T: Topology,
|
||||
S: Score<T> + Serialize,
|
||||
{
|
||||
fn serialize(&self) -> Value {
|
||||
// TODO not sure if this is the right place to handle the error or it should bubble
|
||||
// up?
|
||||
serde_value::to_value(&self).expect("Score should serialize successfully")
|
||||
}
|
||||
}
|
||||
|
||||
pub trait CloneBoxScore<T: Topology> {
|
||||
fn clone_box(&self) -> Box<dyn Score<T>>;
|
||||
}
|
||||
|
||||
impl<S, T> CloneBoxScore<T> for S
|
||||
where
|
||||
T: Topology,
|
||||
S: Score<T> + Clone + 'static,
|
||||
{
|
||||
fn clone_box(&self) -> Box<dyn Score<T>> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ScoreToString<T: Topology> {
|
||||
fn print_score_details(&self) -> String;
|
||||
fn format_value_as_string(&self, val: &Value, indent: usize) -> String;
|
||||
fn format_map(&self, map: &BTreeMap<Value, Value>, indent: usize) -> String;
|
||||
fn wrap_or_truncate(&self, s: &str, width: usize) -> Vec<String>;
|
||||
}
|
||||
|
||||
impl<S, T> ScoreToString<T> for S
|
||||
where
|
||||
T: Topology,
|
||||
S: Score<T> + 'static,
|
||||
{
|
||||
fn print_score_details(&self) -> String {
|
||||
let mut output = String::new();
|
||||
output += "\n";
|
||||
output += &self.format_value_as_string(&self.serialize(), 0);
|
||||
output += "\n";
|
||||
output
|
||||
}
|
||||
fn format_map(&self, map: &BTreeMap<Value, Value>, indent: usize) -> String {
|
||||
let pad = " ".repeat(indent * 2);
|
||||
let mut output = String::new();
|
||||
|
||||
output += &format!(
|
||||
"{}+--------------------------+--------------------------------------------------+\n",
|
||||
pad
|
||||
);
|
||||
output += &format!("{}| {:<24} | {:<48} |\n", pad, "score_name", self.name());
|
||||
output += &format!(
|
||||
"{}+--------------------------+--------------------------------------------------+\n",
|
||||
pad
|
||||
);
|
||||
|
||||
for (k, v) in map {
|
||||
let key_str = match k {
|
||||
Value::String(s) => s.clone(),
|
||||
other => format!("{:?}", other),
|
||||
};
|
||||
|
||||
let formatted_val = self.format_value_as_string(v, indent + 1);
|
||||
let lines = formatted_val.lines().map(|line| line.trim_start());
|
||||
|
||||
let wrapped_lines: Vec<_> = lines
|
||||
.flat_map(|line| self.wrap_or_truncate(line.trim_start(), 48))
|
||||
.collect();
|
||||
|
||||
if let Some(first) = wrapped_lines.first() {
|
||||
output += &format!("{}| {:<24} | {:<48} |\n", pad, key_str, first);
|
||||
for line in &wrapped_lines[1..] {
|
||||
output += &format!("{}| {:<24} | {:<48} |\n", pad, "", line);
|
||||
}
|
||||
}
|
||||
|
||||
// let first_line = lines.next().unwrap_or("");
|
||||
// output += &format!("{}| {:<24} | {:<48} |\n", pad, key_str, first_line);
|
||||
//
|
||||
// for line in lines {
|
||||
// output += &format!("{}| {:<24} | {:<48} |\n", pad, "", line);
|
||||
// }
|
||||
}
|
||||
|
||||
output += &format!(
|
||||
"{}+--------------------------+--------------------------------------------------+\n\n",
|
||||
pad
|
||||
);
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
fn wrap_or_truncate(&self, s: &str, width: usize) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
let mut current = s;
|
||||
|
||||
while !current.is_empty() {
|
||||
if current.len() <= width {
|
||||
lines.push(current.to_string());
|
||||
break;
|
||||
}
|
||||
|
||||
// Try to wrap at whitespace if possible
|
||||
let mut split_index = current[..width].rfind(' ').unwrap_or(width);
|
||||
if split_index == 0 {
|
||||
split_index = width;
|
||||
}
|
||||
|
||||
lines.push(current[..split_index].trim_end().to_string());
|
||||
current = current[split_index..].trim_start();
|
||||
}
|
||||
|
||||
lines
|
||||
}
|
||||
|
||||
fn format_value_as_string(&self, val: &Value, indent: usize) -> String {
|
||||
let pad = " ".repeat(indent * 2);
|
||||
let mut output = String::new();
|
||||
|
||||
match val {
|
||||
Value::Bool(b) => output += &format!("{}{}\n", pad, b),
|
||||
Value::U8(u) => output += &format!("{}{}\n", pad, u),
|
||||
Value::U16(u) => output += &format!("{}{}\n", pad, u),
|
||||
Value::U32(u) => output += &format!("{}{}\n", pad, u),
|
||||
Value::U64(u) => output += &format!("{}{}\n", pad, u),
|
||||
Value::I8(i) => output += &format!("{}{}\n", pad, i),
|
||||
Value::I16(i) => output += &format!("{}{}\n", pad, i),
|
||||
Value::I32(i) => output += &format!("{}{}\n", pad, i),
|
||||
Value::I64(i) => output += &format!("{}{}\n", pad, i),
|
||||
Value::F32(f) => output += &format!("{}{}\n", pad, f),
|
||||
Value::F64(f) => output += &format!("{}{}\n", pad, f),
|
||||
Value::Char(c) => output += &format!("{}{}\n", pad, c),
|
||||
Value::String(s) => output += &format!("{}{:<48}\n", pad, s),
|
||||
Value::Unit => output += &format!("{}<unit>\n", pad),
|
||||
Value::Bytes(bytes) => output += &format!("{}{:?}\n", pad, bytes),
|
||||
|
||||
Value::Option(opt) => match opt {
|
||||
Some(inner) => {
|
||||
output += &format!("{}Option:\n", pad);
|
||||
output += &self.format_value_as_string(inner, indent + 1);
|
||||
}
|
||||
None => output += &format!("{}None\n", pad),
|
||||
},
|
||||
|
||||
Value::Newtype(inner) => {
|
||||
output += &format!("{}Newtype:\n", pad);
|
||||
output += &self.format_value_as_string(inner, indent + 1);
|
||||
}
|
||||
|
||||
Value::Seq(seq) => {
|
||||
if seq.is_empty() {
|
||||
output += &format!("{}[]\n", pad);
|
||||
} else {
|
||||
output += &format!("{}[\n", pad);
|
||||
for item in seq {
|
||||
output += &self.format_value_as_string(item, indent + 1);
|
||||
}
|
||||
output += &format!("{}]\n", pad);
|
||||
}
|
||||
}
|
||||
|
||||
Value::Map(map) => {
|
||||
if map.is_empty() {
|
||||
output += &format!("{}<empty map>\n", pad);
|
||||
} else if indent == 0 {
|
||||
output += &self.format_map(map, indent);
|
||||
} else {
|
||||
for (k, v) in map {
|
||||
let key_str = match k {
|
||||
Value::String(s) => s.clone(),
|
||||
other => format!("{:?}", other),
|
||||
};
|
||||
|
||||
let val_str = self
|
||||
.format_value_as_string(v, indent + 1)
|
||||
.trim()
|
||||
.to_string();
|
||||
let val_lines: Vec<_> = val_str.lines().collect();
|
||||
|
||||
output +=
|
||||
&format!("{}{}: {}\n", pad, key_str, val_lines.first().unwrap_or(&""));
|
||||
for line in val_lines.iter().skip(1) {
|
||||
output += &format!("{} {}\n", pad, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
//TODO write test to check that the output is what it should be
|
||||
//
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::modules::dns::DnsScore;
|
||||
use crate::topology::HAClusterTopology;
|
||||
|
||||
#[test]
|
||||
fn test_format_values_as_string() {
|
||||
let dns_score = Box::new(DnsScore::new(vec![], None));
|
||||
let print_score_output =
|
||||
<DnsScore as ScoreToString<HAClusterTopology>>::print_score_details(&dns_score);
|
||||
let expected_empty_dns_score_table = "\n+--------------------------+--------------------------------------------------+\n| score_name | DnsScore |\n+--------------------------+--------------------------------------------------+\n| dns_entries | [] |\n| register_dhcp_leases | None |\n+--------------------------+--------------------------------------------------+\n\n\n";
|
||||
assert_eq!(print_score_output, expected_empty_dns_score_table);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use async_trait::async_trait;
|
||||
use harmony_macros::ip;
|
||||
use harmony_types::net::MacAddress;
|
||||
use log::info;
|
||||
|
||||
use crate::executors::ExecutorError;
|
||||
use crate::interpret::InterpretError;
|
||||
use crate::interpret::Outcome;
|
||||
|
||||
use super::DHCPStaticEntry;
|
||||
use super::DhcpServer;
|
||||
@@ -12,14 +15,16 @@ use super::DnsServer;
|
||||
use super::Firewall;
|
||||
use super::HttpServer;
|
||||
use super::IpAddress;
|
||||
use super::K8sclient;
|
||||
use super::LoadBalancer;
|
||||
use super::LoadBalancerService;
|
||||
use super::LogicalHost;
|
||||
use super::Router;
|
||||
use super::TftpServer;
|
||||
|
||||
use super::Topology;
|
||||
use super::Url;
|
||||
use super::openshift::OpenshiftClient;
|
||||
use super::k8s::K8sClient;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -38,11 +43,28 @@ pub struct HAClusterTopology {
|
||||
pub switch: Vec<LogicalHost>,
|
||||
}
|
||||
|
||||
impl HAClusterTopology {
|
||||
pub async fn oc_client(&self) -> Result<Arc<OpenshiftClient>, kube::Error> {
|
||||
Ok(Arc::new(OpenshiftClient::try_default().await?))
|
||||
#[async_trait]
|
||||
impl Topology for HAClusterTopology {
|
||||
fn name(&self) -> &str {
|
||||
"HAClusterTopology"
|
||||
}
|
||||
async fn ensure_ready(&self) -> Result<Outcome, InterpretError> {
|
||||
todo!(
|
||||
"ensure_ready, not entirely sure what it should do here, probably something like verify that the hosts are reachable and all services are up and ready."
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl K8sclient for HAClusterTopology {
|
||||
async fn k8s_client(&self) -> Result<Arc<K8sClient>, String> {
|
||||
Ok(Arc::new(
|
||||
K8sClient::try_default().await.map_err(|e| e.to_string())?,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl HAClusterTopology {
|
||||
pub fn autoload() -> Self {
|
||||
let dummy_infra = Arc::new(DummyInfra {});
|
||||
let dummy_host = LogicalHost {
|
||||
@@ -67,7 +89,167 @@ impl HAClusterTopology {
|
||||
}
|
||||
}
|
||||
|
||||
struct DummyInfra;
|
||||
#[async_trait]
|
||||
impl DnsServer for HAClusterTopology {
|
||||
async fn register_dhcp_leases(&self, register: bool) -> Result<(), ExecutorError> {
|
||||
self.dns_server.register_dhcp_leases(register).await
|
||||
}
|
||||
async fn register_hosts(&self, hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
self.dns_server.register_hosts(hosts).await
|
||||
}
|
||||
fn remove_record(&self, name: &str, record_type: DnsRecordType) -> Result<(), ExecutorError> {
|
||||
self.dns_server.remove_record(name, record_type)
|
||||
}
|
||||
async fn list_records(&self) -> Vec<DnsRecord> {
|
||||
self.dns_server.list_records().await
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
self.dns_server.get_ip()
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.dns_server.get_host()
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
self.dns_server.commit_config().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl LoadBalancer for HAClusterTopology {
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
self.load_balancer.get_ip()
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.load_balancer.get_host()
|
||||
}
|
||||
async fn add_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
self.load_balancer.add_service(service).await
|
||||
}
|
||||
async fn remove_service(&self, service: &LoadBalancerService) -> Result<(), ExecutorError> {
|
||||
self.load_balancer.remove_service(service).await
|
||||
}
|
||||
async fn list_services(&self) -> Vec<LoadBalancerService> {
|
||||
self.load_balancer.list_services().await
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
self.load_balancer.ensure_initialized().await
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
self.load_balancer.commit_config().await
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
self.load_balancer.reload_restart().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpServer for HAClusterTopology {
|
||||
async fn add_static_mapping(&self, entry: &DHCPStaticEntry) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.add_static_mapping(entry).await
|
||||
}
|
||||
async fn remove_static_mapping(&self, mac: &MacAddress) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.remove_static_mapping(mac).await
|
||||
}
|
||||
async fn list_static_mappings(&self) -> Vec<(MacAddress, IpAddress)> {
|
||||
self.dhcp_server.list_static_mappings().await
|
||||
}
|
||||
async fn set_next_server(&self, ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.set_next_server(ip).await
|
||||
}
|
||||
async fn set_boot_filename(&self, boot_filename: &str) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.set_boot_filename(boot_filename).await
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
self.dhcp_server.get_ip()
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.dhcp_server.get_host()
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.commit_config().await
|
||||
}
|
||||
|
||||
async fn set_filename(&self, filename: &str) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.set_filename(filename).await
|
||||
}
|
||||
async fn set_filename64(&self, filename64: &str) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.set_filename64(filename64).await
|
||||
}
|
||||
async fn set_filenameipxe(&self, filenameipxe: &str) -> Result<(), ExecutorError> {
|
||||
self.dhcp_server.set_filenameipxe(filenameipxe).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TftpServer for HAClusterTopology {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError> {
|
||||
self.tftp_server.serve_files(url).await
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
self.tftp_server.get_ip()
|
||||
}
|
||||
|
||||
async fn set_ip(&self, ip: IpAddress) -> Result<(), ExecutorError> {
|
||||
self.tftp_server.set_ip(ip).await
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
self.tftp_server.ensure_initialized().await
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
self.tftp_server.commit_config().await
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
self.tftp_server.reload_restart().await
|
||||
}
|
||||
}
|
||||
|
||||
impl Router for HAClusterTopology {
|
||||
fn get_gateway(&self) -> super::IpAddress {
|
||||
self.router.get_gateway()
|
||||
}
|
||||
fn get_cidr(&self) -> cidr::Ipv4Cidr {
|
||||
self.router.get_cidr()
|
||||
}
|
||||
fn get_host(&self) -> LogicalHost {
|
||||
self.router.get_host()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HttpServer for HAClusterTopology {
|
||||
async fn serve_files(&self, url: &Url) -> Result<(), ExecutorError> {
|
||||
self.http_server.serve_files(url).await
|
||||
}
|
||||
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn ensure_initialized(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn commit_config(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn reload_restart(&self) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DummyInfra;
|
||||
|
||||
#[async_trait]
|
||||
impl Topology for DummyInfra {
|
||||
fn name(&self) -> &str {
|
||||
todo!()
|
||||
}
|
||||
|
||||
async fn ensure_ready(&self) -> Result<Outcome, InterpretError> {
|
||||
let dummy_msg = "This is a dummy infrastructure that does nothing";
|
||||
info!("{dummy_msg}");
|
||||
Ok(Outcome::success(dummy_msg.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
const UNIMPLEMENTED_DUMMY_INFRA: &str = "This is a dummy infrastructure, no operation is supported";
|
||||
|
||||
@@ -121,6 +303,15 @@ impl DhcpServer for DummyInfra {
|
||||
async fn set_boot_filename(&self, _boot_filename: &str) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn set_filename(&self, _filename: &str) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn set_filename64(&self, _filename: &str) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn set_filenameipxe(&self, _filenameipxe: &str) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn get_ip(&self) -> IpAddress {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
@@ -210,11 +401,7 @@ impl DnsServer for DummyInfra {
|
||||
async fn register_hosts(&self, _hosts: Vec<DnsRecord>) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
fn remove_record(
|
||||
&mut self,
|
||||
_name: &str,
|
||||
_record_type: DnsRecordType,
|
||||
) -> Result<(), ExecutorError> {
|
||||
fn remove_record(&self, _name: &str, _record_type: DnsRecordType) -> Result<(), ExecutorError> {
|
||||
unimplemented!("{}", UNIMPLEMENTED_DUMMY_INFRA)
|
||||
}
|
||||
async fn list_records(&self) -> Vec<DnsRecord> {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user