diff --git a/.forge/ci.toml b/.forge/ci.toml new file mode 100644 index 0000000..7d82561 --- /dev/null +++ b/.forge/ci.toml @@ -0,0 +1,42 @@ +# CI for kur. Format: forge's docs/ci.md. +# +# The workflow has no branch condition, so the job also runs for pull requests. +# One job does everything, so its steps run one at a time. A tag push matching "v*" publishes a +# release with the binary and SHA256SUMS, only when the job succeeded. + +name = "build" + +[on] +push = ["main"] +pull_request = true +manual = true +tags = ["v*"] + +[jobs.build] +image = "docker.io/library/rust:1" +# Build parallelism comes from the runner (CARGO_BUILD_JOBS follows its CPU limit). Drops debuginfo. +# CARGO_HOME in the workspace puts the downloaded crates in the cache, so a run downloads only new ones. +env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home" } +# Tests run first, so a failure shows before the slow LTO release build. +# The groups are the job's steps on the run page, and `exec 2>&1` keeps a marker in order with cargo's +# stderr, which the runner reads from a separate pipe. +run = """ +exec 2>&1 +echo "::group::Tests" +cargo test +echo "::endgroup::" +echo "::group::Release build" +cargo build --release +echo "::endgroup::" +echo "::group::Package" +ARCH=$(uname -m) +cp target/release/kur kur-$ARCH-linux +sha256sum kur-$ARCH-linux > SHA256SUMS +echo "::endgroup::" +""" +artifacts = ["kur-*-linux", "SHA256SUMS"] +cache = ["target", ".cargo-home"] +timeout_minutes = 60 + +[release] +assets = ["build:kur-*-linux", "build:SHA256SUMS"] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..44c82b8 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,609 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "375989decec1a0fa424442bed520fa12ede43a48475ce8c7417d2c69b32b5f6b" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "kur" +version = "0.1.0" +dependencies = [ + "hex", + "serde", + "serde_json", + "sha2", + "toml", + "toml_edit", + "ureq", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "untrusted", + "windows-sys", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "toml" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5ffcdf8f50436dbbfd675c1fe1b8e0854f42b7defea8584bdebe1aee900e561" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.18+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ec6e78bd70db9420d8d212fa9dc97f116448a1ceff5d00eabb991d407e21396" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7be76686bdf7198002062423ca0d8cf9b75a27c8e1de804513b97e97b555d9d" +dependencies = [ + "base64", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..9e5e4ed --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "kur" +version = "0.1.0" +edition = "2024" +license = "AGPL-3.0-or-later" +description = "Installs the newest forge release of each app on a server, with rollback" + +[dependencies] +hex = "0.4.3" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +sha2 = "0.11.1" +toml = "1.2.0" +toml_edit = "0.25.18" +ureq = "3.5.1" + +[lints.rust] +unsafe_code = "forbid" + +[profile.dev] +debug = "line-tables-only" + +[profile.release] +lto = true +codegen-units = 1 diff --git a/README.md b/README.md new file mode 100644 index 0000000..1011587 --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# kur + +kur ("install" in Turkish) installs the newest release of each configured app on a server. It runs +from a systemd timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary +in only when the release asset differs from the installed file. After a swap it restarts the app's +systemd unit and health-checks it, and it rolls back to the previous binary if the check fails. It is +one binary that runs as root and has no daemon. + +## Releases + +For each app, kur lists the repo's releases (newest first) and takes the first one that is not a draft +and is not a prerelease. Set `prerelease = true` on an app to also accept prereleases. Within the chosen +release it looks up the asset named by `asset` (with `{arch}` filled in). The forge reports each asset's +sha256; kur verifies the download against that value and refuses a mismatch. + +## Run flow + +For each app, in order: + +1. Fetch the release and asset. +2. Compare the sha256 of the installed binary with the asset's. If equal, report `up to date`. +3. If the asset's sha256 is listed in `{state_dir}/{name}.bad`, report it as skipped. +4. Download to `{path}.kur-new`, hashing while writing. Mode 0755, fsync. +5. If `check` is set, run the new file with those arguments (10 s limit). Failure marks the build bad. +6. Rename the installed binary to `{path}.prev` and the new file to `{path}`. +7. If `unit` is set, restart it and wait until `systemctl is-active` succeeds, `health_url` returns 2xx, + and the unit is still active 5 s later. Times out after `health_timeout_secs`. +8. On health failure, the build's sha256 is appended to `{name}.bad`. If `{path}.prev` exists, it is + renamed back to `{path}` and the unit is restarted. Otherwise the run reports that there was no + previous binary to restore. + +A run holds a lock on `{state_dir}/lock`, so a manual `kur run` exits at once while the timer's run is +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 +collects. + +### The bad list + +`{state_dir}/{name}.bad` holds one sha256 per line. kur skips any release whose asset hash is in the +file. To retry a build, delete its line, or delete the file to clear the list for that app. + +## Install + +Run as root on the app server. + +```sh +install -m 0755 kur /usr/local/bin/kur +install -d -m 0755 /etc/kur +install -m 0600 config/kur.example.toml /etc/kur/kur.toml # then edit it +# Optional, for private repos. Use a read-only token. +(umask 077; printf '%s\n' 'TOKEN' > /etc/kur/token) +install -m 0644 deploy/kur.service deploy/kur.timer /etc/systemd/system/ +systemctl daemon-reload +systemctl enable --now kur.timer +``` + +The app units (for example `im.service`) are not part of this repo. They must exist before kur runs +for that app. If `token_file` is set in the config, the token file must be mode 0600. + +## Commands + +``` +kur run process every app once +kur run process one app +kur status show installed and newest versions; changes nothing +kur --version print "kur " +kur help print usage (also used for unknown commands, exit 2) +``` + +Global option: `--config `, placed before the command. Otherwise `KUR_CONFIG` is used, then +`/etc/kur/kur.toml`. + +Exit code is 0 when every app succeeded or was up to date, and 1 if any app failed. + +## Config reference + +Top level: + +| Key | Required | Default | Meaning | +|---|---|---|---| +| `forge` | yes | none | Forge base URL, `https://` or `http://`. Trailing slash is trimmed. | +| `token_file` | no | none | File with a forge token for private repos. Read once, trimmed. Unreadable file is a config error. | +| `state_dir` | no | `/var/lib/kur` | Directory for `.bad` and `.tag` files and the run lock. Created with mode 0700 if missing. | + +Each `[[app]]` table: + +| Key | Required | Default | Meaning | +|---|---|---|---| +| `name` | yes | none | Unique. Must match `^[a-z0-9][a-z0-9_-]{0,39}$`. | +| `repo` | yes | none | Forge repo as `owner/name`. | +| `asset` | yes | none | Asset file name. `{arch}` is replaced by the machine architecture. | +| `path` | yes | none | Absolute path of the installed binary. | +| `unit` | no | none | systemd unit to restart and health-check. Without it kur only swaps the file. | +| `prerelease` | no | `false` | Also accept prerelease releases. | +| `check` | no | none | Arguments for the new binary, run before the swap. Must exit 0 within 10 s. | +| `health_url` | no | none | URL that must return 2xx after restart. No token is sent. | +| `health_timeout_secs` | no | `30` | Time allowed for the health check to pass. | + +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. + +See `config/kur.example.toml` for a working example. + +## Config changes between versions + +Unknown keys are warnings, as above. When a release renames a key, the old name keeps working. `kur run` +then rewrites the config file to the new names and keeps its comments and layout. The original is saved +next to it as `.bak`. `kur status` reports the renames but writes nothing. If the rewrite fails, +kur warns and runs with the renamed config in memory. + +## Publishing an app + +kur needs each app's repo to publish its binary as a forge release. The app repo needs a forge CI +config with a `[release]` section that publishes `--linux` (for example `im-x86_64-linux`) +on `v*` tags, so the release has an asset that kur can match. See `.forge/ci.toml` in this repo for +an example. diff --git a/config/kur.example.toml b/config/kur.example.toml new file mode 100644 index 0000000..2009274 --- /dev/null +++ b/config/kur.example.toml @@ -0,0 +1,36 @@ +# Example kur config. Install it as /etc/kur/kur.toml (mode 0600). +# Field reference: README.md. + +# Forge base URL. A trailing slash is fine. +forge = "https://git.tahinli.com" + +# Optional: file holding a forge token for private repos. Read once at start, trimmed. +# Use a read-only token. Must be mode 0600. +# token_file = "/etc/kur/token" + +# Optional: where kur keeps .bad and .tag files. Default shown. +# state_dir = "/var/lib/kur" + +# The im server. Its unit is im.service, which kur restarts after a swap. +[[app]] +name = "im" +repo = "Tahinli/im" +# {arch} is replaced by the machine architecture (x86_64, aarch64). +asset = "im-{arch}-linux" +path = "/usr/local/bin/im" +unit = "im.service" +# im has no --version flag, so there is no pre-swap check. +# health_url must match the listen address in im's config. +health_url = "http://127.0.0.1:7650/healthz" +# health_timeout_secs = 30 +# prerelease = false + +# kur updates itself. There is no unit: the new binary is swapped in and +# used from the next timer run on. kur runs `kur --version` on the new build +# before swapping it in, so a broken build is never installed. +[[app]] +name = "kur" +repo = "Tahinli/kur" +asset = "kur-{arch}-linux" +path = "/usr/local/bin/kur" +check = ["--version"] diff --git a/deploy/kur.service b/deploy/kur.service new file mode 100644 index 0000000..fd96fc5 --- /dev/null +++ b/deploy/kur.service @@ -0,0 +1,30 @@ +[Unit] +Description=kur: install newest forge releases of configured apps +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +# Runs as root: it replaces binaries in /usr/local/bin and restarts units. +ExecStart=/usr/local/bin/kur run +Environment=KUR_CONFIG=/etc/kur/kur.toml +# /var/lib/kur, mode 0700 (.bad, .tag files). +StateDirectory=kur +StateDirectoryMode=0700 +# Installed binaries must be 0755. kur sets the mode itself, but keep the umask +# from making anything more private than that. +UMask=0022 + +# Light hardening only. ProtectSystem= is deliberately left unset: "strict" and +# "full" make /usr read-only, and /usr/local/bin is under /usr, so kur could not +# replace app binaries. PrivateTmp, ProtectHome and the rest do not touch +# /usr/local/bin or systemctl. +NoNewPrivileges=yes +PrivateTmp=yes +ProtectHome=yes +ProtectKernelTunables=yes +ProtectKernelModules=yes +ProtectKernelLogs=yes +ProtectControlGroups=yes +RestrictSUIDSGID=yes +LockPersonality=yes diff --git a/deploy/kur.timer b/deploy/kur.timer new file mode 100644 index 0000000..55f00e7 --- /dev/null +++ b/deploy/kur.timer @@ -0,0 +1,13 @@ +[Unit] +Description=Run kur every 5 minutes + +[Timer] +# First run 2 minutes after boot, then 5 minutes after each run starts. +OnBootSec=2min +OnUnitActiveSec=5min +RandomizedDelaySec=30s +# Do not catch up on missed runs after downtime. +Persistent=false + +[Install] +WantedBy=timers.target diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..9159220 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,237 @@ +//! Config file: TOML parsing, validation, and reading the forge token. + +use crate::{Res, migrate}; +use serde::Deserialize; +use std::collections::HashSet; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; + +/// Config path used when neither `--config` nor `KUR_CONFIG` is given. +pub const DEFAULT_PATH: &str = "/etc/kur/kur.toml"; +const DEFAULT_STATE_DIR: &str = "/var/lib/kur"; +/// Top-level keys; must match the `Raw` fields. +const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; +/// Keys in each `[[app]]` table; must match the `App` fields. +const KNOWN_APP_KEYS: &[&str] = &[ + "name", + "repo", + "asset", + "path", + "unit", + "prerelease", + "check", + "health_url", + "health_timeout_secs", +]; + +/// Raw TOML shape; `apps` comes from the `[[app]]` tables. +#[derive(Deserialize)] +struct Raw { + forge: String, + token_file: Option, + state_dir: Option, + #[serde(default, rename = "app")] + apps: Vec, +} + +/// One `[[app]]` table. +#[derive(Deserialize)] +pub struct App { + pub name: String, + pub repo: String, + pub asset: String, + pub path: PathBuf, + pub unit: Option, + #[serde(default)] + pub prerelease: bool, + pub check: Option>, + pub health_url: Option, + #[serde(default = "default_health_timeout")] + pub health_timeout_secs: u64, +} + +fn default_health_timeout() -> u64 { + 30 +} + +/// Validated configuration. +pub struct Config { + /// Forge base URL without a trailing slash. + pub forge: String, + /// Forge token, trimmed; sent only to forge URLs. + pub token: Option, + pub state_dir: PathBuf, + pub apps: Vec, + /// Non-fatal notices, such as unknown keys. + pub warnings: Vec, + /// One message per key renamed by `migrate::RENAMES`. + pub migrated: Vec, +} + +impl App { + /// Asset file name for this host, with `{arch}` expanded. + pub fn asset_name(&self) -> String { + self.asset.replace("{arch}", std::env::consts::ARCH) + } + + /// `path` with `suffix` appended, in the same directory (e.g. `.kur-new`, `.prev`). + pub fn sibling(&self, suffix: &str) -> PathBuf { + let mut name = self.path.clone().into_os_string(); + name.push(suffix); + PathBuf::from(name) + } +} + +/// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. +/// If anything was renamed and `write` is set, the file is rewritten once the config is valid. +pub fn load(path: &Path, write: bool) -> Res { + let mut text = + fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + // If the text does not parse, skip migration; the toml::from_str below reports the error. + let mut migrated = Vec::new(); + if let Ok(mut doc) = text.parse::() { + migrated = migrate::apply(&mut doc, migrate::RENAMES); + if !migrated.is_empty() { + text = doc.to_string(); + } + } + let table: toml::Table = + toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let mut warnings = unknown_key_warnings(&table); + let raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + + let forge = raw.forge.trim_end_matches('/').to_string(); + if !forge.starts_with("https://") && !forge.starts_with("http://") { + return Err("forge must start with https:// or http://".into()); + } + if raw.apps.is_empty() { + return Err("no [[app]] entries in config".into()); + } + let mut names = HashSet::new(); + for app in &raw.apps { + if !valid_name(&app.name) { + return Err(format!("invalid app name {:?}", app.name)); + } + if !names.insert(app.name.as_str()) { + return Err(format!("duplicate app name {}", app.name)); + } + let parts: Vec<&str> = app.repo.split('/').collect(); + if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { + return Err(format!("{}: repo must be owner/name", app.name)); + } + if !app.path.is_absolute() { + return Err(format!("{}: path must be absolute", app.name)); + } + } + + let token = raw.token_file.as_deref().map(read_token).transpose()?; + let state_dir = raw + .state_dir + .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_DIR)); + if !migrated.is_empty() + && write + && let Err(e) = rewrite_config(path, &text) + { + warnings.push(format!("could not rewrite config: {e}")); + } + Ok(Config { + forge, + token, + state_dir, + apps: raw.apps, + warnings, + migrated, + }) +} + +/// Replaces the config at `path` with `text`, keeping the original as `.bak`. +/// The temp file is removed if anything fails, and the original is left in place. +fn rewrite_config(path: &Path, text: &str) -> io::Result<()> { + let tmp = with_suffix(path, ".kur-tmp"); + let result = write_and_swap(path, &tmp, text); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +fn write_and_swap(path: &Path, tmp: &Path, text: &str) -> io::Result<()> { + // fs::copy keeps the original's permission bits on the backup. + fs::copy(path, with_suffix(path, ".bak"))?; + let perms = fs::metadata(path)?.permissions(); + // 0600 from creation, so the config is never readable by others before the final mode is set. + let mut file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(tmp)?; + file.write_all(text.as_bytes())?; + file.set_permissions(perms)?; + file.sync_all()?; + drop(file); + fs::rename(tmp, path)?; + let parent = match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + }; + fs::File::open(parent)?.sync_all() +} + +/// `path` with `suffix` appended to its file name. +fn with_suffix(path: &Path, suffix: &str) -> PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(suffix); + PathBuf::from(name) +} + +/// One warning per key that is not in the known lists, at the top level and in each `[[app]]`. +fn unknown_key_warnings(table: &toml::Table) -> Vec { + let mut warnings = Vec::new(); + for key in table.keys() { + if !KNOWN_TOP_KEYS.contains(&key.as_str()) { + warnings.push(format!("unknown key {key:?}")); + } + } + if let Some(toml::Value::Array(apps)) = table.get("app") { + for (index, app) in apps.iter().enumerate() { + let Some(app) = app.as_table() else { + continue; + }; + let label = match app.get("name").and_then(toml::Value::as_str) { + Some(name) => name.to_string(), + None => format!("#{}", index + 1), + }; + for key in app.keys() { + if !KNOWN_APP_KEYS.contains(&key.as_str()) { + warnings.push(format!("unknown key {key:?} in [[app]] {label}")); + } + } + } + } + warnings +} + +/// Matches `^[a-z0-9][a-z0-9_-]{0,39}$`. +fn valid_name(name: &str) -> bool { + let bytes = name.as_bytes(); + !bytes.is_empty() + && bytes.len() <= 40 + && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) + && bytes + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-') +} + +/// Reads the token file, trimmed. The token is never included in error messages. +fn read_token(path: &Path) -> Res { + let text = + fs::read_to_string(path).map_err(|e| format!("token_file {}: {e}", path.display()))?; + let token = text.trim(); + if token.is_empty() { + return Err(format!("token_file {} is empty", path.display())); + } + Ok(token.to_string()) +} diff --git a/src/forge.rs b/src/forge.rs new file mode 100644 index 0000000..2002fa3 --- /dev/null +++ b/src/forge.rs @@ -0,0 +1,146 @@ +//! Forge release API and streaming, hashed asset download. + +use crate::Res; +use crate::config::{App, Config}; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::time::Duration; +use ureq::http::Response; +use ureq::{Agent, Body}; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +const API_TIMEOUT: Duration = Duration::from_secs(30); +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600); +const MAX_DOWNLOAD: u64 = 1 << 30; +const MAX_API_BODY: u64 = 16 << 20; + +#[derive(Deserialize)] +struct Release { + tag: String, + draft: bool, + prerelease: bool, + assets: Vec, +} + +/// A downloadable file attached to a release. +#[derive(Deserialize)] +pub struct Asset { + name: String, + size: u64, + pub sha256: String, + download_url: String, +} + +/// Client for one forge. The token is attached only to URLs under the forge base. +pub struct Forge { + agent: Agent, + /// Forge base URL plus a trailing slash, for the token host check. + prefix: String, + token: Option, +} + +impl Forge { + pub fn new(cfg: &Config) -> Forge { + let agent = Agent::config_builder() + .timeout_connect(Some(CONNECT_TIMEOUT)) + .http_status_as_error(false) + .build() + .into(); + Forge { + agent, + prefix: format!("{}/", cfg.forge), + token: cfg.token.clone(), + } + } + + /// GET `url` with an overall timeout, adding the token if `url` is on the forge host. + fn get(&self, url: &str, timeout: Duration) -> Res> { + let mut req = self + .agent + .get(url) + .config() + .timeout_global(Some(timeout)) + .build(); + if let Some(token) = self + .token + .as_deref() + .filter(|_| url.starts_with(&self.prefix)) + { + req = req.header("Authorization", format!("token {token}")); + } + req.call().map_err(|e| format!("request failed: {e}")) + } + + /// Newest eligible release of the app's repo and its asset for this host, as `(tag, asset)`. + pub fn latest(&self, app: &App) -> Res<(String, Asset)> { + let url = format!("{}api/v1/repos/{}/releases", self.prefix, app.repo); + let mut resp = self.get(&url, API_TIMEOUT)?; + if !resp.status().is_success() { + return Err(format!("releases API returned {}", resp.status())); + } + let releases: Vec = + serde_json::from_reader(resp.body_mut().with_config().limit(MAX_API_BODY).reader()) + .map_err(|e| format!("bad releases JSON: {e}"))?; + + let Release { tag, assets, .. } = releases + .into_iter() + .find(|r| !r.draft && (app.prerelease || !r.prerelease)) + .ok_or("no release")?; + let want = app.asset_name(); + let asset = assets + .into_iter() + .find(|a| a.name == want) + .ok_or_else(|| format!("release {tag} has no asset {want}"))?; + if asset.sha256.len() != 64 + || !asset + .sha256 + .bytes() + .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) + { + return Err(format!("asset {want} has a malformed sha256")); + } + Ok((tag, asset)) + } + + /// Streams `asset` to `dest` (mode 0755, fsynced), failing on a hash mismatch or the size cap. + /// On error the caller removes `dest`. + pub fn download(&self, asset: &Asset, dest: &Path) -> Res<()> { + if asset.size > MAX_DOWNLOAD { + return Err(format!("asset {} is larger than 1 GiB", asset.name)); + } + let mut resp = self.get(&asset.download_url, DOWNLOAD_TIMEOUT)?; + if !resp.status().is_success() { + return Err(format!("download returned {}", resp.status())); + } + let mut body = resp.body_mut().with_config().limit(MAX_DOWNLOAD).reader(); + let mut file = File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = body + .read(&mut buf) + .map_err(|e| format!("download failed: {e}"))?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]) + .map_err(|e| format!("write {}: {e}", dest.display()))?; + } + file.set_permissions(fs::Permissions::from_mode(0o755)) + .and_then(|()| file.sync_all()) + .map_err(|e| format!("finalize {}: {e}", dest.display()))?; + let got = hex::encode(hasher.finalize()); + if got != asset.sha256 { + return Err(format!( + "sha256 mismatch for {} (expected {}, got {got})", + asset.name, asset.sha256 + )); + } + Ok(()) + } +} diff --git a/src/install.rs b/src/install.rs new file mode 100644 index 0000000..e40ccf0 --- /dev/null +++ b/src/install.rs @@ -0,0 +1,266 @@ +//! Per-app install flow: download, check, swap, restart, health check, rollback. +//! State files in `state_dir`: `{name}.bad` lists rejected sha256s, `{name}.tag` the last tag installed. + +use crate::Res; +use crate::config::{App, Config}; +use crate::forge::Forge; +use sha2::{Digest, Sha256}; +use std::fs::{self, File, OpenOptions}; +use std::io::{ErrorKind, Read, Write}; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +const CHECK_TIMEOUT: Duration = Duration::from_secs(10); +const HEALTH_REQUEST_TIMEOUT: Duration = Duration::from_secs(5); +const STABLE_FOR: Duration = Duration::from_secs(5); + +/// Creates the state directory (mode 0700) if it does not exist. +pub fn ensure_state_dir(dir: &Path) -> Res<()> { + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .map_err(|e| format!("state dir {}: {e}", dir.display())) +} + +/// Takes the exclusive run lock (`state_dir/lock`). Fails at once if another run holds it. +pub fn lock(dir: &Path) -> Res { + let path = dir.join("lock"); + let file = File::create(&path).map_err(|e| format!("open {}: {e}", path.display()))?; + file.try_lock() + .map_err(|_| "another kur run is in progress".to_string())?; + Ok(file) +} + +/// `kur status` text for one app (after the name). Changes nothing. +pub fn status(forge: &Forge, cfg: &Config, app: &App) -> Res { + let (tag, asset) = forge.latest(app)?; + let installed = file_sha256(&app.path)?; + let state = if installed.as_deref() == Some(asset.sha256.as_str()) { + "up to date" + } else if is_bad(cfg, app, &asset.sha256)? { + "skipped (bad build)" + } else { + "update available" + }; + let inst = match &installed { + Some(sha) => format!("installed {}", short(sha)), + None => "not installed".to_string(), + }; + Ok(format!( + "{inst}, newest {tag} {}: {state}", + short(&asset.sha256) + )) +} + +/// Installs the newest release of one app if needed. Returns the status text after the app name. +pub fn update(forge: &Forge, cfg: &Config, app: &App) -> Res { + let (tag, asset) = forge.latest(app)?; + if file_sha256(&app.path)?.as_deref() == Some(asset.sha256.as_str()) { + return Ok(format!("up to date ({tag})")); + } + if is_bad(cfg, app, &asset.sha256)? { + return Ok(format!("skipped (bad build {tag})")); + } + + let staged = app.sibling(".kur-new"); + let _ = fs::remove_file(&staged); + if let Err(e) = forge.download(&asset, &staged) { + let _ = fs::remove_file(&staged); + return Err(e); + } + if let Err(e) = check_binary(app, &staged) { + let _ = fs::remove_file(&staged); + mark_bad(cfg, app, &asset.sha256)?; + return Err(e); + } + swap(app, &staged)?; + + let Some(unit) = app.unit.as_deref() else { + write_tag(cfg, app, &tag)?; + return Ok(format!("{tag} installed")); + }; + match deploy(app, unit) { + Ok(()) => { + write_tag(cfg, app, &tag)?; + Ok(format!("{tag} installed")) + } + Err(reason) => { + let marked = mark_bad(cfg, app, &asset.sha256); + let mut msg = rollback(app, unit, &tag, &reason); + if let Err(e) = marked { + msg = format!("{msg}; could not record bad build: {e}"); + } + Err(msg) + } + } +} + +/// First 12 hex chars of a sha256, for display. +fn short(sha: &str) -> &str { + sha.get(..12).unwrap_or(sha) +} + +/// Lowercase hex sha256 of the file at `path`, or None if it does not exist. +fn file_sha256(path: &Path) -> Res> { + let mut file = match File::open(path) { + Ok(file) => file, + Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(format!("open {}: {e}", path.display())), + }; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = file + .read(&mut buf) + .map_err(|e| format!("read {}: {e}", path.display()))?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(Some(hex::encode(hasher.finalize()))) +} + +fn state_file(cfg: &Config, app: &App, ext: &str) -> PathBuf { + cfg.state_dir.join(format!("{}.{ext}", app.name)) +} + +/// Whether `sha` is listed in the app's `.bad` file. +fn is_bad(cfg: &Config, app: &App, sha: &str) -> Res { + match fs::read_to_string(state_file(cfg, app, "bad")) { + Ok(text) => Ok(text.lines().any(|line| line.trim() == sha)), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(false), + Err(e) => Err(format!("read bad list: {e}")), + } +} + +fn mark_bad(cfg: &Config, app: &App, sha: &str) -> Res<()> { + let path = state_file(cfg, app, "bad"); + let mut file = OpenOptions::new() + .create(true) + .append(true) + .open(&path) + .map_err(|e| format!("open {}: {e}", path.display()))?; + writeln!(file, "{sha}").map_err(|e| format!("write {}: {e}", path.display())) +} + +fn write_tag(cfg: &Config, app: &App, tag: &str) -> Res<()> { + let path = state_file(cfg, app, "tag"); + fs::write(&path, tag).map_err(|e| format!("write {}: {e}", path.display())) +} + +/// Runs the staged binary with the app's `check` args, if any. Fails on non-zero exit or timeout. +fn check_binary(app: &App, staged: &Path) -> Res<()> { + let Some(args) = &app.check else { + return Ok(()); + }; + let mut child = Command::new(staged) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| format!("cannot run staged binary: {e}"))?; + let deadline = Instant::now() + CHECK_TIMEOUT; + loop { + if let Some(status) = child.try_wait().map_err(|e| format!("check: {e}"))? { + return if status.success() { + Ok(()) + } else { + Err(format!("check exited with {status}")) + }; + } + if Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return Err("check timed out".into()); + } + sleep(Duration::from_millis(50)); + } +} + +/// Moves the current binary to `.prev` (if any) and the staged file into place, then fsyncs the dir. +fn swap(app: &App, staged: &Path) -> Res<()> { + match fs::rename(&app.path, app.sibling(".prev")) { + Err(e) if e.kind() != ErrorKind::NotFound => { + return Err(format!("keep previous {}: {e}", app.path.display())); + } + _ => {} + } + fs::rename(staged, &app.path).map_err(|e| format!("install {}: {e}", app.path.display()))?; + let dir = app.path.parent().unwrap_or(Path::new("/")); + File::open(dir) + .and_then(|d| d.sync_all()) + .map_err(|e| format!("fsync {}: {e}", dir.display())) +} + +/// Restarts `unit` and waits until it is active and healthy, then requires it to stay active. +/// Returns the failure reason on error. +fn deploy(app: &App, unit: &str) -> Result<(), String> { + restart(unit)?; + let deadline = Instant::now() + Duration::from_secs(app.health_timeout_secs); + while !(is_active(unit) && health_ok(app.health_url.as_deref())) { + if Instant::now() >= deadline { + return Err("health check timed out".into()); + } + sleep(Duration::from_secs(1)); + } + sleep(STABLE_FOR); + if !is_active(unit) { + return Err(format!("{unit} stopped after health check")); + } + Ok(()) +} + +/// Restores `.prev` over the failed binary and restarts the unit. Returns the error text. +fn rollback(app: &App, unit: &str, tag: &str, reason: &str) -> String { + let failed = format!("{tag} failed health check ({reason})"); + match fs::rename(app.sibling(".prev"), &app.path) { + Ok(()) => match restart(unit) { + Ok(()) => format!("{failed}, rolled back"), + Err(e) => format!("{failed}, rolled back but {e}"), + }, + Err(e) if e.kind() == ErrorKind::NotFound => { + format!("{failed}, no previous binary to restore") + } + Err(e) => format!("{failed}, restore failed: {e}"), + } +} + +/// True if `url` is unset or answers 2xx within the request timeout. No token is sent. +fn health_ok(url: Option<&str>) -> bool { + let Some(url) = url else { + return true; + }; + ureq::get(url) + .config() + .timeout_global(Some(HEALTH_REQUEST_TIMEOUT)) + .build() + .call() + .is_ok_and(|resp| resp.status().is_success()) +} + +fn restart(unit: &str) -> Result<(), String> { + systemctl(&["restart", unit]) +} + +fn is_active(unit: &str) -> bool { + systemctl(&["is-active", "--quiet", unit]).is_ok() +} + +fn systemctl(args: &[&str]) -> Result<(), String> { + let status = Command::new("systemctl") + .args(args) + .stdout(Stdio::null()) + .status() + .map_err(|e| format!("systemctl: {e}"))?; + if status.success() { + Ok(()) + } else { + Err(format!("systemctl {} failed", args.join(" "))) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..3a74a53 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,125 @@ +//! kur: installs the newest forge release of each configured app on this host, with rollback. +//! Runs from a systemd timer as root; prints one line per app on stdout, errors on stderr. + +mod config; +mod forge; +mod install; +mod migrate; + +use crate::config::{App, Config}; +use crate::forge::Forge; +use std::env; +use std::path::PathBuf; +use std::process::ExitCode; + +/// Crate-wide result type; errors are human-readable messages. +pub type Res = Result; + +const USAGE: &str = "usage: kur [--config ] + +commands: + run [app] install newer releases (all apps, or only ) + status show installed and newest releases; changes nothing + --version print the version +"; + +fn main() -> ExitCode { + let mut args = env::args().skip(1); + let mut config_path = env::var_os("KUR_CONFIG") + .map_or_else(|| PathBuf::from(config::DEFAULT_PATH), PathBuf::from); + let mut words = Vec::new(); + while let Some(arg) = args.next() { + match arg.as_str() { + "--config" => match args.next() { + Some(path) => config_path = path.into(), + None => return usage(), + }, + "--version" => { + println!("kur {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + _ => words.push(arg), + } + } + let words: Vec<&str> = words.iter().map(String::as_str).collect(); + let (only, status) = match words.as_slice() { + ["run"] => (None, false), + ["run", name] => (Some(*name), false), + ["status"] => (None, true), + _ => return usage(), + }; + + // Status never writes, so a renamed key is only reported. + let cfg = match config::load(&config_path, !status) { + Ok(cfg) => cfg, + Err(e) => { + eprintln!("kur: {e}"); + return ExitCode::FAILURE; + } + }; + let note = if status { + " (not written, status changes nothing)" + } else { + "" + }; + for message in &cfg.migrated { + println!("kur: config: {message}{note}"); + } + for warning in &cfg.warnings { + eprintln!("kur: warning: {warning}"); + } + let apps: Vec<&App> = cfg + .apps + .iter() + .filter(|app| only.is_none_or(|name| app.name == name)) + .collect(); + if apps.is_empty() { + eprintln!("kur: no app named {}", only.unwrap_or_default()); + return ExitCode::FAILURE; + } + // Held until exit, so a manual `kur run` and a timer run never stage the same files at once. + let _lock = if status { + None + } else { + match install::ensure_state_dir(&cfg.state_dir).and_then(|()| install::lock(&cfg.state_dir)) + { + Ok(lock) => Some(lock), + Err(e) => { + eprintln!("kur: {e}"); + return ExitCode::FAILURE; + } + } + }; + process_apps(&cfg, &apps, status) +} + +/// Runs status or update for each app. One app failing never stops the others. +fn process_apps(cfg: &Config, apps: &[&App], status: bool) -> ExitCode { + let forge = Forge::new(cfg); + let mut failed = false; + for app in apps { + let result = if status { + install::status(&forge, cfg, app) + } else { + install::update(&forge, cfg, app) + }; + match result { + Ok(msg) => println!("{}: {msg}", app.name), + Err(e) => { + eprintln!("kur: {}: {e}", app.name); + failed = true; + } + } + } + if failed { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + } +} + +/// Prints usage and returns exit code 2 (bad invocation). +fn usage() -> ExitCode { + eprint!("{USAGE}"); + ExitCode::from(2) +} diff --git a/src/migrate.rs b/src/migrate.rs new file mode 100644 index 0000000..0c2613d --- /dev/null +++ b/src/migrate.rs @@ -0,0 +1,127 @@ +//! Config key renames. Old configs keep working, and `kur run` rewrites them to the new names. + +use toml_edit::{DocumentMut, Item, Key, Table}; + +/// Where a rename applies. +// Nothing is renamed yet, so no entry constructs these variants. +#[allow(dead_code)] +#[derive(Clone, Copy)] +pub enum Scope { + /// The root table. + Top, + /// Every table in the `[[app]]` array. + App, +} + +/// `(scope, old name, new name)`. Add an entry here when a key is renamed, never remove one. +/// Also add the new name to `KNOWN_TOP_KEYS` or `KNOWN_APP_KEYS` in `config.rs`. +/// +/// Example, for an `[[app]]` key `health_wait` renamed to `health_timeout_secs`: +/// ```text +/// (Scope::App, "health_wait", "health_timeout_secs"), +/// ``` +pub const RENAMES: &[(Scope, &str, &str)] = &[]; + +/// What happened to the old key in one table. +enum Change { + Renamed, + Dropped, +} + +/// Renames keys in `doc` in place and returns one message per change. +/// +/// A renamed key keeps its value, its position in the table, and its comments. If the new name +/// is already set in the same table, the old key is removed instead. +pub fn apply(doc: &mut DocumentMut, renames: &[(Scope, &str, &str)]) -> Vec { + let mut messages = Vec::new(); + for &(scope, old, new) in renames { + match scope { + Scope::Top => { + if let Some(change) = rename_key(doc.as_table_mut(), old, new) { + messages.push(describe(&change, old, new, None)); + } + } + Scope::App => { + let Some(apps) = doc + .get_mut("app") + .and_then(|item| item.as_array_of_tables_mut()) + else { + continue; + }; + for (index, table) in apps.iter_mut().enumerate() { + let label = app_label(table, index); + if let Some(change) = rename_key(table, old, new) { + messages.push(describe(&change, old, new, Some(&label))); + } + } + } + } + } + messages +} + +/// The `name` of an `[[app]]` table, or `#<1-based index>` if it has none. +fn app_label(table: &Table, index: usize) -> String { + match table.get("name").and_then(Item::as_str) { + Some(name) => name.to_string(), + None => format!("#{}", index + 1), + } +} + +/// Renames `old` to `new` in `table`, keeping the key's position and decor. Returns `None` if +/// `old` is not set. +fn rename_key(table: &mut Table, old: &str, new: &str) -> Option { + if !table.contains_key(old) { + return None; + } + if table.contains_key(new) { + table.remove(old); + return Some(Change::Dropped); + } + // toml_edit cannot change a key's name in place, so take every entry out in order and + // insert them back, with the renamed key where the old one was. + let names: Vec = table.iter().map(|(key, _)| key.to_string()).collect(); + let entries: Vec<(Key, Item)> = names + .iter() + .filter_map(|name| table.remove_entry(name)) + .collect(); + for (key, item) in entries { + if key.get() == old { + let renamed = Key::new(new).with_leaf_decor(key.leaf_decor().clone()); + table.insert_formatted(&renamed, item); + } else { + table.insert_formatted(&key, item); + } + } + Some(Change::Renamed) +} + +fn describe(change: &Change, old: &str, new: &str, app: Option<&str>) -> String { + let location = app + .map(|label| format!(" in [[app]] {label}")) + .unwrap_or_default(); + match change { + Change::Renamed => format!("renamed {old:?} to {new:?}{location}"), + Change::Dropped => format!("dropped {old:?} (already set as {new:?}){location}"), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renames_app_key_keeping_comment_value_and_position() { + let text = "forge = \"https://x\"\n\n[[app]]\nname = \"im\"\n# how often\nold_key = 5\nrepo = \"a/b\"\n"; + let mut doc: DocumentMut = text.parse().unwrap(); + let renames = [(Scope::App, "old_key", "new_key")]; + let messages = apply(&mut doc, &renames); + let out = doc.to_string(); + assert!(out.contains("# how often\nnew_key = 5\nrepo"), "{out}"); + assert!(!out.contains("old_key"), "{out}"); + assert_eq!( + messages, + ["renamed \"old_key\" to \"new_key\" in [[app]] im"] + ); + } +}