🎉 init: kur installs the newest forge release of each app, with health check, rollback and self-update
Browse files at this commit13 changed files +1771 -0
- .forge/ci.toml +42 -0
- .gitignore +1 -0
- Cargo.lock +609 -0
- Cargo.toml +25 -0
- README.md +114 -0
- config/kur.example.toml +36 -0
- deploy/kur.service +30 -0
- deploy/kur.timer +13 -0
- src/config.rs +237 -0
- src/forge.rs +146 -0
- src/install.rs +266 -0
- src/main.rs +125 -0
- src/migrate.rs +127 -0
.forge/ci.tomladded+42 -0
| @@ -0,0 +1,42 @@ | |||
| 1 | +# CI for kur. Format: forge's docs/ci.md. | ||
| 2 | +# | ||
| 3 | +# The workflow has no branch condition, so the job also runs for pull requests. | ||
| 4 | +# One job does everything, so its steps run one at a time. A tag push matching "v*" publishes a | ||
| 5 | +# release with the binary and SHA256SUMS, only when the job succeeded. | ||
| 6 | + | ||
| 7 | +name = "build" | ||
| 8 | + | ||
| 9 | +[on] | ||
| 10 | +push = ["main"] | ||
| 11 | +pull_request = true | ||
| 12 | +manual = true | ||
| 13 | +tags = ["v*"] | ||
| 14 | + | ||
| 15 | +[jobs.build] | ||
| 16 | +image = "docker.io/library/rust:1" | ||
| 17 | +# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo. | ||
| 18 | +# CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones. | ||
| 19 | +env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home" } | ||
| 20 | +# Tests run first, so a failure shows before the slow LTO release build. | ||
| 21 | +# The groups are the job's steps on the run page, and `exec 2>&1` keeps a marker in order with cargo's | ||
| 22 | +# stderr, which the runner reads from a separate pipe. | ||
| 23 | +run = """ | ||
| 24 | +exec 2>&1 | ||
| 25 | +echo "::group::Tests" | ||
| 26 | +cargo test | ||
| 27 | +echo "::endgroup::" | ||
| 28 | +echo "::group::Release build" | ||
| 29 | +cargo build --release | ||
| 30 | +echo "::endgroup::" | ||
| 31 | +echo "::group::Package" | ||
| 32 | +ARCH=$(uname -m) | ||
| 33 | +cp target/release/kur kur-$ARCH-linux | ||
| 34 | +sha256sum kur-$ARCH-linux > SHA256SUMS | ||
| 35 | +echo "::endgroup::" | ||
| 36 | +""" | ||
| 37 | +artifacts = ["kur-*-linux", "SHA256SUMS"] | ||
| 38 | +cache = ["target", ".cargo-home"] | ||
| 39 | +timeout_minutes = 60 | ||
| 40 | + | ||
| 41 | +[release] | ||
| 42 | +assets = ["build:kur-*-linux", "build:SHA256SUMS"] | ||
.gitignoreadded+1 -0
| @@ -0,0 +1 @@ | |||
| 1 | +target/ | ||
Cargo.lockadded+609 -0
| @@ -0,0 +1,609 @@ | |||
| 1 | +# This file is automatically @generated by Cargo. | ||
| 2 | +# It is not intended for manual editing. | ||
| 3 | +version = 4 | ||
| 4 | + | ||
| 5 | +[[package]] | ||
| 6 | +name = "adler2" | ||
| 7 | +version = "2.0.1" | ||
| 8 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 9 | +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | ||
| 10 | + | ||
| 11 | +[[package]] | ||
| 12 | +name = "base64" | ||
| 13 | +version = "0.23.1" | ||
| 14 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 15 | +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" | ||
| 16 | + | ||
| 17 | +[[package]] | ||
| 18 | +name = "block-buffer" | ||
| 19 | +version = "0.12.1" | ||
| 20 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 21 | +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" | ||
| 22 | +dependencies = [ | ||
| 23 | + "hybrid-array", | ||
| 24 | +] | ||
| 25 | + | ||
| 26 | +[[package]] | ||
| 27 | +name = "bytes" | ||
| 28 | +version = "1.12.1" | ||
| 29 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 30 | +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" | ||
| 31 | + | ||
| 32 | +[[package]] | ||
| 33 | +name = "cc" | ||
| 34 | +version = "1.11.0" | ||
| 35 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 36 | +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" | ||
| 37 | +dependencies = [ | ||
| 38 | + "find-msvc-tools", | ||
| 39 | + "shlex", | ||
| 40 | +] | ||
| 41 | + | ||
| 42 | +[[package]] | ||
| 43 | +name = "cfg-if" | ||
| 44 | +version = "1.0.5" | ||
| 45 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 46 | +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" | ||
| 47 | + | ||
| 48 | +[[package]] | ||
| 49 | +name = "const-oid" | ||
| 50 | +version = "0.10.2" | ||
| 51 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 52 | +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" | ||
| 53 | + | ||
| 54 | +[[package]] | ||
| 55 | +name = "cpufeatures" | ||
| 56 | +version = "0.3.1" | ||
| 57 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 58 | +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" | ||
| 59 | +dependencies = [ | ||
| 60 | + "libc", | ||
| 61 | +] | ||
| 62 | + | ||
| 63 | +[[package]] | ||
| 64 | +name = "crc32fast" | ||
| 65 | +version = "1.5.4" | ||
| 66 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 67 | +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" | ||
| 68 | +dependencies = [ | ||
| 69 | + "cfg-if", | ||
| 70 | +] | ||
| 71 | + | ||
| 72 | +[[package]] | ||
| 73 | +name = "crypto-common" | ||
| 74 | +version = "0.2.2" | ||
| 75 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 76 | +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" | ||
| 77 | +dependencies = [ | ||
| 78 | + "hybrid-array", | ||
| 79 | +] | ||
| 80 | + | ||
| 81 | +[[package]] | ||
| 82 | +name = "digest" | ||
| 83 | +version = "0.11.3" | ||
| 84 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 85 | +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" | ||
| 86 | +dependencies = [ | ||
| 87 | + "block-buffer", | ||
| 88 | + "const-oid", | ||
| 89 | + "crypto-common", | ||
| 90 | +] | ||
| 91 | + | ||
| 92 | +[[package]] | ||
| 93 | +name = "equivalent" | ||
| 94 | +version = "1.0.3" | ||
| 95 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 96 | +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" | ||
| 97 | + | ||
| 98 | +[[package]] | ||
| 99 | +name = "find-msvc-tools" | ||
| 100 | +version = "0.1.15" | ||
| 101 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 102 | +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" | ||
| 103 | + | ||
| 104 | +[[package]] | ||
| 105 | +name = "flate2" | ||
| 106 | +version = "1.1.10" | ||
| 107 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 108 | +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" | ||
| 109 | +dependencies = [ | ||
| 110 | + "crc32fast", | ||
| 111 | + "miniz_oxide", | ||
| 112 | + "zlib-rs", | ||
| 113 | +] | ||
| 114 | + | ||
| 115 | +[[package]] | ||
| 116 | +name = "getrandom" | ||
| 117 | +version = "0.2.17" | ||
| 118 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 119 | +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" | ||
| 120 | +dependencies = [ | ||
| 121 | + "cfg-if", | ||
| 122 | + "libc", | ||
| 123 | + "wasi", | ||
| 124 | +] | ||
| 125 | + | ||
| 126 | +[[package]] | ||
| 127 | +name = "hashbrown" | ||
| 128 | +version = "0.17.1" | ||
| 129 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 130 | +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" | ||
| 131 | + | ||
| 132 | +[[package]] | ||
| 133 | +name = "hex" | ||
| 134 | +version = "0.4.3" | ||
| 135 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 136 | +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" | ||
| 137 | + | ||
| 138 | +[[package]] | ||
| 139 | +name = "http" | ||
| 140 | +version = "1.5.0" | ||
| 141 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 142 | +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" | ||
| 143 | +dependencies = [ | ||
| 144 | + "bytes", | ||
| 145 | + "itoa", | ||
| 146 | +] | ||
| 147 | + | ||
| 148 | +[[package]] | ||
| 149 | +name = "httparse" | ||
| 150 | +version = "1.10.1" | ||
| 151 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 152 | +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" | ||
| 153 | + | ||
| 154 | +[[package]] | ||
| 155 | +name = "hybrid-array" | ||
| 156 | +version = "0.4.15" | ||
| 157 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 158 | +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" | ||
| 159 | +dependencies = [ | ||
| 160 | + "typenum", | ||
| 161 | +] | ||
| 162 | + | ||
| 163 | +[[package]] | ||
| 164 | +name = "indexmap" | ||
| 165 | +version = "2.14.2" | ||
| 166 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 167 | +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" | ||
| 168 | +dependencies = [ | ||
| 169 | + "equivalent", | ||
| 170 | + "hashbrown", | ||
| 171 | +] | ||
| 172 | + | ||
| 173 | +[[package]] | ||
| 174 | +name = "itoa" | ||
| 175 | +version = "1.0.18" | ||
| 176 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 177 | +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" | ||
| 178 | + | ||
| 179 | +[[package]] | ||
| 180 | +name = "kur" | ||
| 181 | +version = "0.1.0" | ||
| 182 | +dependencies = [ | ||
| 183 | + "hex", | ||
| 184 | + "serde", | ||
| 185 | + "serde_json", | ||
| 186 | + "sha2", | ||
| 187 | + "toml", | ||
| 188 | + "toml_edit", | ||
| 189 | + "ureq", | ||
| 190 | +] | ||
| 191 | + | ||
| 192 | +[[package]] | ||
| 193 | +name = "libc" | ||
| 194 | +version = "0.2.191" | ||
| 195 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 196 | +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | ||
| 197 | + | ||
| 198 | +[[package]] | ||
| 199 | +name = "log" | ||
| 200 | +version = "0.4.35" | ||
| 201 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 202 | +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" | ||
| 203 | + | ||
| 204 | +[[package]] | ||
| 205 | +name = "memchr" | ||
| 206 | +version = "2.8.3" | ||
| 207 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 208 | +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" | ||
| 209 | + | ||
| 210 | +[[package]] | ||
| 211 | +name = "miniz_oxide" | ||
| 212 | +version = "0.9.1" | ||
| 213 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 214 | +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" | ||
| 215 | +dependencies = [ | ||
| 216 | + "adler2", | ||
| 217 | + "simd-adler32", | ||
| 218 | +] | ||
| 219 | + | ||
| 220 | +[[package]] | ||
| 221 | +name = "once_cell" | ||
| 222 | +version = "1.21.4" | ||
| 223 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 224 | +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" | ||
| 225 | + | ||
| 226 | +[[package]] | ||
| 227 | +name = "percent-encoding" | ||
| 228 | +version = "2.3.2" | ||
| 229 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 230 | +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" | ||
| 231 | + | ||
| 232 | +[[package]] | ||
| 233 | +name = "proc-macro2" | ||
| 234 | +version = "1.0.107" | ||
| 235 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 236 | +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" | ||
| 237 | +dependencies = [ | ||
| 238 | + "unicode-ident", | ||
| 239 | +] | ||
| 240 | + | ||
| 241 | +[[package]] | ||
| 242 | +name = "quote" | ||
| 243 | +version = "1.0.47" | ||
| 244 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 245 | +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" | ||
| 246 | +dependencies = [ | ||
| 247 | + "proc-macro2", | ||
| 248 | +] | ||
| 249 | + | ||
| 250 | +[[package]] | ||
| 251 | +name = "ring" | ||
| 252 | +version = "0.17.14" | ||
| 253 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 254 | +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" | ||
| 255 | +dependencies = [ | ||
| 256 | + "cc", | ||
| 257 | + "cfg-if", | ||
| 258 | + "getrandom", | ||
| 259 | + "libc", | ||
| 260 | + "untrusted", | ||
| 261 | + "windows-sys", | ||
| 262 | +] | ||
| 263 | + | ||
| 264 | +[[package]] | ||
| 265 | +name = "rustls" | ||
| 266 | +version = "0.23.46" | ||
| 267 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 268 | +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" | ||
| 269 | +dependencies = [ | ||
| 270 | + "log", | ||
| 271 | + "once_cell", | ||
| 272 | + "ring", | ||
| 273 | + "rustls-pki-types", | ||
| 274 | + "rustls-webpki", | ||
| 275 | + "subtle", | ||
| 276 | + "zeroize", | ||
| 277 | +] | ||
| 278 | + | ||
| 279 | +[[package]] | ||
| 280 | +name = "rustls-pki-types" | ||
| 281 | +version = "1.15.1" | ||
| 282 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 283 | +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" | ||
| 284 | +dependencies = [ | ||
| 285 | + "zeroize", | ||
| 286 | +] | ||
| 287 | + | ||
| 288 | +[[package]] | ||
| 289 | +name = "rustls-webpki" | ||
| 290 | +version = "0.103.16" | ||
| 291 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 292 | +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" | ||
| 293 | +dependencies = [ | ||
| 294 | + "ring", | ||
| 295 | + "rustls-pki-types", | ||
| 296 | + "untrusted", | ||
| 297 | +] | ||
| 298 | + | ||
| 299 | +[[package]] | ||
| 300 | +name = "serde" | ||
| 301 | +version = "1.0.229" | ||
| 302 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 303 | +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" | ||
| 304 | +dependencies = [ | ||
| 305 | + "serde_core", | ||
| 306 | + "serde_derive", | ||
| 307 | +] | ||
| 308 | + | ||
| 309 | +[[package]] | ||
| 310 | +name = "serde_core" | ||
| 311 | +version = "1.0.229" | ||
| 312 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 313 | +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" | ||
| 314 | +dependencies = [ | ||
| 315 | + "serde_derive", | ||
| 316 | +] | ||
| 317 | + | ||
| 318 | +[[package]] | ||
| 319 | +name = "serde_derive" | ||
| 320 | +version = "1.0.229" | ||
| 321 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 322 | +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" | ||
| 323 | +dependencies = [ | ||
| 324 | + "proc-macro2", | ||
| 325 | + "quote", | ||
| 326 | + "syn", | ||
| 327 | +] | ||
| 328 | + | ||
| 329 | +[[package]] | ||
| 330 | +name = "serde_json" | ||
| 331 | +version = "1.0.154" | ||
| 332 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 333 | +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" | ||
| 334 | +dependencies = [ | ||
| 335 | + "itoa", | ||
| 336 | + "memchr", | ||
| 337 | + "serde", | ||
| 338 | + "serde_core", | ||
| 339 | + "zmij", | ||
| 340 | +] | ||
| 341 | + | ||
| 342 | +[[package]] | ||
| 343 | +name = "serde_spanned" | ||
| 344 | +version = "1.1.2" | ||
| 345 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 346 | +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" | ||
| 347 | +dependencies = [ | ||
| 348 | + "serde_core", | ||
| 349 | +] | ||
| 350 | + | ||
| 351 | +[[package]] | ||
| 352 | +name = "sha2" | ||
| 353 | +version = "0.11.1" | ||
| 354 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 355 | +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" | ||
| 356 | +dependencies = [ | ||
| 357 | + "cfg-if", | ||
| 358 | + "cpufeatures", | ||
| 359 | + "digest", | ||
| 360 | +] | ||
| 361 | + | ||
| 362 | +[[package]] | ||
| 363 | +name = "shlex" | ||
| 364 | +version = "2.0.1" | ||
| 365 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 366 | +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" | ||
| 367 | + | ||
| 368 | +[[package]] | ||
| 369 | +name = "simd-adler32" | ||
| 370 | +version = "0.3.10" | ||
| 371 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 372 | +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | ||
| 373 | + | ||
| 374 | +[[package]] | ||
| 375 | +name = "subtle" | ||
| 376 | +version = "2.6.1" | ||
| 377 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 378 | +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" | ||
| 379 | + | ||
| 380 | +[[package]] | ||
| 381 | +name = "syn" | ||
| 382 | +version = "3.0.9" | ||
| 383 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 384 | +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" | ||
| 385 | +dependencies = [ | ||
| 386 | + "proc-macro2", | ||
| 387 | + "quote", | ||
| 388 | + "unicode-ident", | ||
| 389 | +] | ||
| 390 | + | ||
| 391 | +[[package]] | ||
| 392 | +name = "toml" | ||
| 393 | +version = "1.2.0+spec-1.1.0" | ||
| 394 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 395 | +checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" | ||
| 396 | +dependencies = [ | ||
| 397 | + "indexmap", | ||
| 398 | + "serde_core", | ||
| 399 | + "serde_spanned", | ||
| 400 | + "toml_datetime", | ||
| 401 | + "toml_parser", | ||
| 402 | + "toml_writer", | ||
| 403 | + "winnow", | ||
| 404 | +] | ||
| 405 | + | ||
| 406 | +[[package]] | ||
| 407 | +name = "toml_datetime" | ||
| 408 | +version = "1.1.2+spec-1.1.0" | ||
| 409 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 410 | +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" | ||
| 411 | +dependencies = [ | ||
| 412 | + "serde_core", | ||
| 413 | +] | ||
| 414 | + | ||
| 415 | +[[package]] | ||
| 416 | +name = "toml_edit" | ||
| 417 | +version = "0.25.18+spec-1.1.0" | ||
| 418 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 419 | +checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" | ||
| 420 | +dependencies = [ | ||
| 421 | + "indexmap", | ||
| 422 | + "toml_datetime", | ||
| 423 | + "toml_parser", | ||
| 424 | + "toml_writer", | ||
| 425 | + "winnow", | ||
| 426 | +] | ||
| 427 | + | ||
| 428 | +[[package]] | ||
| 429 | +name = "toml_parser" | ||
| 430 | +version = "1.1.5+spec-1.1.0" | ||
| 431 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 432 | +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" | ||
| 433 | +dependencies = [ | ||
| 434 | + "winnow", | ||
| 435 | +] | ||
| 436 | + | ||
| 437 | +[[package]] | ||
| 438 | +name = "toml_writer" | ||
| 439 | +version = "1.2.0+spec-1.1.0" | ||
| 440 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 441 | +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" | ||
| 442 | + | ||
| 443 | +[[package]] | ||
| 444 | +name = "typenum" | ||
| 445 | +version = "1.20.1" | ||
| 446 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 447 | +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" | ||
| 448 | + | ||
| 449 | +[[package]] | ||
| 450 | +name = "unicode-ident" | ||
| 451 | +version = "1.0.27" | ||
| 452 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 453 | +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" | ||
| 454 | + | ||
| 455 | +[[package]] | ||
| 456 | +name = "untrusted" | ||
| 457 | +version = "0.9.0" | ||
| 458 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 459 | +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" | ||
| 460 | + | ||
| 461 | +[[package]] | ||
| 462 | +name = "ureq" | ||
| 463 | +version = "3.5.1" | ||
| 464 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 465 | +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" | ||
| 466 | +dependencies = [ | ||
| 467 | + "base64", | ||
| 468 | + "flate2", | ||
| 469 | + "log", | ||
| 470 | + "percent-encoding", | ||
| 471 | + "rustls", | ||
| 472 | + "rustls-pki-types", | ||
| 473 | + "ureq-proto", | ||
| 474 | + "utf8-zero", | ||
| 475 | + "webpki-roots", | ||
| 476 | +] | ||
| 477 | + | ||
| 478 | +[[package]] | ||
| 479 | +name = "ureq-proto" | ||
| 480 | +version = "0.7.1" | ||
| 481 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 482 | +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" | ||
| 483 | +dependencies = [ | ||
| 484 | + "base64", | ||
| 485 | + "http", | ||
| 486 | + "httparse", | ||
| 487 | + "log", | ||
| 488 | +] | ||
| 489 | + | ||
| 490 | +[[package]] | ||
| 491 | +name = "utf8-zero" | ||
| 492 | +version = "0.8.1" | ||
| 493 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 494 | +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" | ||
| 495 | + | ||
| 496 | +[[package]] | ||
| 497 | +name = "wasi" | ||
| 498 | +version = "0.11.1+wasi-snapshot-preview1" | ||
| 499 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 500 | +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" | ||
| 501 | + | ||
| 502 | +[[package]] | ||
| 503 | +name = "webpki-roots" | ||
| 504 | +version = "1.0.11" | ||
| 505 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 506 | +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" | ||
| 507 | +dependencies = [ | ||
| 508 | + "rustls-pki-types", | ||
| 509 | +] | ||
| 510 | + | ||
| 511 | +[[package]] | ||
| 512 | +name = "windows-sys" | ||
| 513 | +version = "0.52.0" | ||
| 514 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 515 | +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" | ||
| 516 | +dependencies = [ | ||
| 517 | + "windows-targets", | ||
| 518 | +] | ||
| 519 | + | ||
| 520 | +[[package]] | ||
| 521 | +name = "windows-targets" | ||
| 522 | +version = "0.52.6" | ||
| 523 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 524 | +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" | ||
| 525 | +dependencies = [ | ||
| 526 | + "windows_aarch64_gnullvm", | ||
| 527 | + "windows_aarch64_msvc", | ||
| 528 | + "windows_i686_gnu", | ||
| 529 | + "windows_i686_gnullvm", | ||
| 530 | + "windows_i686_msvc", | ||
| 531 | + "windows_x86_64_gnu", | ||
| 532 | + "windows_x86_64_gnullvm", | ||
| 533 | + "windows_x86_64_msvc", | ||
| 534 | +] | ||
| 535 | + | ||
| 536 | +[[package]] | ||
| 537 | +name = "windows_aarch64_gnullvm" | ||
| 538 | +version = "0.52.6" | ||
| 539 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 540 | +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" | ||
| 541 | + | ||
| 542 | +[[package]] | ||
| 543 | +name = "windows_aarch64_msvc" | ||
| 544 | +version = "0.52.6" | ||
| 545 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 546 | +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" | ||
| 547 | + | ||
| 548 | +[[package]] | ||
| 549 | +name = "windows_i686_gnu" | ||
| 550 | +version = "0.52.6" | ||
| 551 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 552 | +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" | ||
| 553 | + | ||
| 554 | +[[package]] | ||
| 555 | +name = "windows_i686_gnullvm" | ||
| 556 | +version = "0.52.6" | ||
| 557 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 558 | +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" | ||
| 559 | + | ||
| 560 | +[[package]] | ||
| 561 | +name = "windows_i686_msvc" | ||
| 562 | +version = "0.52.6" | ||
| 563 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 564 | +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" | ||
| 565 | + | ||
| 566 | +[[package]] | ||
| 567 | +name = "windows_x86_64_gnu" | ||
| 568 | +version = "0.52.6" | ||
| 569 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 570 | +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" | ||
| 571 | + | ||
| 572 | +[[package]] | ||
| 573 | +name = "windows_x86_64_gnullvm" | ||
| 574 | +version = "0.52.6" | ||
| 575 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 576 | +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" | ||
| 577 | + | ||
| 578 | +[[package]] | ||
| 579 | +name = "windows_x86_64_msvc" | ||
| 580 | +version = "0.52.6" | ||
| 581 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 582 | +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" | ||
| 583 | + | ||
| 584 | +[[package]] | ||
| 585 | +name = "winnow" | ||
| 586 | +version = "1.0.4" | ||
| 587 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 588 | +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" | ||
| 589 | +dependencies = [ | ||
| 590 | + "memchr", | ||
| 591 | +] | ||
| 592 | + | ||
| 593 | +[[package]] | ||
| 594 | +name = "zeroize" | ||
| 595 | +version = "1.9.1" | ||
| 596 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 597 | +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" | ||
| 598 | + | ||
| 599 | +[[package]] | ||
| 600 | +name = "zlib-rs" | ||
| 601 | +version = "0.6.8" | ||
| 602 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 603 | +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" | ||
| 604 | + | ||
| 605 | +[[package]] | ||
| 606 | +name = "zmij" | ||
| 607 | +version = "1.0.23" | ||
| 608 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 609 | +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" | ||
Cargo.tomladded+25 -0
| @@ -0,0 +1,25 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "kur" | ||
| 3 | +version = "0.1.0" | ||
| 4 | +edition = "2024" | ||
| 5 | +license = "AGPL-3.0-or-later" | ||
| 6 | +description = "Installs the newest forge release of each app on a server, with rollback" | ||
| 7 | + | ||
| 8 | +[dependencies] | ||
| 9 | +hex = "0.4.3" | ||
| 10 | +serde = { version = "1.0.229", features = ["derive"] } | ||
| 11 | +serde_json = "1.0.154" | ||
| 12 | +sha2 = "0.11.1" | ||
| 13 | +toml = "1.2.0" | ||
| 14 | +toml_edit = "0.25.18" | ||
| 15 | +ureq = "3.5.1" | ||
| 16 | + | ||
| 17 | +[lints.rust] | ||
| 18 | +unsafe_code = "forbid" | ||
| 19 | + | ||
| 20 | +[profile.dev] | ||
| 21 | +debug = "line-tables-only" | ||
| 22 | + | ||
| 23 | +[profile.release] | ||
| 24 | +lto = true | ||
| 25 | +codegen-units = 1 | ||
README.mdadded+114 -0
| @@ -0,0 +1,114 @@ | |||
| 1 | +# kur | ||
| 2 | + | ||
| 3 | +kur ("install" in Turkish) installs the newest release of each configured app on a server. It runs | ||
| 4 | +from a systemd timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary | ||
| 5 | +in only when the release asset differs from the installed file. After a swap it restarts the app's | ||
| 6 | +systemd unit and health-checks it, and it rolls back to the previous binary if the check fails. It is | ||
| 7 | +one binary that runs as root and has no daemon. | ||
| 8 | + | ||
| 9 | +## Releases | ||
| 10 | + | ||
| 11 | +For each app, kur lists the repo's releases (newest first) and takes the first one that is not a draft | ||
| 12 | +and is not a prerelease. Set `prerelease = true` on an app to also accept prereleases. Within the chosen | ||
| 13 | +release it looks up the asset named by `asset` (with `{arch}` filled in). The forge reports each asset's | ||
| 14 | +sha256; kur verifies the download against that value and refuses a mismatch. | ||
| 15 | + | ||
| 16 | +## Run flow | ||
| 17 | + | ||
| 18 | +For each app, in order: | ||
| 19 | + | ||
| 20 | +1. Fetch the release and asset. | ||
| 21 | +2. Compare the sha256 of the installed binary with the asset's. If equal, report `up to date`. | ||
| 22 | +3. If the asset's sha256 is listed in `{state_dir}/{name}.bad`, report it as skipped. | ||
| 23 | +4. Download to `{path}.kur-new`, hashing while writing. Mode 0755, fsync. | ||
| 24 | +5. If `check` is set, run the new file with those arguments (10 s limit). Failure marks the build bad. | ||
| 25 | +6. Rename the installed binary to `{path}.prev` and the new file to `{path}`. | ||
| 26 | +7. If `unit` is set, restart it and wait until `systemctl is-active` succeeds, `health_url` returns 2xx, | ||
| 27 | + and the unit is still active 5 s later. Times out after `health_timeout_secs`. | ||
| 28 | +8. On health failure, the build's sha256 is appended to `{name}.bad`. If `{path}.prev` exists, it is | ||
| 29 | + renamed back to `{path}` and the unit is restarted. Otherwise the run reports that there was no | ||
| 30 | + previous binary to restore. | ||
| 31 | + | ||
| 32 | +A run holds a lock on `{state_dir}/lock`, so a manual `kur run` exits at once while the timer's run is | ||
| 33 | +in progress. `kur status` takes no lock. One app failing does not stop the others. Output goes to stdout and errors to stderr, which journald | ||
| 34 | +collects. | ||
| 35 | + | ||
| 36 | +### The bad list | ||
| 37 | + | ||
| 38 | +`{state_dir}/{name}.bad` holds one sha256 per line. kur skips any release whose asset hash is in the | ||
| 39 | +file. To retry a build, delete its line, or delete the file to clear the list for that app. | ||
| 40 | + | ||
| 41 | +## Install | ||
| 42 | + | ||
| 43 | +Run as root on the app server. | ||
| 44 | + | ||
| 45 | +```sh | ||
| 46 | +install -m 0755 kur /usr/local/bin/kur | ||
| 47 | +install -d -m 0755 /etc/kur | ||
| 48 | +install -m 0600 config/kur.example.toml /etc/kur/kur.toml # then edit it | ||
| 49 | +# Optional, for private repos. Use a read-only token. | ||
| 50 | +(umask 077; printf '%s\n' 'TOKEN' > /etc/kur/token) | ||
| 51 | +install -m 0644 deploy/kur.service deploy/kur.timer /etc/systemd/system/ | ||
| 52 | +systemctl daemon-reload | ||
| 53 | +systemctl enable --now kur.timer | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +The app units (for example `im.service`) are not part of this repo. They must exist before kur runs | ||
| 57 | +for that app. If `token_file` is set in the config, the token file must be mode 0600. | ||
| 58 | + | ||
| 59 | +## Commands | ||
| 60 | + | ||
| 61 | +``` | ||
| 62 | +kur run process every app once | ||
| 63 | +kur run <name> process one app | ||
| 64 | +kur status show installed and newest versions; changes nothing | ||
| 65 | +kur --version print "kur <version>" | ||
| 66 | +kur help print usage (also used for unknown commands, exit 2) | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +Global option: `--config <path>`, placed before the command. Otherwise `KUR_CONFIG` is used, then | ||
| 70 | +`/etc/kur/kur.toml`. | ||
| 71 | + | ||
| 72 | +Exit code is 0 when every app succeeded or was up to date, and 1 if any app failed. | ||
| 73 | + | ||
| 74 | +## Config reference | ||
| 75 | + | ||
| 76 | +Top level: | ||
| 77 | + | ||
| 78 | +| Key | Required | Default | Meaning | | ||
| 79 | +|---|---|---|---| | ||
| 80 | +| `forge` | yes | none | Forge base URL, `https://` or `http://`. Trailing slash is trimmed. | | ||
| 81 | +| `token_file` | no | none | File with a forge token for private repos. Read once, trimmed. Unreadable file is a config error. | | ||
| 82 | +| `state_dir` | no | `/var/lib/kur` | Directory for `.bad` and `.tag` files and the run lock. Created with mode 0700 if missing. | | ||
| 83 | + | ||
| 84 | +Each `[[app]]` table: | ||
| 85 | + | ||
| 86 | +| Key | Required | Default | Meaning | | ||
| 87 | +|---|---|---|---| | ||
| 88 | +| `name` | yes | none | Unique. Must match `^[a-z0-9][a-z0-9_-]{0,39}$`. | | ||
| 89 | +| `repo` | yes | none | Forge repo as `owner/name`. | | ||
| 90 | +| `asset` | yes | none | Asset file name. `{arch}` is replaced by the machine architecture. | | ||
| 91 | +| `path` | yes | none | Absolute path of the installed binary. | | ||
| 92 | +| `unit` | no | none | systemd unit to restart and health-check. Without it kur only swaps the file. | | ||
| 93 | +| `prerelease` | no | `false` | Also accept prerelease releases. | | ||
| 94 | +| `check` | no | none | Arguments for the new binary, run before the swap. Must exit 0 within 10 s. | | ||
| 95 | +| `health_url` | no | none | URL that must return 2xx after restart. No token is sent. | | ||
| 96 | +| `health_timeout_secs` | no | `30` | Time allowed for the health check to pass. | | ||
| 97 | + | ||
| 98 | +Unknown keys are reported as a warning on every run and in `kur status`, and ignored, so a config written for a newer kur still works with an older one. A misspelled optional key is therefore ignored, so check the warnings after editing. A config error exits 1 before anything is changed. | ||
| 99 | + | ||
| 100 | +See `config/kur.example.toml` for a working example. | ||
| 101 | + | ||
| 102 | +## Config changes between versions | ||
| 103 | + | ||
| 104 | +Unknown keys are warnings, as above. When a release renames a key, the old name keeps working. `kur run` | ||
| 105 | +then rewrites the config file to the new names and keeps its comments and layout. The original is saved | ||
| 106 | +next to it as `<config>.bak`. `kur status` reports the renames but writes nothing. If the rewrite fails, | ||
| 107 | +kur warns and runs with the renamed config in memory. | ||
| 108 | + | ||
| 109 | +## Publishing an app | ||
| 110 | + | ||
| 111 | +kur needs each app's repo to publish its binary as a forge release. The app repo needs a forge CI | ||
| 112 | +config with a `[release]` section that publishes `<app>-<arch>-linux` (for example `im-x86_64-linux`) | ||
| 113 | +on `v*` tags, so the release has an asset that kur can match. See `.forge/ci.toml` in this repo for | ||
| 114 | +an example. | ||
config/kur.example.tomladded+36 -0
| @@ -0,0 +1,36 @@ | |||
| 1 | +# Example kur config. Install it as /etc/kur/kur.toml (mode 0600). | ||
| 2 | +# Field reference: README.md. | ||
| 3 | + | ||
| 4 | +# Forge base URL. A trailing slash is fine. | ||
| 5 | +forge = "https://git.tahinli.com" | ||
| 6 | + | ||
| 7 | +# Optional: file holding a forge token for private repos. Read once at start, trimmed. | ||
| 8 | +# Use a read-only token. Must be mode 0600. | ||
| 9 | +# token_file = "/etc/kur/token" | ||
| 10 | + | ||
| 11 | +# Optional: where kur keeps .bad and .tag files. Default shown. | ||
| 12 | +# state_dir = "/var/lib/kur" | ||
| 13 | + | ||
| 14 | +# The im server. Its unit is im.service, which kur restarts after a swap. | ||
| 15 | +[[app]] | ||
| 16 | +name = "im" | ||
| 17 | +repo = "Tahinli/im" | ||
| 18 | +# {arch} is replaced by the machine architecture (x86_64, aarch64). | ||
| 19 | +asset = "im-{arch}-linux" | ||
| 20 | +path = "/usr/local/bin/im" | ||
| 21 | +unit = "im.service" | ||
| 22 | +# im has no --version flag, so there is no pre-swap check. | ||
| 23 | +# health_url must match the listen address in im's config. | ||
| 24 | +health_url = "http://127.0.0.1:7650/healthz" | ||
| 25 | +# health_timeout_secs = 30 | ||
| 26 | +# prerelease = false | ||
| 27 | + | ||
| 28 | +# kur updates itself. There is no unit: the new binary is swapped in and | ||
| 29 | +# used from the next timer run on. kur runs `kur --version` on the new build | ||
| 30 | +# before swapping it in, so a broken build is never installed. | ||
| 31 | +[[app]] | ||
| 32 | +name = "kur" | ||
| 33 | +repo = "Tahinli/kur" | ||
| 34 | +asset = "kur-{arch}-linux" | ||
| 35 | +path = "/usr/local/bin/kur" | ||
| 36 | +check = ["--version"] | ||
deploy/kur.serviceadded+30 -0
| @@ -0,0 +1,30 @@ | |||
| 1 | +[Unit] | ||
| 2 | +Description=kur: install newest forge releases of configured apps | ||
| 3 | +Wants=network-online.target | ||
| 4 | +After=network-online.target | ||
| 5 | + | ||
| 6 | +[Service] | ||
| 7 | +Type=oneshot | ||
| 8 | +# Runs as root: it replaces binaries in /usr/local/bin and restarts units. | ||
| 9 | +ExecStart=/usr/local/bin/kur run | ||
| 10 | +Environment=KUR_CONFIG=/etc/kur/kur.toml | ||
| 11 | +# /var/lib/kur, mode 0700 (.bad, .tag files). | ||
| 12 | +StateDirectory=kur | ||
| 13 | +StateDirectoryMode=0700 | ||
| 14 | +# Installed binaries must be 0755. kur sets the mode itself, but keep the umask | ||
| 15 | +# from making anything more private than that. | ||
| 16 | +UMask=0022 | ||
| 17 | + | ||
| 18 | +# Light hardening only. ProtectSystem= is deliberately left unset: "strict" and | ||
| 19 | +# "full" make /usr read-only, and /usr/local/bin is under /usr, so kur could not | ||
| 20 | +# replace app binaries. PrivateTmp, ProtectHome and the rest do not touch | ||
| 21 | +# /usr/local/bin or systemctl. | ||
| 22 | +NoNewPrivileges=yes | ||
| 23 | +PrivateTmp=yes | ||
| 24 | +ProtectHome=yes | ||
| 25 | +ProtectKernelTunables=yes | ||
| 26 | +ProtectKernelModules=yes | ||
| 27 | +ProtectKernelLogs=yes | ||
| 28 | +ProtectControlGroups=yes | ||
| 29 | +RestrictSUIDSGID=yes | ||
| 30 | +LockPersonality=yes | ||
deploy/kur.timeradded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +[Unit] | ||
| 2 | +Description=Run kur every 5 minutes | ||
| 3 | + | ||
| 4 | +[Timer] | ||
| 5 | +# First run 2 minutes after boot, then 5 minutes after each run starts. | ||
| 6 | +OnBootSec=2min | ||
| 7 | +OnUnitActiveSec=5min | ||
| 8 | +RandomizedDelaySec=30s | ||
| 9 | +# Do not catch up on missed runs after downtime. | ||
| 10 | +Persistent=false | ||
| 11 | + | ||
| 12 | +[Install] | ||
| 13 | +WantedBy=timers.target | ||
src/config.rsadded+237 -0
| @@ -0,0 +1,237 @@ | |||
| 1 | +//! Config file: TOML parsing, validation, and reading the forge token. | ||
| 2 | + | ||
| 3 | +use crate::{Res, migrate}; | ||
| 4 | +use serde::Deserialize; | ||
| 5 | +use std::collections::HashSet; | ||
| 6 | +use std::fs::{self, OpenOptions}; | ||
| 7 | +use std::io::{self, Write}; | ||
| 8 | +use std::os::unix::fs::OpenOptionsExt; | ||
| 9 | +use std::path::{Path, PathBuf}; | ||
| 10 | + | ||
| 11 | +/// Config path used when neither `--config` nor `KUR_CONFIG` is given. | ||
| 12 | +pub const DEFAULT_PATH: &str = "/etc/kur/kur.toml"; | ||
| 13 | +const DEFAULT_STATE_DIR: &str = "/var/lib/kur"; | ||
| 14 | +/// Top-level keys; must match the `Raw` fields. | ||
| 15 | +const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; | ||
| 16 | +/// Keys in each `[[app]]` table; must match the `App` fields. | ||
| 17 | +const KNOWN_APP_KEYS: &[&str] = &[ | ||
| 18 | + "name", | ||
| 19 | + "repo", | ||
| 20 | + "asset", | ||
| 21 | + "path", | ||
| 22 | + "unit", | ||
| 23 | + "prerelease", | ||
| 24 | + "check", | ||
| 25 | + "health_url", | ||
| 26 | + "health_timeout_secs", | ||
| 27 | +]; | ||
| 28 | + | ||
| 29 | +/// Raw TOML shape; `apps` comes from the `[[app]]` tables. | ||
| 30 | +#[derive(Deserialize)] | ||
| 31 | +struct Raw { | ||
| 32 | + forge: String, | ||
| 33 | + token_file: Option<PathBuf>, | ||
| 34 | + state_dir: Option<PathBuf>, | ||
| 35 | + #[serde(default, rename = "app")] | ||
| 36 | + apps: Vec<App>, | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// One `[[app]]` table. | ||
| 40 | +#[derive(Deserialize)] | ||
| 41 | +pub struct App { | ||
| 42 | + pub name: String, | ||
| 43 | + pub repo: String, | ||
| 44 | + pub asset: String, | ||
| 45 | + pub path: PathBuf, | ||
| 46 | + pub unit: Option<String>, | ||
| 47 | + #[serde(default)] | ||
| 48 | + pub prerelease: bool, | ||
| 49 | + pub check: Option<Vec<String>>, | ||
| 50 | + pub health_url: Option<String>, | ||
| 51 | + #[serde(default = "default_health_timeout")] | ||
| 52 | + pub health_timeout_secs: u64, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +fn default_health_timeout() -> u64 { | ||
| 56 | + 30 | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// Validated configuration. | ||
| 60 | +pub struct Config { | ||
| 61 | + /// Forge base URL without a trailing slash. | ||
| 62 | + pub forge: String, | ||
| 63 | + /// Forge token, trimmed; sent only to forge URLs. | ||
| 64 | + pub token: Option<String>, | ||
| 65 | + pub state_dir: PathBuf, | ||
| 66 | + pub apps: Vec<App>, | ||
| 67 | + /// Non-fatal notices, such as unknown keys. | ||
| 68 | + pub warnings: Vec<String>, | ||
| 69 | + /// One message per key renamed by `migrate::RENAMES`. | ||
| 70 | + pub migrated: Vec<String>, | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +impl App { | ||
| 74 | + /// Asset file name for this host, with `{arch}` expanded. | ||
| 75 | + pub fn asset_name(&self) -> String { | ||
| 76 | + self.asset.replace("{arch}", std::env::consts::ARCH) | ||
| 77 | + } | ||
| 78 | + | ||
| 79 | + /// `path` with `suffix` appended, in the same directory (e.g. `.kur-new`, `.prev`). | ||
| 80 | + pub fn sibling(&self, suffix: &str) -> PathBuf { | ||
| 81 | + let mut name = self.path.clone().into_os_string(); | ||
| 82 | + name.push(suffix); | ||
| 83 | + PathBuf::from(name) | ||
| 84 | + } | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. | ||
| 88 | +/// If anything was renamed and `write` is set, the file is rewritten once the config is valid. | ||
| 89 | +pub fn load(path: &Path, write: bool) -> Res<Config> { | ||
| 90 | + let mut text = | ||
| 91 | + fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; | ||
| 92 | + // If the text does not parse, skip migration; the toml::from_str below reports the error. | ||
| 93 | + let mut migrated = Vec::new(); | ||
| 94 | + if let Ok(mut doc) = text.parse::<toml_edit::DocumentMut>() { | ||
| 95 | + migrated = migrate::apply(&mut doc, migrate::RENAMES); | ||
| 96 | + if !migrated.is_empty() { | ||
| 97 | + text = doc.to_string(); | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + let table: toml::Table = | ||
| 101 | + toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 102 | + let mut warnings = unknown_key_warnings(&table); | ||
| 103 | + let raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; | ||
| 104 | + | ||
| 105 | + let forge = raw.forge.trim_end_matches('/').to_string(); | ||
| 106 | + if !forge.starts_with("https://") && !forge.starts_with("http://") { | ||
| 107 | + return Err("forge must start with https:// or http://".into()); | ||
| 108 | + } | ||
| 109 | + if raw.apps.is_empty() { | ||
| 110 | + return Err("no [[app]] entries in config".into()); | ||
| 111 | + } | ||
| 112 | + let mut names = HashSet::new(); | ||
| 113 | + for app in &raw.apps { | ||
| 114 | + if !valid_name(&app.name) { | ||
| 115 | + return Err(format!("invalid app name {:?}", app.name)); | ||
| 116 | + } | ||
| 117 | + if !names.insert(app.name.as_str()) { | ||
| 118 | + return Err(format!("duplicate app name {}", app.name)); | ||
| 119 | + } | ||
| 120 | + let parts: Vec<&str> = app.repo.split('/').collect(); | ||
| 121 | + if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { | ||
| 122 | + return Err(format!("{}: repo must be owner/name", app.name)); | ||
| 123 | + } | ||
| 124 | + if !app.path.is_absolute() { | ||
| 125 | + return Err(format!("{}: path must be absolute", app.name)); | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + let token = raw.token_file.as_deref().map(read_token).transpose()?; | ||
| 130 | + let state_dir = raw | ||
| 131 | + .state_dir | ||
| 132 | + .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_DIR)); | ||
| 133 | + if !migrated.is_empty() | ||
| 134 | + && write | ||
| 135 | + && let Err(e) = rewrite_config(path, &text) | ||
| 136 | + { | ||
| 137 | + warnings.push(format!("could not rewrite config: {e}")); | ||
| 138 | + } | ||
| 139 | + Ok(Config { | ||
| 140 | + forge, | ||
| 141 | + token, | ||
| 142 | + state_dir, | ||
| 143 | + apps: raw.apps, | ||
| 144 | + warnings, | ||
| 145 | + migrated, | ||
| 146 | + }) | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +/// Replaces the config at `path` with `text`, keeping the original as `<path>.bak`. | ||
| 150 | +/// The temp file is removed if anything fails, and the original is left in place. | ||
| 151 | +fn rewrite_config(path: &Path, text: &str) -> io::Result<()> { | ||
| 152 | + let tmp = with_suffix(path, ".kur-tmp"); | ||
| 153 | + let result = write_and_swap(path, &tmp, text); | ||
| 154 | + if result.is_err() { | ||
| 155 | + let _ = fs::remove_file(&tmp); | ||
| 156 | + } | ||
| 157 | + result | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +fn write_and_swap(path: &Path, tmp: &Path, text: &str) -> io::Result<()> { | ||
| 161 | + // fs::copy keeps the original's permission bits on the backup. | ||
| 162 | + fs::copy(path, with_suffix(path, ".bak"))?; | ||
| 163 | + let perms = fs::metadata(path)?.permissions(); | ||
| 164 | + // 0600 from creation, so the config is never readable by others before the final mode is set. | ||
| 165 | + let mut file = OpenOptions::new() | ||
| 166 | + .write(true) | ||
| 167 | + .create(true) | ||
| 168 | + .truncate(true) | ||
| 169 | + .mode(0o600) | ||
| 170 | + .open(tmp)?; | ||
| 171 | + file.write_all(text.as_bytes())?; | ||
| 172 | + file.set_permissions(perms)?; | ||
| 173 | + file.sync_all()?; | ||
| 174 | + drop(file); | ||
| 175 | + fs::rename(tmp, path)?; | ||
| 176 | + let parent = match path.parent() { | ||
| 177 | + Some(dir) if !dir.as_os_str().is_empty() => dir, | ||
| 178 | + _ => Path::new("."), | ||
| 179 | + }; | ||
| 180 | + fs::File::open(parent)?.sync_all() | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +/// `path` with `suffix` appended to its file name. | ||
| 184 | +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { | ||
| 185 | + let mut name = path.as_os_str().to_owned(); | ||
| 186 | + name.push(suffix); | ||
| 187 | + PathBuf::from(name) | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// One warning per key that is not in the known lists, at the top level and in each `[[app]]`. | ||
| 191 | +fn unknown_key_warnings(table: &toml::Table) -> Vec<String> { | ||
| 192 | + let mut warnings = Vec::new(); | ||
| 193 | + for key in table.keys() { | ||
| 194 | + if !KNOWN_TOP_KEYS.contains(&key.as_str()) { | ||
| 195 | + warnings.push(format!("unknown key {key:?}")); | ||
| 196 | + } | ||
| 197 | + } | ||
| 198 | + if let Some(toml::Value::Array(apps)) = table.get("app") { | ||
| 199 | + for (index, app) in apps.iter().enumerate() { | ||
| 200 | + let Some(app) = app.as_table() else { | ||
| 201 | + continue; | ||
| 202 | + }; | ||
| 203 | + let label = match app.get("name").and_then(toml::Value::as_str) { | ||
| 204 | + Some(name) => name.to_string(), | ||
| 205 | + None => format!("#{}", index + 1), | ||
| 206 | + }; | ||
| 207 | + for key in app.keys() { | ||
| 208 | + if !KNOWN_APP_KEYS.contains(&key.as_str()) { | ||
| 209 | + warnings.push(format!("unknown key {key:?} in [[app]] {label}")); | ||
| 210 | + } | ||
| 211 | + } | ||
| 212 | + } | ||
| 213 | + } | ||
| 214 | + warnings | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +/// Matches `^[a-z0-9][a-z0-9_-]{0,39}$`. | ||
| 218 | +fn valid_name(name: &str) -> bool { | ||
| 219 | + let bytes = name.as_bytes(); | ||
| 220 | + !bytes.is_empty() | ||
| 221 | + && bytes.len() <= 40 | ||
| 222 | + && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) | ||
| 223 | + && bytes | ||
| 224 | + .iter() | ||
| 225 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +/// Reads the token file, trimmed. The token is never included in error messages. | ||
| 229 | +fn read_token(path: &Path) -> Res<String> { | ||
| 230 | + let text = | ||
| 231 | + fs::read_to_string(path).map_err(|e| format!("token_file {}: {e}", path.display()))?; | ||
| 232 | + let token = text.trim(); | ||
| 233 | + if token.is_empty() { | ||
| 234 | + return Err(format!("token_file {} is empty", path.display())); | ||
| 235 | + } | ||
| 236 | + Ok(token.to_string()) | ||
| 237 | +} | ||
src/forge.rsadded+146 -0
| @@ -0,0 +1,146 @@ | |||
| 1 | +//! Forge release API and streaming, hashed asset download. | ||
| 2 | + | ||
| 3 | +use crate::Res; | ||
| 4 | +use crate::config::{App, Config}; | ||
| 5 | +use serde::Deserialize; | ||
| 6 | +use sha2::{Digest, Sha256}; | ||
| 7 | +use std::fs::{self, File}; | ||
| 8 | +use std::io::{Read, Write}; | ||
| 9 | +use std::os::unix::fs::PermissionsExt; | ||
| 10 | +use std::path::Path; | ||
| 11 | +use std::time::Duration; | ||
| 12 | +use ureq::http::Response; | ||
| 13 | +use ureq::{Agent, Body}; | ||
| 14 | + | ||
| 15 | +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 16 | +const API_TIMEOUT: Duration = Duration::from_secs(30); | ||
| 17 | +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600); | ||
| 18 | +const MAX_DOWNLOAD: u64 = 1 << 30; | ||
| 19 | +const MAX_API_BODY: u64 = 16 << 20; | ||
| 20 | + | ||
| 21 | +#[derive(Deserialize)] | ||
| 22 | +struct Release { | ||
| 23 | + tag: String, | ||
| 24 | + draft: bool, | ||
| 25 | + prerelease: bool, | ||
| 26 | + assets: Vec<Asset>, | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// A downloadable file attached to a release. | ||
| 30 | +#[derive(Deserialize)] | ||
| 31 | +pub struct Asset { | ||
| 32 | + name: String, | ||
| 33 | + size: u64, | ||
| 34 | + pub sha256: String, | ||
| 35 | + download_url: String, | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Client for one forge. The token is attached only to URLs under the forge base. | ||
| 39 | +pub struct Forge { | ||
| 40 | + agent: Agent, | ||
| 41 | + /// Forge base URL plus a trailing slash, for the token host check. | ||
| 42 | + prefix: String, | ||
| 43 | + token: Option<String>, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +impl Forge { | ||
| 47 | + pub fn new(cfg: &Config) -> Forge { | ||
| 48 | + let agent = Agent::config_builder() | ||
| 49 | + .timeout_connect(Some(CONNECT_TIMEOUT)) | ||
| 50 | + .http_status_as_error(false) | ||
| 51 | + .build() | ||
| 52 | + .into(); | ||
| 53 | + Forge { | ||
| 54 | + agent, | ||
| 55 | + prefix: format!("{}/", cfg.forge), | ||
| 56 | + token: cfg.token.clone(), | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + /// GET `url` with an overall timeout, adding the token if `url` is on the forge host. | ||
| 61 | + fn get(&self, url: &str, timeout: Duration) -> Res<Response<Body>> { | ||
| 62 | + let mut req = self | ||
| 63 | + .agent | ||
| 64 | + .get(url) | ||
| 65 | + .config() | ||
| 66 | + .timeout_global(Some(timeout)) | ||
| 67 | + .build(); | ||
| 68 | + if let Some(token) = self | ||
| 69 | + .token | ||
| 70 | + .as_deref() | ||
| 71 | + .filter(|_| url.starts_with(&self.prefix)) | ||
| 72 | + { | ||
| 73 | + req = req.header("Authorization", format!("token {token}")); | ||
| 74 | + } | ||
| 75 | + req.call().map_err(|e| format!("request failed: {e}")) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Newest eligible release of the app's repo and its asset for this host, as `(tag, asset)`. | ||
| 79 | + pub fn latest(&self, app: &App) -> Res<(String, Asset)> { | ||
| 80 | + let url = format!("{}api/v1/repos/{}/releases", self.prefix, app.repo); | ||
| 81 | + let mut resp = self.get(&url, API_TIMEOUT)?; | ||
| 82 | + if !resp.status().is_success() { | ||
| 83 | + return Err(format!("releases API returned {}", resp.status())); | ||
| 84 | + } | ||
| 85 | + let releases: Vec<Release> = | ||
| 86 | + serde_json::from_reader(resp.body_mut().with_config().limit(MAX_API_BODY).reader()) | ||
| 87 | + .map_err(|e| format!("bad releases JSON: {e}"))?; | ||
| 88 | + | ||
| 89 | + let Release { tag, assets, .. } = releases | ||
| 90 | + .into_iter() | ||
| 91 | + .find(|r| !r.draft && (app.prerelease || !r.prerelease)) | ||
| 92 | + .ok_or("no release")?; | ||
| 93 | + let want = app.asset_name(); | ||
| 94 | + let asset = assets | ||
| 95 | + .into_iter() | ||
| 96 | + .find(|a| a.name == want) | ||
| 97 | + .ok_or_else(|| format!("release {tag} has no asset {want}"))?; | ||
| 98 | + if asset.sha256.len() != 64 | ||
| 99 | + || !asset | ||
| 100 | + .sha256 | ||
| 101 | + .bytes() | ||
| 102 | + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) | ||
| 103 | + { | ||
| 104 | + return Err(format!("asset {want} has a malformed sha256")); | ||
| 105 | + } | ||
| 106 | + Ok((tag, asset)) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + /// Streams `asset` to `dest` (mode 0755, fsynced), failing on a hash mismatch or the size cap. | ||
| 110 | + /// On error the caller removes `dest`. | ||
| 111 | + pub fn download(&self, asset: &Asset, dest: &Path) -> Res<()> { | ||
| 112 | + if asset.size > MAX_DOWNLOAD { | ||
| 113 | + return Err(format!("asset {} is larger than 1 GiB", asset.name)); | ||
| 114 | + } | ||
| 115 | + let mut resp = self.get(&asset.download_url, DOWNLOAD_TIMEOUT)?; | ||
| 116 | + if !resp.status().is_success() { | ||
| 117 | + return Err(format!("download returned {}", resp.status())); | ||
| 118 | + } | ||
| 119 | + let mut body = resp.body_mut().with_config().limit(MAX_DOWNLOAD).reader(); | ||
| 120 | + let mut file = File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?; | ||
| 121 | + let mut hasher = Sha256::new(); | ||
| 122 | + let mut buf = vec![0u8; 64 * 1024]; | ||
| 123 | + loop { | ||
| 124 | + let n = body | ||
| 125 | + .read(&mut buf) | ||
| 126 | + .map_err(|e| format!("download failed: {e}"))?; | ||
| 127 | + if n == 0 { | ||
| 128 | + break; | ||
| 129 | + } | ||
| 130 | + hasher.update(&buf[..n]); | ||
| 131 | + file.write_all(&buf[..n]) | ||
| 132 | + .map_err(|e| format!("write {}: {e}", dest.display()))?; | ||
| 133 | + } | ||
| 134 | + file.set_permissions(fs::Permissions::from_mode(0o755)) | ||
| 135 | + .and_then(|()| file.sync_all()) | ||
| 136 | + .map_err(|e| format!("finalize {}: {e}", dest.display()))?; | ||
| 137 | + let got = hex::encode(hasher.finalize()); | ||
| 138 | + if got != asset.sha256 { | ||
| 139 | + return Err(format!( | ||
| 140 | + "sha256 mismatch for {} (expected {}, got {got})", | ||
| 141 | + asset.name, asset.sha256 | ||
| 142 | + )); | ||
| 143 | + } | ||
| 144 | + Ok(()) | ||
| 145 | + } | ||
| 146 | +} | ||
src/install.rsadded+266 -0
| @@ -0,0 +1,266 @@ | |||
| 1 | +//! Per-app install flow: download, check, swap, restart, health check, rollback. | ||
| 2 | +//! State files in `state_dir`: `{name}.bad` lists rejected sha256s, `{name}.tag` the last tag installed. | ||
| 3 | + | ||
| 4 | +use crate::Res; | ||
| 5 | +use crate::config::{App, Config}; | ||
| 6 | +use crate::forge::Forge; | ||
| 7 | +use sha2::{Digest, Sha256}; | ||
| 8 | +use std::fs::{self, File, OpenOptions}; | ||
| 9 | +use std::io::{ErrorKind, Read, Write}; | ||
| 10 | +use std::os::unix::fs::DirBuilderExt; | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | +use std::process::{Command, Stdio}; | ||
| 13 | +use std::thread::sleep; | ||
| 14 | +use std::time::{Duration, Instant}; | ||
| 15 | + | ||
| 16 | +const CHECK_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 17 | +const HEALTH_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); | ||
| 18 | +const STABLE_FOR: Duration = Duration::from_secs(5); | ||
| 19 | + | ||
| 20 | +/// Creates the state directory (mode 0700) if it does not exist. | ||
| 21 | +pub fn ensure_state_dir(dir: &Path) -> Res<()> { | ||
| 22 | + fs::DirBuilder::new() | ||
| 23 | + .recursive(true) | ||
| 24 | + .mode(0o700) | ||
| 25 | + .create(dir) | ||
| 26 | + .map_err(|e| format!("state dir {}: {e}", dir.display())) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// Takes the exclusive run lock (`state_dir/lock`). Fails at once if another run holds it. | ||
| 30 | +pub fn lock(dir: &Path) -> Res<File> { | ||
| 31 | + let path = dir.join("lock"); | ||
| 32 | + let file = File::create(&path).map_err(|e| format!("open {}: {e}", path.display()))?; | ||
| 33 | + file.try_lock() | ||
| 34 | + .map_err(|_| "another kur run is in progress".to_string())?; | ||
| 35 | + Ok(file) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// `kur status` text for one app (after the name). Changes nothing. | ||
| 39 | +pub fn status(forge: &Forge, cfg: &Config, app: &App) -> Res<String> { | ||
| 40 | + let (tag, asset) = forge.latest(app)?; | ||
| 41 | + let installed = file_sha256(&app.path)?; | ||
| 42 | + let state = if installed.as_deref() == Some(asset.sha256.as_str()) { | ||
| 43 | + "up to date" | ||
| 44 | + } else if is_bad(cfg, app, &asset.sha256)? { | ||
| 45 | + "skipped (bad build)" | ||
| 46 | + } else { | ||
| 47 | + "update available" | ||
| 48 | + }; | ||
| 49 | + let inst = match &installed { | ||
| 50 | + Some(sha) => format!("installed {}", short(sha)), | ||
| 51 | + None => "not installed".to_string(), | ||
| 52 | + }; | ||
| 53 | + Ok(format!( | ||
| 54 | + "{inst}, newest {tag} {}: {state}", | ||
| 55 | + short(&asset.sha256) | ||
| 56 | + )) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// Installs the newest release of one app if needed. Returns the status text after the app name. | ||
| 60 | +pub fn update(forge: &Forge, cfg: &Config, app: &App) -> Res<String> { | ||
| 61 | + let (tag, asset) = forge.latest(app)?; | ||
| 62 | + if file_sha256(&app.path)?.as_deref() == Some(asset.sha256.as_str()) { | ||
| 63 | + return Ok(format!("up to date ({tag})")); | ||
| 64 | + } | ||
| 65 | + if is_bad(cfg, app, &asset.sha256)? { | ||
| 66 | + return Ok(format!("skipped (bad build {tag})")); | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + let staged = app.sibling(".kur-new"); | ||
| 70 | + let _ = fs::remove_file(&staged); | ||
| 71 | + if let Err(e) = forge.download(&asset, &staged) { | ||
| 72 | + let _ = fs::remove_file(&staged); | ||
| 73 | + return Err(e); | ||
| 74 | + } | ||
| 75 | + if let Err(e) = check_binary(app, &staged) { | ||
| 76 | + let _ = fs::remove_file(&staged); | ||
| 77 | + mark_bad(cfg, app, &asset.sha256)?; | ||
| 78 | + return Err(e); | ||
| 79 | + } | ||
| 80 | + swap(app, &staged)?; | ||
| 81 | + | ||
| 82 | + let Some(unit) = app.unit.as_deref() else { | ||
| 83 | + write_tag(cfg, app, &tag)?; | ||
| 84 | + return Ok(format!("{tag} installed")); | ||
| 85 | + }; | ||
| 86 | + match deploy(app, unit) { | ||
| 87 | + Ok(()) => { | ||
| 88 | + write_tag(cfg, app, &tag)?; | ||
| 89 | + Ok(format!("{tag} installed")) | ||
| 90 | + } | ||
| 91 | + Err(reason) => { | ||
| 92 | + let marked = mark_bad(cfg, app, &asset.sha256); | ||
| 93 | + let mut msg = rollback(app, unit, &tag, &reason); | ||
| 94 | + if let Err(e) = marked { | ||
| 95 | + msg = format!("{msg}; could not record bad build: {e}"); | ||
| 96 | + } | ||
| 97 | + Err(msg) | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +/// First 12 hex chars of a sha256, for display. | ||
| 103 | +fn short(sha: &str) -> &str { | ||
| 104 | + sha.get(..12).unwrap_or(sha) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Lowercase hex sha256 of the file at `path`, or None if it does not exist. | ||
| 108 | +fn file_sha256(path: &Path) -> Res<Option<String>> { | ||
| 109 | + let mut file = match File::open(path) { | ||
| 110 | + Ok(file) => file, | ||
| 111 | + Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), | ||
| 112 | + Err(e) => return Err(format!("open {}: {e}", path.display())), | ||
| 113 | + }; | ||
| 114 | + let mut hasher = Sha256::new(); | ||
| 115 | + let mut buf = vec![0u8; 64 * 1024]; | ||
| 116 | + loop { | ||
| 117 | + let n = file | ||
| 118 | + .read(&mut buf) | ||
| 119 | + .map_err(|e| format!("read {}: {e}", path.display()))?; | ||
| 120 | + if n == 0 { | ||
| 121 | + break; | ||
| 122 | + } | ||
| 123 | + hasher.update(&buf[..n]); | ||
| 124 | + } | ||
| 125 | + Ok(Some(hex::encode(hasher.finalize()))) | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +fn state_file(cfg: &Config, app: &App, ext: &str) -> PathBuf { | ||
| 129 | + cfg.state_dir.join(format!("{}.{ext}", app.name)) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// Whether `sha` is listed in the app's `.bad` file. | ||
| 133 | +fn is_bad(cfg: &Config, app: &App, sha: &str) -> Res<bool> { | ||
| 134 | + match fs::read_to_string(state_file(cfg, app, "bad")) { | ||
| 135 | + Ok(text) => Ok(text.lines().any(|line| line.trim() == sha)), | ||
| 136 | + Err(e) if e.kind() == ErrorKind::NotFound => Ok(false), | ||
| 137 | + Err(e) => Err(format!("read bad list: {e}")), | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +fn mark_bad(cfg: &Config, app: &App, sha: &str) -> Res<()> { | ||
| 142 | + let path = state_file(cfg, app, "bad"); | ||
| 143 | + let mut file = OpenOptions::new() | ||
| 144 | + .create(true) | ||
| 145 | + .append(true) | ||
| 146 | + .open(&path) | ||
| 147 | + .map_err(|e| format!("open {}: {e}", path.display()))?; | ||
| 148 | + writeln!(file, "{sha}").map_err(|e| format!("write {}: {e}", path.display())) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +fn write_tag(cfg: &Config, app: &App, tag: &str) -> Res<()> { | ||
| 152 | + let path = state_file(cfg, app, "tag"); | ||
| 153 | + fs::write(&path, tag).map_err(|e| format!("write {}: {e}", path.display())) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// Runs the staged binary with the app's `check` args, if any. Fails on non-zero exit or timeout. | ||
| 157 | +fn check_binary(app: &App, staged: &Path) -> Res<()> { | ||
| 158 | + let Some(args) = &app.check else { | ||
| 159 | + return Ok(()); | ||
| 160 | + }; | ||
| 161 | + let mut child = Command::new(staged) | ||
| 162 | + .args(args) | ||
| 163 | + .stdin(Stdio::null()) | ||
| 164 | + .stdout(Stdio::null()) | ||
| 165 | + .stderr(Stdio::null()) | ||
| 166 | + .spawn() | ||
| 167 | + .map_err(|e| format!("cannot run staged binary: {e}"))?; | ||
| 168 | + let deadline = Instant::now() + CHECK_TIMEOUT; | ||
| 169 | + loop { | ||
| 170 | + if let Some(status) = child.try_wait().map_err(|e| format!("check: {e}"))? { | ||
| 171 | + return if status.success() { | ||
| 172 | + Ok(()) | ||
| 173 | + } else { | ||
| 174 | + Err(format!("check exited with {status}")) | ||
| 175 | + }; | ||
| 176 | + } | ||
| 177 | + if Instant::now() >= deadline { | ||
| 178 | + let _ = child.kill(); | ||
| 179 | + let _ = child.wait(); | ||
| 180 | + return Err("check timed out".into()); | ||
| 181 | + } | ||
| 182 | + sleep(Duration::from_millis(50)); | ||
| 183 | + } | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +/// Moves the current binary to `.prev` (if any) and the staged file into place, then fsyncs the dir. | ||
| 187 | +fn swap(app: &App, staged: &Path) -> Res<()> { | ||
| 188 | + match fs::rename(&app.path, app.sibling(".prev")) { | ||
| 189 | + Err(e) if e.kind() != ErrorKind::NotFound => { | ||
| 190 | + return Err(format!("keep previous {}: {e}", app.path.display())); | ||
| 191 | + } | ||
| 192 | + _ => {} | ||
| 193 | + } | ||
| 194 | + fs::rename(staged, &app.path).map_err(|e| format!("install {}: {e}", app.path.display()))?; | ||
| 195 | + let dir = app.path.parent().unwrap_or(Path::new("/")); | ||
| 196 | + File::open(dir) | ||
| 197 | + .and_then(|d| d.sync_all()) | ||
| 198 | + .map_err(|e| format!("fsync {}: {e}", dir.display())) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// Restarts `unit` and waits until it is active and healthy, then requires it to stay active. | ||
| 202 | +/// Returns the failure reason on error. | ||
| 203 | +fn deploy(app: &App, unit: &str) -> Result<(), String> { | ||
| 204 | + restart(unit)?; | ||
| 205 | + let deadline = Instant::now() + Duration::from_secs(app.health_timeout_secs); | ||
| 206 | + while !(is_active(unit) && health_ok(app.health_url.as_deref())) { | ||
| 207 | + if Instant::now() >= deadline { | ||
| 208 | + return Err("health check timed out".into()); | ||
| 209 | + } | ||
| 210 | + sleep(Duration::from_secs(1)); | ||
| 211 | + } | ||
| 212 | + sleep(STABLE_FOR); | ||
| 213 | + if !is_active(unit) { | ||
| 214 | + return Err(format!("{unit} stopped after health check")); | ||
| 215 | + } | ||
| 216 | + Ok(()) | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// Restores `.prev` over the failed binary and restarts the unit. Returns the error text. | ||
| 220 | +fn rollback(app: &App, unit: &str, tag: &str, reason: &str) -> String { | ||
| 221 | + let failed = format!("{tag} failed health check ({reason})"); | ||
| 222 | + match fs::rename(app.sibling(".prev"), &app.path) { | ||
| 223 | + Ok(()) => match restart(unit) { | ||
| 224 | + Ok(()) => format!("{failed}, rolled back"), | ||
| 225 | + Err(e) => format!("{failed}, rolled back but {e}"), | ||
| 226 | + }, | ||
| 227 | + Err(e) if e.kind() == ErrorKind::NotFound => { | ||
| 228 | + format!("{failed}, no previous binary to restore") | ||
| 229 | + } | ||
| 230 | + Err(e) => format!("{failed}, restore failed: {e}"), | ||
| 231 | + } | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// True if `url` is unset or answers 2xx within the request timeout. No token is sent. | ||
| 235 | +fn health_ok(url: Option<&str>) -> bool { | ||
| 236 | + let Some(url) = url else { | ||
| 237 | + return true; | ||
| 238 | + }; | ||
| 239 | + ureq::get(url) | ||
| 240 | + .config() | ||
| 241 | + .timeout_global(Some(HEALTH_REQUEST_TIMEOUT)) | ||
| 242 | + .build() | ||
| 243 | + .call() | ||
| 244 | + .is_ok_and(|resp| resp.status().is_success()) | ||
| 245 | +} | ||
| 246 | + | ||
| 247 | +fn restart(unit: &str) -> Result<(), String> { | ||
| 248 | + systemctl(&["restart", unit]) | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +fn is_active(unit: &str) -> bool { | ||
| 252 | + systemctl(&["is-active", "--quiet", unit]).is_ok() | ||
| 253 | +} | ||
| 254 | + | ||
| 255 | +fn systemctl(args: &[&str]) -> Result<(), String> { | ||
| 256 | + let status = Command::new("systemctl") | ||
| 257 | + .args(args) | ||
| 258 | + .stdout(Stdio::null()) | ||
| 259 | + .status() | ||
| 260 | + .map_err(|e| format!("systemctl: {e}"))?; | ||
| 261 | + if status.success() { | ||
| 262 | + Ok(()) | ||
| 263 | + } else { | ||
| 264 | + Err(format!("systemctl {} failed", args.join(" "))) | ||
| 265 | + } | ||
| 266 | +} | ||
src/main.rsadded+125 -0
| @@ -0,0 +1,125 @@ | |||
| 1 | +//! kur: installs the newest forge release of each configured app on this host, with rollback. | ||
| 2 | +//! Runs from a systemd timer as root; prints one line per app on stdout, errors on stderr. | ||
| 3 | + | ||
| 4 | +mod config; | ||
| 5 | +mod forge; | ||
| 6 | +mod install; | ||
| 7 | +mod migrate; | ||
| 8 | + | ||
| 9 | +use crate::config::{App, Config}; | ||
| 10 | +use crate::forge::Forge; | ||
| 11 | +use std::env; | ||
| 12 | +use std::path::PathBuf; | ||
| 13 | +use std::process::ExitCode; | ||
| 14 | + | ||
| 15 | +/// Crate-wide result type; errors are human-readable messages. | ||
| 16 | +pub type Res<T> = Result<T, String>; | ||
| 17 | + | ||
| 18 | +const USAGE: &str = "usage: kur [--config <path>] <command> | ||
| 19 | + | ||
| 20 | +commands: | ||
| 21 | + run [app] install newer releases (all apps, or only <app>) | ||
| 22 | + status show installed and newest releases; changes nothing | ||
| 23 | + --version print the version | ||
| 24 | +"; | ||
| 25 | + | ||
| 26 | +fn main() -> ExitCode { | ||
| 27 | + let mut args = env::args().skip(1); | ||
| 28 | + let mut config_path = env::var_os("KUR_CONFIG") | ||
| 29 | + .map_or_else(|| PathBuf::from(config::DEFAULT_PATH), PathBuf::from); | ||
| 30 | + let mut words = Vec::new(); | ||
| 31 | + while let Some(arg) = args.next() { | ||
| 32 | + match arg.as_str() { | ||
| 33 | + "--config" => match args.next() { | ||
| 34 | + Some(path) => config_path = path.into(), | ||
| 35 | + None => return usage(), | ||
| 36 | + }, | ||
| 37 | + "--version" => { | ||
| 38 | + println!("kur {}", env!("CARGO_PKG_VERSION")); | ||
| 39 | + return ExitCode::SUCCESS; | ||
| 40 | + } | ||
| 41 | + _ => words.push(arg), | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + let words: Vec<&str> = words.iter().map(String::as_str).collect(); | ||
| 45 | + let (only, status) = match words.as_slice() { | ||
| 46 | + ["run"] => (None, false), | ||
| 47 | + ["run", name] => (Some(*name), false), | ||
| 48 | + ["status"] => (None, true), | ||
| 49 | + _ => return usage(), | ||
| 50 | + }; | ||
| 51 | + | ||
| 52 | + // Status never writes, so a renamed key is only reported. | ||
| 53 | + let cfg = match config::load(&config_path, !status) { | ||
| 54 | + Ok(cfg) => cfg, | ||
| 55 | + Err(e) => { | ||
| 56 | + eprintln!("kur: {e}"); | ||
| 57 | + return ExitCode::FAILURE; | ||
| 58 | + } | ||
| 59 | + }; | ||
| 60 | + let note = if status { | ||
| 61 | + " (not written, status changes nothing)" | ||
| 62 | + } else { | ||
| 63 | + "" | ||
| 64 | + }; | ||
| 65 | + for message in &cfg.migrated { | ||
| 66 | + println!("kur: config: {message}{note}"); | ||
| 67 | + } | ||
| 68 | + for warning in &cfg.warnings { | ||
| 69 | + eprintln!("kur: warning: {warning}"); | ||
| 70 | + } | ||
| 71 | + let apps: Vec<&App> = cfg | ||
| 72 | + .apps | ||
| 73 | + .iter() | ||
| 74 | + .filter(|app| only.is_none_or(|name| app.name == name)) | ||
| 75 | + .collect(); | ||
| 76 | + if apps.is_empty() { | ||
| 77 | + eprintln!("kur: no app named {}", only.unwrap_or_default()); | ||
| 78 | + return ExitCode::FAILURE; | ||
| 79 | + } | ||
| 80 | + // Held until exit, so a manual `kur run` and a timer run never stage the same files at once. | ||
| 81 | + let _lock = if status { | ||
| 82 | + None | ||
| 83 | + } else { | ||
| 84 | + match install::ensure_state_dir(&cfg.state_dir).and_then(|()| install::lock(&cfg.state_dir)) | ||
| 85 | + { | ||
| 86 | + Ok(lock) => Some(lock), | ||
| 87 | + Err(e) => { | ||
| 88 | + eprintln!("kur: {e}"); | ||
| 89 | + return ExitCode::FAILURE; | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + }; | ||
| 93 | + process_apps(&cfg, &apps, status) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// Runs status or update for each app. One app failing never stops the others. | ||
| 97 | +fn process_apps(cfg: &Config, apps: &[&App], status: bool) -> ExitCode { | ||
| 98 | + let forge = Forge::new(cfg); | ||
| 99 | + let mut failed = false; | ||
| 100 | + for app in apps { | ||
| 101 | + let result = if status { | ||
| 102 | + install::status(&forge, cfg, app) | ||
| 103 | + } else { | ||
| 104 | + install::update(&forge, cfg, app) | ||
| 105 | + }; | ||
| 106 | + match result { | ||
| 107 | + Ok(msg) => println!("{}: {msg}", app.name), | ||
| 108 | + Err(e) => { | ||
| 109 | + eprintln!("kur: {}: {e}", app.name); | ||
| 110 | + failed = true; | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + if failed { | ||
| 115 | + ExitCode::FAILURE | ||
| 116 | + } else { | ||
| 117 | + ExitCode::SUCCESS | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +/// Prints usage and returns exit code 2 (bad invocation). | ||
| 122 | +fn usage() -> ExitCode { | ||
| 123 | + eprint!("{USAGE}"); | ||
| 124 | + ExitCode::from(2) | ||
| 125 | +} | ||
src/migrate.rsadded+127 -0
| @@ -0,0 +1,127 @@ | |||
| 1 | +//! Config key renames. Old configs keep working, and `kur run` rewrites them to the new names. | ||
| 2 | + | ||
| 3 | +use toml_edit::{DocumentMut, Item, Key, Table}; | ||
| 4 | + | ||
| 5 | +/// Where a rename applies. | ||
| 6 | +// Nothing is renamed yet, so no entry constructs these variants. | ||
| 7 | +#[allow(dead_code)] | ||
| 8 | +#[derive(Clone, Copy)] | ||
| 9 | +pub enum Scope { | ||
| 10 | + /// The root table. | ||
| 11 | + Top, | ||
| 12 | + /// Every table in the `[[app]]` array. | ||
| 13 | + App, | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// `(scope, old name, new name)`. Add an entry here when a key is renamed, never remove one. | ||
| 17 | +/// Also add the new name to `KNOWN_TOP_KEYS` or `KNOWN_APP_KEYS` in `config.rs`. | ||
| 18 | +/// | ||
| 19 | +/// Example, for an `[[app]]` key `health_wait` renamed to `health_timeout_secs`: | ||
| 20 | +/// ```text | ||
| 21 | +/// (Scope::App, "health_wait", "health_timeout_secs"), | ||
| 22 | +/// ``` | ||
| 23 | +pub const RENAMES: &[(Scope, &str, &str)] = &[]; | ||
| 24 | + | ||
| 25 | +/// What happened to the old key in one table. | ||
| 26 | +enum Change { | ||
| 27 | + Renamed, | ||
| 28 | + Dropped, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// Renames keys in `doc` in place and returns one message per change. | ||
| 32 | +/// | ||
| 33 | +/// A renamed key keeps its value, its position in the table, and its comments. If the new name | ||
| 34 | +/// is already set in the same table, the old key is removed instead. | ||
| 35 | +pub fn apply(doc: &mut DocumentMut, renames: &[(Scope, &str, &str)]) -> Vec<String> { | ||
| 36 | + let mut messages = Vec::new(); | ||
| 37 | + for &(scope, old, new) in renames { | ||
| 38 | + match scope { | ||
| 39 | + Scope::Top => { | ||
| 40 | + if let Some(change) = rename_key(doc.as_table_mut(), old, new) { | ||
| 41 | + messages.push(describe(&change, old, new, None)); | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + Scope::App => { | ||
| 45 | + let Some(apps) = doc | ||
| 46 | + .get_mut("app") | ||
| 47 | + .and_then(|item| item.as_array_of_tables_mut()) | ||
| 48 | + else { | ||
| 49 | + continue; | ||
| 50 | + }; | ||
| 51 | + for (index, table) in apps.iter_mut().enumerate() { | ||
| 52 | + let label = app_label(table, index); | ||
| 53 | + if let Some(change) = rename_key(table, old, new) { | ||
| 54 | + messages.push(describe(&change, old, new, Some(&label))); | ||
| 55 | + } | ||
| 56 | + } | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | + messages | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// The `name` of an `[[app]]` table, or `#<1-based index>` if it has none. | ||
| 64 | +fn app_label(table: &Table, index: usize) -> String { | ||
| 65 | + match table.get("name").and_then(Item::as_str) { | ||
| 66 | + Some(name) => name.to_string(), | ||
| 67 | + None => format!("#{}", index + 1), | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +/// Renames `old` to `new` in `table`, keeping the key's position and decor. Returns `None` if | ||
| 72 | +/// `old` is not set. | ||
| 73 | +fn rename_key(table: &mut Table, old: &str, new: &str) -> Option<Change> { | ||
| 74 | + if !table.contains_key(old) { | ||
| 75 | + return None; | ||
| 76 | + } | ||
| 77 | + if table.contains_key(new) { | ||
| 78 | + table.remove(old); | ||
| 79 | + return Some(Change::Dropped); | ||
| 80 | + } | ||
| 81 | + // toml_edit cannot change a key's name in place, so take every entry out in order and | ||
| 82 | + // insert them back, with the renamed key where the old one was. | ||
| 83 | + let names: Vec<String> = table.iter().map(|(key, _)| key.to_string()).collect(); | ||
| 84 | + let entries: Vec<(Key, Item)> = names | ||
| 85 | + .iter() | ||
| 86 | + .filter_map(|name| table.remove_entry(name)) | ||
| 87 | + .collect(); | ||
| 88 | + for (key, item) in entries { | ||
| 89 | + if key.get() == old { | ||
| 90 | + let renamed = Key::new(new).with_leaf_decor(key.leaf_decor().clone()); | ||
| 91 | + table.insert_formatted(&renamed, item); | ||
| 92 | + } else { | ||
| 93 | + table.insert_formatted(&key, item); | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + Some(Change::Renamed) | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +fn describe(change: &Change, old: &str, new: &str, app: Option<&str>) -> String { | ||
| 100 | + let location = app | ||
| 101 | + .map(|label| format!(" in [[app]] {label}")) | ||
| 102 | + .unwrap_or_default(); | ||
| 103 | + match change { | ||
| 104 | + Change::Renamed => format!("renamed {old:?} to {new:?}{location}"), | ||
| 105 | + Change::Dropped => format!("dropped {old:?} (already set as {new:?}){location}"), | ||
| 106 | + } | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +#[cfg(test)] | ||
| 110 | +mod tests { | ||
| 111 | + use super::*; | ||
| 112 | + | ||
| 113 | + #[test] | ||
| 114 | + fn renames_app_key_keeping_comment_value_and_position() { | ||
| 115 | + let text = "forge = \"https://x\"\n\n[[app]]\nname = \"im\"\n# how often\nold_key = 5\nrepo = \"a/b\"\n"; | ||
| 116 | + let mut doc: DocumentMut = text.parse().unwrap(); | ||
| 117 | + let renames = [(Scope::App, "old_key", "new_key")]; | ||
| 118 | + let messages = apply(&mut doc, &renames); | ||
| 119 | + let out = doc.to_string(); | ||
| 120 | + assert!(out.contains("# how often\nnew_key = 5\nrepo"), "{out}"); | ||
| 121 | + assert!(!out.contains("old_key"), "{out}"); | ||
| 122 | + assert_eq!( | ||
| 123 | + messages, | ||
| 124 | + ["renamed \"old_key\" to \"new_key\" in [[app]] im"] | ||
| 125 | + ); | ||
| 126 | + } | ||
| 127 | +} | ||