10 Commits
Author SHA1 Message Date
Dreaded_X 10c6f891d7 --wip-- [skip ci] 2026-09-25 03:39:29 +02:00
Dreaded_X 344f345854 feat: Added ftfp server implementation 2026-09-25 03:39:04 +02:00
Dreaded_X 4bdc1a1d63 chore: Migrate to rust audit fork
Committed / committed (pull_request) Successful in 25s
CI / cargo shear (pull_request) Successful in 4m21s
CI / prek (pull_request) Successful in 5m24s
CI / cargo shear (push) Successful in 6m22s
Release-plz / Release-plz Release (push) Successful in 6m51s
CI / prek (push) Successful in 7m1s
Release-plz / Release-plz PR (push) Successful in 2m54s
2026-08-27 05:01:57 +02:00
Dreaded_X 4fcce0e40a chore(deps): Upgrade dependencies
CI / cargo shear (pull_request) Successful in 5m4s
Committed / committed (pull_request) Successful in 1m10s
CI / prek (pull_request) Successful in 6m52s
Audit / cargo audit (push) Successful in 5m27s
CI / cargo shear (push) Successful in 5m27s
CI / prek (push) Successful in 5m59s
Release-plz / Release-plz Release (push) Successful in 4m51s
Release-plz / Release-plz PR (push) Successful in 4m55s
2026-08-26 02:51:51 +02:00
Release-plz 8290896f9d chore(release): Release v0.1.3
Committed / committed (pull_request) Successful in 37s
CI / cargo shear (pull_request) Successful in 7m5s
CI / prek (pull_request) Successful in 8m39s
Release-plz / Release-plz PR (push) Successful in 8m24s
Release-plz / Release-plz Release (push) Successful in 9m15s
Audit / cargo audit (push) Successful in 5m49s
CI / cargo shear (push) Successful in 5m52s
CI / prek (push) Successful in 7m46s
Release / Arch Linux (push) Successful in 8m56s
Signed-off-by: Release-plz <release-plz@noreply.huizinga.dev>
2026-04-21 03:23:16 +00:00
Dreaded_X f51746c5df feat: Add function that applies netmask to ip
Audit / cargo audit (push) Successful in 7m8s
Committed / committed (pull_request) Successful in 42s
CI / cargo shear (pull_request) Successful in 6m11s
CI / prek (pull_request) Successful in 7m43s
Release-plz / Release-plz Release (push) Successful in 9m20s
CI / prek (push) Successful in 9m22s
CI / cargo shear (push) Successful in 9m26s
Release-plz / Release-plz PR (push) Successful in 3m7s
2026-04-21 04:49:31 +02:00
Dreaded_X ca72d08cc1 refactor: Use ViaDeserialize to convert ip address 2026-04-21 04:49:30 +02:00
Release-plz 6a7ab1f9d5 chore(release): Release v0.1.2
CI / cargo shear (pull_request) Successful in 9m24s
CI / prek (pull_request) Successful in 11m0s
Committed / committed (pull_request) Successful in 1m36s
Release-plz / Release-plz PR (push) Successful in 9m26s
Release-plz / Release-plz Release (push) Successful in 12m6s
Audit / cargo audit (push) Successful in 4m5s
CI / cargo shear (push) Successful in 7m57s
Release / Arch Linux (push) Successful in 9m42s
CI / prek (push) Successful in 4m28s
Signed-off-by: Release-plz <release-plz@noreply.huizinga.dev>
2026-04-17 19:55:20 +00:00
Dreaded_X f7e4a2d545 feat: Make dns optional
Committed / committed (pull_request) Successful in 47s
CI / prek (pull_request) Successful in 6m31s
CI / cargo shear (pull_request) Successful in 7m58s
CI / cargo shear (push) Successful in 7m45s
Release-plz / Release-plz Release (push) Successful in 9m39s
CI / prek (push) Successful in 10m6s
Release-plz / Release-plz PR (push) Successful in 4m47s
2026-04-17 21:32:19 +02:00
Dreaded_X 7142ff0fa3 feat: Allow more than two dns entries 2026-04-17 20:59:42 +02:00
20 changed files with 1379 additions and 544 deletions
+2 -1
View File
@@ -7,6 +7,7 @@ on:
- "**/Cargo.lock" - "**/Cargo.lock"
schedule: schedule:
- cron: "0 0 * * *" - cron: "0 0 * * *"
workflow_dispatch:
jobs: jobs:
audit: audit:
@@ -22,6 +23,6 @@ jobs:
- name: Setup rust cache - name: Setup rust cache
uses: Swatinem/rust-cache@v2 uses: Swatinem/rust-cache@v2
- name: Audit check - name: Audit check
uses: rustsec/audit-check@v2.0.0 uses: https://git.huizinga.dev/infra/rust-audit-check@v3.0.0
with: with:
token: ${{ secrets.GITEA_TOKEN }} token: ${{ secrets.GITEA_TOKEN }}
+17
View File
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [0.1.3](https://git.huizinga.dev/infra/crete/compare/v0.1.2...v0.1.3) - 2026-04-21
### <!-- 0 -->Features
- Add function that applies netmask to ip
### <!-- 3 -->Refactor
- Use ViaDeserialize to convert ip address
## [0.1.2](https://git.huizinga.dev/infra/crete/compare/v0.1.1...v0.1.2) - 2026-04-17
### <!-- 0 -->Features
- Make dns optional
- Allow more than two dns entries
## [0.1.1](https://git.huizinga.dev/infra/crete/compare/v0.1.0...v0.1.1) - 2026-04-13 ## [0.1.1](https://git.huizinga.dev/infra/crete/compare/v0.1.0...v0.1.1) - 2026-04-13
### <!-- 2 -->Bug Fixes ### <!-- 2 -->Bug Fixes
Generated
+455 -494
View File
File diff suppressed because it is too large Load Diff
+7 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "crete" name = "crete"
version = "0.1.1" version = "0.1.3"
edition = "2024" edition = "2024"
default-run = "crete" default-run = "crete"
publish = ["infra"] publish = ["infra"]
@@ -14,11 +14,15 @@ schemars = { version = "1.2.1", features = ["semver1"] }
serde_json = "1.0.149" serde_json = "1.0.149"
[dependencies] [dependencies]
byteorder = "1.5.0"
clap = { version = "4.6.0", features = ["derive"] } clap = { version = "4.6.0", features = ["derive"] }
clap_complete = "4.6.0" clap_complete = "4.6.0"
gix-discover = { version = "0.49.0", features = ["sha1"] } gix-discover = { version = "0.55.0", features = ["sha1"] }
minijinja = { version = "2.18.0", features = ["json", "loader"] } minijinja = { version = "2.18.0", features = ["json", "loader"] }
netascii = "0.1.0"
num_enum = "0.7.6"
optional_struct = "0.5.2" optional_struct = "0.5.2"
regex = "1.13.1"
reqwest = { version = "0.13.2", default-features = false, features = [ reqwest = { version = "0.13.2", default-features = false, features = [
"blocking", "blocking",
"stream", "stream",
@@ -30,6 +34,7 @@ serde = { version = "1.0.228", features = ["derive"] }
serde_json = { workspace = true } serde_json = { workspace = true }
serde_yaml = "0.9.34" serde_yaml = "0.9.34"
thiserror = "2.0.18" thiserror = "2.0.18"
tokio = { version = "1.52.1", features = ["full"] }
walkdir = "2.5.0" walkdir = "2.5.0"
[lib] [lib]
BIN
View File
Binary file not shown.
+210
View File
@@ -0,0 +1,210 @@
version: v1alpha1
debug: false
persist: true
machine:
type: controlplane
token: 6yf327.db3x2zfs5ptbxrst
ca:
crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJQekNCOHFBREFnRUNBaEVBM0ZXN0JrK21pK3h5TFk4V29pNFNqVEFGQmdNclpYQXdFREVPTUF3R0ExVUUKQ2hNRmRHRnNiM013SGhjTk1qVXhNVEE1TURJek9USXdXaGNOTXpVeE1UQTNNREl6T1RJd1dqQVFNUTR3REFZRApWUVFLRXdWMFlXeHZjekFxTUFVR0F5dGxjQU1oQUJvSDVycnRxT3BaakRuaU5scXppOVRlT2c0OW4zMzBtcVp4CjVySXRYVEJJbzJFd1h6QU9CZ05WSFE4QkFmOEVCQU1DQW9Rd0hRWURWUjBsQkJZd0ZBWUlLd1lCQlFVSEF3RUcKQ0NzR0FRVUZCd01DTUE4R0ExVWRFd0VCL3dRRk1BTUJBZjh3SFFZRFZSME9CQllFRkkwcDJYT0pmTVE5SUV0eQpqZzlRYlk0VnJPbGZNQVVHQXl0bGNBTkJBQXkvYlFLYmxZSEtYb0QrZE1NWU1zZmY0QjkzWFJIR29ZWmpGM2lKCnp5R3lXdkh0SnYzdEY3aVJrOG9ibnpWZUR5dnlUOEM0QVAzZUkvZmlZQmFDaXcwPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
key: LS0tLS1CRUdJTiBFRDI1NTE5IFBSSVZBVEUgS0VZLS0tLS0KTUM0Q0FRQXdCUVlESzJWd0JDSUVJTDg3ckFBbTgvUzlNSU1GQm9pZ2ZpUDg4Mmg3QlNUSGppUTFrSng2QmNEVAotLS0tLUVORCBFRDI1NTE5IFBSSVZBVEUgS0VZLS0tLS0K
certSANs: []
kubelet:
image: ghcr.io/siderolabs/kubelet:v1.35.3
extraArgs:
rotate-server-certificates: "true"
extraMounts:
- destination: /var/lib/longhorn
type: bind
source: /var/lib/longhorn
options:
- bind
- rshared
- rw
defaultRuntimeSeccompProfileEnabled: true
disableManifestsDirectory: true
network: {}
install:
disk: /dev/sda
image: factory.talos.dev/metal-installer/53edcacbd9153fcbce2ba04cc41e1c6867ef92b462b37344de8c420ceeb21816:v1.12.6
wipe: false
grubUseUKICmdline: true
files:
- content: |-
[plugins."io.containerd.cri.v1.images"]
discard_unpacked_layers = false
permissions: 0o0
path: /etc/cri/conf.d/20-customization.part
op: create
features:
diskQuotaSupport: true
kubePrism:
enabled: true
port: 7445
hostDNS:
enabled: true
forwardKubeDNSToHost: false
nodeLabels:
node.kubernetes.io/exclude-from-external-load-balancers: ""
cluster:
id: CZ7M2eK-gs9qR50_MYzIL8653An9nHRGCR2R1rfIfSo=
secret: hnYuExJx1JeFfG6Ss3yYI1wuJRqokD9laXboLmI0A4Q=
controlPlane:
endpoint: https://10.0.2.1:6443
clusterName: titan
network:
cni:
name: none
dnsDomain: cluster.local
podSubnets:
- 10.244.0.0/16
serviceSubnets:
- 10.96.0.0/12
token: 5607yr.7fbnk2hyaukxnkwx
secretboxEncryptionSecret: NSHASj2WMMmiZqluiHGKdiJuaxejaz6bmytD07ccp/A=
ca:
crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJpakNDQVRDZ0F3SUJBZ0lSQU4xVTVpY2FlY1B6QXRTeDFobjdCaU13Q2dZSUtvWkl6ajBFQXdJd0ZURVQKTUJFR0ExVUVDaE1LYTNWaVpYSnVaWFJsY3pBZUZ3MHlOVEV4TURrd01qTTVNakJhRncwek5URXhNRGN3TWpNNQpNakJhTUJVeEV6QVJCZ05WQkFvVENtdDFZbVZ5Ym1WMFpYTXdXVEFUQmdjcWhrak9QUUlCQmdncWhrak9QUU1CCkJ3TkNBQVJPYmVEM3UzbWVoYk1NWE9xeHJKYzNFaGovZ1NrNENENm42cXhQcTBIVHdDbk1iY2l1cmNZUTk5VkkKM0ZPUU92ZCtGMGtKS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aTJISC9Yckp4c0Q0Vm5CMFE0TXdmV0taRDFHZXgKVUYxTzNLS0VJWGlwUzlGSTVpK0VweXg0QmtKYnpET1RNejBjS2UvZ3kzQTFCbE14Q1JhMUttamZLZDNWLzBzWgplancvQUFtZkR5QWNISStvRzVDQzBoR2lkWVZWb3hnNU1RRG1NSW44bTdCMWE2VS9tUE9aNldjSkF6NnNZakpkCmlqMGpRZEtsN0hoQkNGVnFpdFNJWHlCNUR1WjVUdkVDZ2dFQU9CVHpHelJHdGVzM1YvenFEaXNiSE04ZXdMMFMKaElqNnJ3ajlIRktmS04wY0E3QUR1UXBLbHFPcU8xZFJvSmZlYm1SWHpUeWxjQ1U2Y3RKQW1PWFF5V1U0dEhOaQpiNWpJRnlFaWRybVY5Z0d5VitIeFJicmQ2bGoyczl2MlEzNkJJbkJCYUxzR2cxeHN0OWU1ZzlyTndTY1RCZ25rCmthV1ZqMGdQcnY1VnNCUVF1Y2ZhMUVhVVhjZUpvY3BEcXcvS0hJbkxkYkNVN3dBKzZMRWZYZXZMbVpEdGluSkMKRWdZdUQrRWpOYUNrWDI4VTErVnk3NS81bXpBT1lCcFV4UVRQQ1NSb1NlLzBXWWJlelBDRjYycXBxZGhvdEZwVAo0U0RIQVZkemVBSXlOSFhUQXozeGMxcnRiUU03VGVWUXE1N3Y2cnkyWkIvZ1pqNUdwUHRvN1NmRzJRPT0KLS0tLS1FTkQgUlNBIFBSSVZBVEUgS0VZLS0tLS0K
apiServer:
image: registry.k8s.io/kube-apiserver:v1.35.3
admissionControl:
- name: PodSecurity
configuration:
apiVersion: pod-security.admission.config.k8s.io/v1alpha1
defaults:
audit: restricted
audit-version: latest
enforce: baseline
enforce-version: latest
warn: restricted
warn-version: latest
exemptions:
namespaces:
- kube-system
runtimeClasses: []
usernames: []
kind: PodSecurityConfiguration
auditPolicy:
apiVersion: audit.k8s.io/v1
kind: Policy
rules:
- level: Metadata
controllerManager:
image: registry.k8s.io/kube-controller-manager:v1.35.3
proxy:
disabled: true
image: registry.k8s.io/kube-proxy:v1.35.3
scheduler:
image: registry.k8s.io/kube-scheduler:v1.35.3
discovery:
enabled: true
registries:
kubernetes:
disabled: true
service: {}
etcd:
ca:
crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJmakNDQVNTZ0F3SUJBZ0lSQU02WFZ6VTd6YlU5QjlqcTJZOU5IRzh3Q2dZSUtvWkl6ajBFQXdJd0R6RU4KTUFzR0ExVUVDaE1FWlhSalpEQWVGdzB5TlRFeE1Ea3dNak01TWpCYUZ3MHpOVEV4TURjd01qTTVNakJhTUE4eApEVEFMQmdOVkJBb1RCR1YwWTJRd1dUQVRCZ2NxaGtqT1BRSUJCZ2dxaGtqT1BRTUJCd05DQUFRcUhzRllaNFA4CmNybTVzaFZEaWNvWWFweXJneGFsaWppcUJubWVMazVlOVM4RnVYMGFac2dwQXdpMkIwWUNNVndQM25SK3d3YVkKVVRtWGpOSDBhcXp2bzJFd1h6QU9CZ05WSFE4QkFmOEVCQU1DQW9Rd0hRWURWUjBsQkJZd0ZBWUlLd1lCQlFVSApBd0VHQ0NzR0FRVUZCd01DTUE4R0ExVWRFd0VCL3dRRk1BTUJBZjh3SFFZRFZSME9CQllFRkxYMkJXSVdKU3diCk9zRW1JR21MTGI4aGp0VXhNQW9HQ0NxR1NNNDlCQU1DQTBnQU1FVUNJRnBCbGdXUHB6Tkg0UkkrYTBrMEczcWIKSE42Z1pFSU5PZkhnWXV2MHNIYy9BaUVBc3p0eTd4ckdLVVYrOXF6bEpNRXBsWi9jVTJ4NFpQbVUzMmdraUQyagpDc1U9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K
key: LS0tLS1CRUdJTiBFQyBQUklWQVRFIEtFWS0tLS0tCk1IY0NBUUVFSUg1L2VmL0d0T1lKN2FuVWUzZnBQRW9ta21oRlJpOWM4eGtLN3ZTTGJPZy9vQW9HQ0NxR1NNNDkKQXdFSG9VUURRZ0FFS2g3QldHZUQvSEs1dWJJVlE0bktHR3FjcTRNV3BZbzRxZ1o1bmk1T1h2VXZCYmw5R21iSQpLUU1JdGdkR0FqRmNEOTUwZnNNR21GRTVsNHpSOUdxczd3PT0KLS0tLS1FTkQgRUMgUFJJVkFURSBLRVktLS0tLQo=
extraManifests:
- https://raw.githubusercontent.com/alex1989hu/kubelet-serving-cert-approver/main/deploy/standalone-install.yaml
- https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
- https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.4.1/standard-install.yaml
inlineManifests:
- name: sops-key
contents: |-
apiVersion: v1
kind: Namespace
metadata:
name: flux-system
---
apiVersion: v1
kind: Secret
metadata:
name: sops-gpg
namespace: flux-system
stringData:
age.agekey: |
# created: 2025-12-01T02:18:04+01:00
# public key: age1hktythzvsnth6u5en2lvag0tftnj9r03w7rpnzfgzgf5w95qxycq2azufj
AGE-SECRET-KEY-1ES2W2EQY2MXKF04QSNMWHERKFX0Y27CDMCWFX47Z3PV6H37R735SV8UDSZ
- name: cluster-variables
contents: |-
---
apiVersion: v1
kind: Namespace
metadata:
name: flux-system
---
apiVersion: v1
kind: ConfigMap
metadata:
name: cluster-variables
namespace: flux-system
data:
cluster_env: production
allowSchedulingOnControlPlanes: true
---
apiVersion: v1alpha1
kind: HostnameConfig
auto: "off"
hostname: helios
---
apiVersion: v1alpha1
kind: LinkConfig
name: enp2s0
up: true
mtu: 9000
addresses:
- address: 10.0.0.202/22
routes:
- gateway: 10.0.0.1
---
apiVersion: v1alpha1
kind: TimeSyncConfig
ntp:
servers:
- nl.pool.ntp.org
---
apiVersion: v1alpha1
kind: ResolverConfig
nameservers:
- address: 1.1.1.1
- address: 8.8.8.8
---
apiVersion: v1alpha1
kind: Layer2VIPConfig
name: 10.0.2.1
link: enp2s0
---
apiVersion: v1alpha1
kind: ExtensionServiceConfig
name: tailscale
environment:
- TS_AUTHKEY=hskey-auth-dn_t5EiIfKGe-GHafxPQRMudp4G_ygs4Rmc5a6TSzdxV4HzKklwOEy-gOiIovOxHfoFlrTt0cpiWp
- TS_EXTRA_ARGS=--login-server https://headscale.huizinga.dev
- TS_ROUTES=
---
apiVersion: v1alpha1
kind: UserVolumeConfig
name: longhorn
provisioning:
diskSelector:
match: system_disk
grow: true
maxSize: 2000GB
---
apiVersion: v1alpha1
kind: UserVolumeConfig
name: local-path-provisioner
volumeType: directory
---
apiVersion: v1alpha1
kind: VolumeConfig
name: EPHEMERAL
provisioning:
maxSize: 30GB
+2 -3
View File
@@ -140,12 +140,11 @@
"array", "array",
"null" "null"
], ],
"default": null,
"items": { "items": {
"type": "string", "type": "string",
"format": "ipv4" "format": "ipv4"
}, }
"maxItems": 2,
"minItems": 2
}, },
"gateway": { "gateway": {
"type": [ "type": [
+2 -3
View File
@@ -136,12 +136,11 @@
"array", "array",
"null" "null"
], ],
"default": null,
"items": { "items": {
"type": "string", "type": "string",
"format": "ipv4" "format": "ipv4"
}, }
"maxItems": 2,
"minItems": 2
}, },
"gateway": { "gateway": {
"type": [ "type": [
+2
View File
@@ -49,4 +49,6 @@ pub enum Commands {
Generate, Generate,
/// Generate completions for your current shell /// Generate completions for your current shell
ShellCompletions, ShellCompletions,
/// Test
Serve,
} }
+18 -8
View File
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::path::PathBuf; use std::path::PathBuf;
use std::process::Command; use std::process::Command;
@@ -73,7 +74,7 @@ struct ClusterDeserialize {
pub struct Cluster { pub struct Cluster {
pub(crate) name: String, pub(crate) name: String,
pub(crate) version: Version, pub(crate) version: Version,
nodes: Vec<Node>, nodes: HashMap<String, Node>,
cluster_env: ClusterEnv, cluster_env: ClusterEnv,
pub(crate) control_plane_ip: Ipv4Addr, pub(crate) control_plane_ip: Ipv4Addr,
pub(crate) secrets_file: PathBuf, pub(crate) secrets_file: PathBuf,
@@ -114,21 +115,24 @@ impl Cluster {
let cluster = Self { let cluster = Self {
name: cluster_name.into(), name: cluster_name.into(),
version: cluster.version, version: cluster.version,
nodes: vec![], nodes: HashMap::new(),
cluster_env: cluster.cluster_env, cluster_env: cluster.cluster_env,
control_plane_ip: cluster.control_plane_ip, control_plane_ip: cluster.control_plane_ip,
secrets_file, secrets_file,
}; };
let nodes = nodes let nodes = nodes
.iter() .into_iter()
.map(|name| Node::get(name, env, &cluster, &default, &base)) .map(|name| {
let node = Node::get(&name, env, &cluster, &default, &base);
(node.hostname().into(), node)
})
.collect(); .collect();
Self { nodes, ..cluster } Self { nodes, ..cluster }
} }
pub fn get_all() -> Vec<Cluster> { pub fn get_all() -> HashMap<String, Cluster> {
let env = PathEnvironment::new_patches(); let env = PathEnvironment::new_patches();
WalkDir::new(get_talos_path().join("clusters")) WalkDir::new(get_talos_path().join("clusters"))
@@ -145,13 +149,19 @@ impl Cluster {
return None; return None;
} }
Some(Cluster::get(&name, &env)) let cluster = Cluster::get(&name, &env);
Some((name, cluster))
}) })
.collect() .collect()
} }
pub fn nodes(&self) -> &[Node] { pub fn nodes(&self) -> impl Iterator<Item = &Node> {
&self.nodes self.nodes.values()
}
pub fn node(&self, name: &str) -> Option<&Node> {
self.nodes.get(name)
} }
pub fn talosctl_gen_config_command(&self) -> Command { pub fn talosctl_gen_config_command(&self) -> Command {
+11 -5
View File
@@ -1,8 +1,8 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::ops::Deref; use std::ops::Deref;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr;
use minijinja::value::ViaDeserialize;
use minijinja::{AutoEscape, Environment, path_loader}; use minijinja::{AutoEscape, Environment, path_loader};
use walkdir::WalkDir; use walkdir::WalkDir;
@@ -16,6 +16,13 @@ pub struct PathEnvironment<'a> {
path: PathBuf, path: PathBuf,
} }
fn apply_netmask(
ip: ViaDeserialize<Ipv4Addr>,
netmask: ViaDeserialize<Ipv4Addr>,
) -> Result<String, minijinja::Error> {
Ok((*ip & *netmask).to_string())
}
impl<'a> PathEnvironment<'a> { impl<'a> PathEnvironment<'a> {
pub fn new(path: &Path) -> Self { pub fn new(path: &Path) -> Self {
let mut env = Environment::new(); let mut env = Environment::new();
@@ -27,10 +34,7 @@ impl<'a> PathEnvironment<'a> {
env.set_auto_escape_callback(|_| AutoEscape::None); env.set_auto_escape_callback(|_| AutoEscape::None);
// Add filters // Add filters
env.add_filter("to_prefix", |netmask: String| { env.add_filter("to_prefix", |netmask: ViaDeserialize<Ipv4Addr>| {
let netmask = Ipv4Addr::from_str(&netmask).map_err(|err| {
minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, err.to_string())
})?;
let mask = netmask.to_bits(); let mask = netmask.to_bits();
let prefix = mask.leading_ones(); let prefix = mask.leading_ones();
@@ -44,6 +48,8 @@ impl<'a> PathEnvironment<'a> {
} }
}); });
env.add_function("apply_netmask", apply_netmask);
// Helper function for getting the path to kubeconfig files // Helper function for getting the path to kubeconfig files
env.add_filter("kubeconfig", move |names: Vec<String>| { env.add_filter("kubeconfig", move |names: Vec<String>| {
names names
+2 -1
View File
@@ -1,4 +1,4 @@
#![feature(impl_trait_in_assoc_type, path_absolute_method)] #![feature(impl_trait_in_assoc_type, path_absolute_method, never_type)]
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::OnceLock; use std::sync::OnceLock;
@@ -8,6 +8,7 @@ pub mod node;
pub mod patch; pub mod patch;
pub mod schematic; pub mod schematic;
pub mod secret; pub mod secret;
pub mod tftp;
pub(crate) static REPO_PATH: OnceLock<PathBuf> = OnceLock::new(); pub(crate) static REPO_PATH: OnceLock<PathBuf> = OnceLock::new();
+57 -12
View File
@@ -6,8 +6,10 @@ use clap::{CommandFactory, Parser};
use clap_complete::{Shell, generate as generate_complete}; use clap_complete::{Shell, generate as generate_complete};
use crete::cluster::Cluster; use crete::cluster::Cluster;
use crete::environment::PathEnvironment; use crete::environment::PathEnvironment;
use crete::{get_configs_path, get_repo_path, set_repo_path}; use crete::tftp::ServerError;
use crete::{get_configs_path, get_repo_path, set_repo_path, tftp};
use minijinja::context; use minijinja::context;
use regex::Regex;
use thiserror::Error; use thiserror::Error;
use crate::cli::{Cli, Commands, GlobalOpts}; use crate::cli::{Cli, Commands, GlobalOpts};
@@ -16,10 +18,15 @@ use crate::cli::{Cli, Commands, GlobalOpts};
enum Error { enum Error {
#[error("No clusters where found")] #[error("No clusters where found")]
NoClustersFound, NoClustersFound,
#[error("Server error: {0}")]
Server(#[from] ServerError),
} }
fn run_command(mut command: Command) { async fn run_command(mut command: Command) {
let output = command.output().unwrap(); let output = tokio::task::spawn_blocking(move || command.output().unwrap())
.await
.unwrap();
if !output.stdout.is_empty() { if !output.stdout.is_empty() {
println!("{}", String::from_utf8_lossy(&output.stdout).trim_end()); println!("{}", String::from_utf8_lossy(&output.stdout).trim_end());
} }
@@ -28,7 +35,7 @@ fn run_command(mut command: Command) {
} }
} }
fn generate(opts: &GlobalOpts) -> Result<(), Error> { async fn generate(opts: &GlobalOpts) -> Result<(), Error> {
set_repo_path(&opts.repo); set_repo_path(&opts.repo);
let clusters = Cluster::get_all(); let clusters = Cluster::get_all();
@@ -50,7 +57,7 @@ fn generate(opts: &GlobalOpts) -> Result<(), Error> {
let content = template let content = template
.render(context! { .render(context! {
clusters, clusters => clusters.values().collect::<Vec<_>>(),
root => opts.repo root => opts.repo
}) })
.unwrap(); .unwrap();
@@ -66,30 +73,68 @@ fn generate(opts: &GlobalOpts) -> Result<(), Error> {
std::fs::create_dir(&path).unwrap(); std::fs::create_dir(&path).unwrap();
// Generate config files // Generate config files
for cluster in clusters { for cluster in clusters.values() {
for node in cluster.nodes() { for node in cluster.nodes() {
run_command(node.talosctl_gen_config_command(&cluster)); let config = node.talosctl_gen_config(cluster).await;
let path = node.config_path(cluster);
std::fs::create_dir_all(path.parent().expect("Config should have parent directory"))
.unwrap();
std::fs::write(path, config).unwrap();
} }
run_command(cluster.talosctl_gen_config_command()); run_command(cluster.talosctl_gen_config_command()).await;
run_command(cluster.talosctl_add_endpoint_command()); run_command(cluster.talosctl_add_endpoint_command()).await;
run_command(cluster.talosctl_merge_command()); run_command(cluster.talosctl_merge_command()).await;
} }
Ok(()) Ok(())
} }
fn main() -> Result<(), Error> { #[tokio::main]
async fn main() -> Result<(), Error> {
let cli = Cli::parse(); let cli = Cli::parse();
match cli.command { match cli.command {
Commands::Generate => generate(&cli.global_opts)?, Commands::Generate => generate(&cli.global_opts).await.unwrap(),
Commands::ShellCompletions => generate_complete( Commands::ShellCompletions => generate_complete(
Shell::from_env().unwrap_or(Shell::Bash), Shell::from_env().unwrap_or(Shell::Bash),
&mut Cli::command(), &mut Cli::command(),
"crete", "crete",
&mut std::io::stdout(), &mut std::io::stdout(),
), ),
Commands::Serve => {
set_repo_path(&cli.global_opts.repo);
tftp::serve(|filename| {
let filename = filename.to_owned();
async move {
let re = Regex::new(r"talos/(?<cluster>.+)/(?<node>.+)\.ya?ml")
.expect("Regex should be valid");
if let Some(caps) = re.captures(&filename) {
let cluster = &caps["cluster"];
let node = &caps["node"];
let clusters = Cluster::get_all();
let cluster = clusters.get(cluster)?;
let node = cluster.node(node)?;
let config = node.talosctl_gen_config(cluster).await;
Some(config.into())
} else {
match filename.as_str() {
"ipxe.pxe" => Some(include_bytes!("../bin/ipxe.pxe").into()),
"test" => Some(vec![1, 2, 3, 4]),
_ => None,
}
}
}
})
.await?;
}
}; };
Ok(()) Ok(())
+28 -7
View File
@@ -1,10 +1,11 @@
use std::net::Ipv4Addr; use std::net::Ipv4Addr;
use std::process::Command; use std::path::PathBuf;
use minijinja::Environment; use minijinja::Environment;
use optional_struct::{Applicable, optional_struct}; use optional_struct::{Applicable, optional_struct};
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio::process::Command;
use crate::cluster::{Base, Cluster}; use crate::cluster::{Base, Cluster};
use crate::patch::{OptionalPatches, OptionalPatchesString, Patches}; use crate::patch::{OptionalPatches, OptionalPatchesString, Patches};
@@ -12,6 +13,17 @@ use crate::schematic::Schematic;
use crate::secret::Secret; use crate::secret::Secret;
use crate::{get_configs_path, get_talos_path}; use crate::{get_configs_path, get_talos_path};
async fn get_output(mut command: Command) -> String {
let output = command.output().await.unwrap();
if !output.stderr.is_empty() {
println!("{}", String::from_utf8_lossy(&output.stderr).trim_end());
}
String::from_utf8_lossy(&output.stdout)
.trim_end()
.to_owned()
}
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Serialize, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
enum NodeType { enum NodeType {
@@ -53,7 +65,8 @@ struct Network {
ip: Ipv4Addr, ip: Ipv4Addr,
netmask: Ipv4Addr, netmask: Ipv4Addr,
gateway: Ipv4Addr, gateway: Ipv4Addr,
dns: [Ipv4Addr; 2], #[serde(default)]
dns: Option<Vec<Ipv4Addr>>,
#[optional_rename(OptionalTailscale)] #[optional_rename(OptionalTailscale)]
#[optional_wrap] #[optional_wrap]
tailscale: Tailscale, tailscale: Tailscale,
@@ -176,10 +189,11 @@ impl Node {
Node { patches, ..node } Node { patches, ..node }
} }
pub fn talosctl_gen_config_command(&self, cluster: &Cluster) -> Command { pub fn hostname(&self) -> &str {
let mut path = get_configs_path().join(&cluster.name).join(&self.hostname); &self.hostname
path.add_extension("yaml"); }
pub async fn talosctl_gen_config(&self, cluster: &Cluster) -> String {
let mut command = Command::new("talosctl"); let mut command = Command::new("talosctl");
command.args([ command.args([
"gen", "gen",
@@ -203,7 +217,7 @@ impl Node {
"--with-docs=false", "--with-docs=false",
"--with-examples=false", "--with-examples=false",
"-o", "-o",
path.to_str().expect("Path should be valid utf-8"), "-", // path.to_str().expect("Path should be valid utf-8"),
]); ]);
for patch in &self.patches.all { for patch in &self.patches.all {
@@ -217,7 +231,14 @@ impl Node {
]); ]);
} }
command get_output(command).await
}
pub fn config_path(&self, cluster: &Cluster) -> PathBuf {
let mut path = get_configs_path().join(&cluster.name).join(&self.hostname);
path.add_extension("yaml");
path
} }
} }
+17 -8
View File
@@ -1,5 +1,6 @@
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize}; use serde::{Deserialize, Deserializer, Serialize};
use tokio::runtime::Handle;
use crate::get_talos_path; use crate::get_talos_path;
@@ -11,7 +12,7 @@ where
let path = get_talos_path().join("schematics").join(name); let path = get_talos_path().join("schematics").join(name);
let content = std::fs::read_to_string(path).unwrap().trim().to_owned(); let content = std::fs::read_to_string(path).unwrap().trim().to_owned();
let client = reqwest::blocking::ClientBuilder::new() let client = reqwest::ClientBuilder::new()
.user_agent(format!( .user_agent(format!(
"{}/{}", "{}/{}",
std::env!("CARGO_PKG_NAME"), std::env!("CARGO_PKG_NAME"),
@@ -20,19 +21,27 @@ where
.build() .build()
.unwrap(); .unwrap();
let res = client let res = tokio::task::block_in_place(|| {
.post("https://factory.talos.dev/schematics") Handle::current().block_on(async {
.body(content) client
.send() .post("https://factory.talos.dev/schematics")
.map_err(serde::de::Error::custom)?; .body(content)
.send()
.await
})
})
.map_err(serde::de::Error::custom)?;
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Response { struct Response {
id: String, id: String,
} }
let response: Response = serde_json::from_str(&res.text().map_err(serde::de::Error::custom)?) let text =
.map_err(serde::de::Error::custom)?; tokio::task::block_in_place(|| Handle::current().block_on(async { res.text().await }))
.map_err(serde::de::Error::custom)?;
let response: Response = serde_json::from_str(&text).map_err(serde::de::Error::custom)?;
Ok(response.id) Ok(response.id)
} }
+20
View File
@@ -0,0 +1,20 @@
use std::io;
use std::string::FromUtf8Error;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Invalid op code '{0}'")]
InvalidOpCode(u16),
#[error("Invalid error code '{0}'")]
InvalidErrorCode(u16),
#[error("Invalid mode '{0}'")]
InvalidMode(String),
#[error("String contains invalid characters")]
InvalidString(#[from] FromUtf8Error),
#[error("Unterminated string")]
UnterminatedString,
#[error("Io error: {0}")]
Io(#[from] io::Error),
}
+7
View File
@@ -0,0 +1,7 @@
mod error;
mod packet;
mod server;
pub use error::Error;
pub use packet::Packet;
pub use server::{Error as ServerError, serve};
+353
View File
@@ -0,0 +1,353 @@
use std::io::{BufRead, BufReader, BufWriter, Cursor, Read, Write};
use std::net::SocketAddr;
use byteorder::{NetworkEndian, ReadBytesExt, WriteBytesExt};
use num_enum::{IntoPrimitive, TryFromPrimitive};
use tokio::net::UdpSocket;
use crate::tftp::Error;
// 2 bytes op code + 2 bytes block number + max 512 bytes data
pub(crate) const PACKET_SIZE: usize = 2 + 2 + 512;
fn decode_null_terminated<R>(reader: &mut BufReader<R>) -> Result<String, Error>
where
R: Read + ?Sized,
{
let mut text = Vec::new();
reader.read_until(0, &mut text)?;
// Make sure we ended with a null terminator
match text.pop() {
Some(0) => {}
None | Some(_) => return Err(Error::UnterminatedString),
}
Ok(String::from_utf8(text)?)
}
fn encode_null_terminated<W>(writer: &mut BufWriter<W>, text: impl AsRef<str>) -> Result<(), Error>
where
W: Write + ?Sized,
{
let text = text.as_ref().as_bytes();
writer.write_all(text)?;
// Add null terminator
writer.write_u8(0)?;
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
NetAscii,
Octet,
Mail,
}
impl Mode {
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let mut mode = decode_null_terminated(reader)?;
mode.make_ascii_lowercase();
let mode = mode;
Ok(match mode.as_str() {
"netascii" => Self::NetAscii,
"octet" => Self::Octet,
"mail" => Self::Mail,
_ => return Err(Error::InvalidMode(mode)),
})
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
let mode = match &self {
Mode::NetAscii => "netascii",
Mode::Octet => "octet",
Mode::Mail => "mail",
};
encode_null_terminated(writer, mode)?;
Ok(())
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Request {
filename: String,
mode: Mode,
}
impl Request {
pub fn filename(&self) -> &str {
&self.filename
}
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let filename = decode_null_terminated(reader)?;
let mode = Mode::decode(reader)?;
Ok(Self { filename, mode })
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
encode_null_terminated(writer, &self.filename)?;
self.mode.encode(writer)?;
Ok(())
}
pub fn mode(&self) -> Mode {
self.mode
}
}
#[derive(Debug)]
pub struct Data {
block: u16,
data: Vec<u8>,
}
impl Data {
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let block = reader.read_u16::<NetworkEndian>()?;
let mut data = Vec::new();
reader.read_to_end(&mut data)?;
Ok(Self { data, block })
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
writer.write_u16::<NetworkEndian>(self.block)?;
writer.write_all(&self.data)?;
Ok(())
}
}
#[derive(Debug)]
pub struct Ack(u16);
impl Ack {
pub fn block(&self) -> u16 {
self.0
}
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let number = reader.read_u16::<NetworkEndian>()?;
Ok(Self(number))
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
writer.write_u16::<NetworkEndian>(self.0)?;
Ok(())
}
}
#[derive(Debug, TryFromPrimitive, IntoPrimitive, Clone, Copy)]
#[repr(u16)]
pub enum ErrorCode {
NotDefined,
FileNotFound,
AccessViolation,
DiskFull,
Illegal,
UnknownTransferId,
FileAlreadyExists,
NoSuchUser,
}
impl ErrorCode {
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let code = reader.read_u16::<NetworkEndian>()?;
Self::try_from_primitive(code).map_err(|err| Error::InvalidErrorCode(err.number))
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
let code: u16 = (*self).into();
writer.write_u16::<NetworkEndian>(code)?;
Ok(())
}
}
#[derive(Debug)]
pub struct ErrorMessage {
code: ErrorCode,
message: String,
}
impl ErrorMessage {
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let code = ErrorCode::decode(reader)?;
let message = decode_null_terminated(reader)?;
Ok(Self { code, message })
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
self.code.encode(writer)?;
encode_null_terminated(writer, &self.message)?;
Ok(())
}
}
#[derive(Debug)]
pub enum Packet {
Read(Request),
Write(Request),
Data(Data),
Ack(Ack),
Error(ErrorMessage),
}
impl Packet {
pub fn data(block: u16, data: &[u8]) -> Self {
Self::Data(Data {
block,
data: data.into(),
})
}
pub fn ack(block: u16) -> Self {
Self::Ack(Ack(block))
}
pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
Self::Error(ErrorMessage {
code,
message: message.into(),
})
}
fn decode<R>(reader: &mut BufReader<R>) -> Result<Self, Error>
where
R: Read + ?Sized,
{
let op_code = reader.read_u16::<NetworkEndian>()?;
Ok(match op_code {
1 => Self::Read(Request::decode(reader)?),
2 => Self::Write(Request::decode(reader)?),
3 => Self::Data(Data::decode(reader)?),
4 => Self::Ack(Ack::decode(reader)?),
5 => Self::Error(ErrorMessage::decode(reader)?),
_ => return Err(Error::InvalidOpCode(op_code)),
})
}
fn encode<W>(&self, writer: &mut BufWriter<W>) -> Result<(), Error>
where
W: Write + ?Sized,
{
match &self {
Self::Read(inner) => {
writer.write_u16::<NetworkEndian>(1)?;
inner.encode(writer)?;
}
Self::Write(inner) => {
writer.write_u16::<NetworkEndian>(2)?;
inner.encode(writer)?;
}
Self::Data(inner) => {
writer.write_u16::<NetworkEndian>(3)?;
inner.encode(writer)?;
}
Self::Ack(inner) => {
writer.write_u16::<NetworkEndian>(4)?;
inner.encode(writer)?;
}
Self::Error(inner) => {
writer.write_u16::<NetworkEndian>(5)?;
inner.encode(writer)?;
}
};
Ok(())
}
pub async fn recv_from(socket: &UdpSocket) -> Result<(Self, SocketAddr), Error> {
let mut buf = Vec::with_capacity(PACKET_SIZE);
let (_, src) = socket.recv_buf_from(&mut buf).await?;
let packet = buf.try_into()?;
Ok((packet, src))
}
pub async fn send_to(&self, socket: &UdpSocket, src: &SocketAddr) -> Result<(), Error> {
let buf: Vec<_> = self.try_into()?;
socket.send_to(&buf, src).await?;
Ok(())
}
}
impl TryFrom<&Packet> for Vec<u8> {
type Error = Error;
fn try_from(packet: &Packet) -> Result<Self, Self::Error> {
let mut buf = Vec::with_capacity(PACKET_SIZE);
let mut writer = BufWriter::new(Cursor::new(&mut buf));
packet.encode(&mut writer)?;
// Normally the writer would get dropped after we return, but since it has a mutable
// borrow in buf we have to drop it first.
drop(writer);
Ok(buf)
}
}
impl TryFrom<Vec<u8>> for Packet {
type Error = Error;
fn try_from(buf: Vec<u8>) -> Result<Self, <Packet as TryFrom<Vec<u8>>>::Error> {
let mut reader = BufReader::new(Cursor::new(buf));
Packet::decode(&mut reader)
}
}
+168
View File
@@ -0,0 +1,168 @@
use std::io;
use std::net::SocketAddr;
use std::time::Duration;
use thiserror::Error;
use tokio::net::UdpSocket;
use crate::tftp::packet::{ErrorCode, Mode};
use crate::tftp::{self, Packet};
#[derive(Debug, Error)]
pub enum Error {
#[error("{0}")]
Tftp(#[from] tftp::Error),
#[error("Io error: {0}")]
Io(#[from] io::Error),
#[error("Unsupported operation: {0:#?}")]
UnsupportedOperation(Packet),
#[error("File not found: {0}")]
FileNotFound(String),
#[error("Unsupported mode: {0:?}")]
UnsupportedMode(Mode),
#[error("Source changed: {0}")]
SourceChanged(SocketAddr),
#[error("UnexpectedPacket: {0:#?}")]
UnexpectedPacket(Packet),
#[error("Timeout")]
Timeout,
}
pub async fn handle_connection<F, Fut>(
src: SocketAddr,
packet: Packet,
callback: F,
) -> Result<(), Error>
where
F: Fn(&str) -> Fut,
Fut: Future<Output = Option<Vec<u8>>>,
{
let socket = UdpSocket::bind("127.0.0.1:0").await?;
println!(
"{src}: Connecting from {}",
socket.local_addr().expect("Socket is bound")
);
let Packet::Read(request) = packet else {
Packet::error(ErrorCode::NotDefined, "Operation not supported")
.send_to(&socket, &src)
.await?;
return Err(Error::UnsupportedOperation(packet));
};
let filename = request.filename();
println!("{src}: {filename} [{:?}]", request.mode());
let Some(data) = callback(filename).await else {
Packet::error(ErrorCode::FileNotFound, "Unknown file")
.send_to(&socket, &src)
.await?;
return Err(Error::FileNotFound(filename.into()));
};
let mode = request.mode();
let data = match mode {
// In case of netascii mode we need to re-encode to escape certain sequences
Mode::NetAscii => netascii::Netascii::from_bytes(data).collect(),
Mode::Octet => data,
_ => {
Packet::error(
ErrorCode::NotDefined,
format!("Mode {mode:?} is not supported"),
)
.send_to(&socket, &src)
.await?;
return Err(Error::UnsupportedMode(mode));
}
};
let mut chunks = data.chunks(512).enumerate();
let mut chunk = chunks.next();
let mut timeout = 0;
loop {
// Send the first byte
if let Some((index, chunk)) = chunk {
Packet::data((index + 1) as u16, chunk)
.send_to(&socket, &src)
.await?;
}
tokio::select! {
recv = Packet::recv_from(&socket) => {
timeout = 0;
let (packet, new_src) = recv?;
// I think this is might technically be possible and fine, but I don't
// really know how to test it properly so we don't support it.
if new_src != src {
Packet::error(ErrorCode::Illegal, "Source changed")
.send_to(&socket, &src)
.await?;
return Err(Error::SourceChanged(new_src));
}
match packet {
Packet::Ack(ack) => {
// If we receive an ack for the current chunk go to the next one
if let Some((index, _)) = chunk
&& (index + 1) as u16 == ack.block()
{
chunk = chunks.next();
}
if chunk.is_none() {
break;
}
}
_ => {
Packet::error(ErrorCode::Illegal, "Unexpected packet")
.send_to(&socket, &src)
.await?;
return Err(Error::UnexpectedPacket(packet));
}
}
},
_ = tokio::time::sleep(Duration::from_secs(1)) => {
timeout += 1;
if timeout == 5 {
return Err(Error::Timeout);
}
}
}
}
println!("{src}: Transmission complete");
Ok(())
}
pub async fn serve<F, Fut>(callback: F) -> Result<!, Error>
where
F: (Fn(&str) -> Fut) + Clone + Send + 'static,
Fut: Future<Output = Option<Vec<u8>>> + Send + 'static,
{
let socket = UdpSocket::bind("127.0.0.1:69").await?;
println!("Server started");
loop {
let (packet, src) = Packet::recv_from(&socket).await?;
let callback = callback.clone();
tokio::spawn({
async move {
if let Err(err) = handle_connection(src, packet, callback).await {
println!("{src}: {err}")
}
}
});
}
}
+1
View File
@@ -0,0 +1 @@