diff --git a/.github/workflows/ci-kube.yml b/.github/workflows/ci-kube.yml new file mode 100644 index 0000000..93a98a0 --- /dev/null +++ b/.github/workflows/ci-kube.yml @@ -0,0 +1,116 @@ +name: edgelet-kube CI + +on: + push: + branches: [ main, develop, edgelet-kube/** ] + paths: + - 'kube/**' + - '.github/workflows/ci-kube.yml' + pull_request: + branches: [ main, develop, edgelet-kube/** ] + paths: + - 'kube/**' + - '.github/workflows/ci-kube.yml' + workflow_dispatch: + +permissions: read-all + +env: + GO_VERSION: '1.26.11' + GOWORK: 'off' + +jobs: + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: go vet + run: make vet-kube + + - name: golangci-lint + uses: golangci/golangci-lint-action@82606bf257cbaff209d206a39f5134f0cfbfd2ee # v9.2.1 + with: + version: v2.12.2 + working-directory: kube + args: --timeout=5m0s --config=.golangci.yaml + + - name: Static security analysis + working-directory: kube + run: | + if ! command -v gosec >/dev/null 2>&1; then + go install github.com/securego/gosec/v2/cmd/gosec@latest + fi + GOWORK=off gosec ./cmd/... ./internal/... + + build: + name: Build linux/amd64 + runs-on: ubuntu-latest + needs: [lint] + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: Test dispatch + working-directory: kube + run: go test ./internal/... -skip '^TestChildUsesRuntimePaths$' + + - name: Test containerd runtime paths + working-directory: kube + run: | + go test -c -o /tmp/containerd.test ./internal/containerd/ + sudo /tmp/containerd.test -test.count=1 -test.v -test.run '^TestChildUsesRuntimePaths$' + + - name: Aux build dependencies + run: sudo TARGETARCH=amd64 ./scripts/install-embed-build-deps + + - name: Build linux/amd64 + working-directory: kube + run: bash scripts/build.sh + + - name: Extract and exec + working-directory: kube + run: bash scripts/smoke.sh + + build-arm64: + name: Build linux/arm64 + runs-on: ubuntu-24.04-arm + needs: [lint] + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: Aux build dependencies + run: sudo TARGETARCH=arm64 ./scripts/install-embed-build-deps + + - name: Build linux/arm64 + working-directory: kube + env: + ARCH: arm64 + run: bash scripts/build.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 279cb34..1729e20 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,8 @@ on: - 'sbom.cdx.json' - 'sbom.spdx.json' - 'licensegen/**' + - '!kube/**' + - '!.github/workflows/ci-kube.yml' pull_request: branches: [ main, develop, edgelet/** ] paths: @@ -43,12 +45,14 @@ on: - 'sbom.cdx.json' - 'sbom.spdx.json' - 'licensegen/**' + - '!kube/**' + - '!.github/workflows/ci-kube.yml' workflow_dispatch: permissions: read-all env: - GO_VERSION: '1.26.10' + GO_VERSION: '1.26.11' jobs: lint: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 838d358..350b8c9 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -9,7 +9,7 @@ on: permissions: read-all env: - GO_VERSION: '1.26.10' + GO_VERSION: '1.26.11' jobs: analyze: diff --git a/.github/workflows/conformance-kube.yml b/.github/workflows/conformance-kube.yml new file mode 100644 index 0000000..06ccff0 --- /dev/null +++ b/.github/workflows/conformance-kube.yml @@ -0,0 +1,171 @@ +name: edgelet-kube conformance + +on: + workflow_dispatch: + push: + tags: + - 'edgelet-kube-v*\+edgelet*' + +permissions: read-all + +env: + GO_VERSION: '1.26.11' + GOWORK: 'off' + +jobs: + artifacts: + name: linux/amd64 release artifacts + runs-on: ubuntu-latest + timeout-minutes: 90 + permissions: + contents: read + actions: write + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: Free disk + run: | + sudo rm -rf \ + /usr/local/lib/android \ + /usr/share/dotnet \ + /opt/hostedtoolcache/CodeQL \ + /usr/share/swift \ + /usr/local/.ghcup || true + df -h + + - name: Aux build dependencies + run: sudo TARGETARCH=amd64 ./scripts/install-embed-build-deps + + - name: Build thin binary + working-directory: kube + run: bash scripts/build.sh + + - name: Reported version is the Kubernetes patch + working-directory: kube + env: + REF_NAME: ${{ github.ref_name }} + run: | + set -euo pipefail + pin=$(awk '$1 == "kubernetes" { print $2; exit }' scripts/airgap/pins.txt) + test -n "$pin" + test -f build/edgelet-kube-server + info=$(go version -m build/edgelet-kube-server) + # Both component-base and client-go are stamped on one ldflags line. + count=$(printf '%s\n' "$info" | grep -o -F "version.gitVersion=${pin}" | wc -l | tr -d ' ' || true) + test "$count" -ge 2 + if printf '%s\n' "$info" | grep -F -q "gitVersion=${REF_NAME}"; then + echo "git tag ${REF_NAME} was stamped as gitVersion" >&2 + exit 1 + fi + + - name: Stage thin binary + run: | + set -euo pipefail + test -f kube/build/edgelet-kube + mkdir -p dist + install -m 0755 kube/build/edgelet-kube dist/edgelet-kube-linux-amd64 + + - name: Start containerd + run: | + set -euo pipefail + if ! command -v ctr >/dev/null 2>&1; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends containerd + fi + if ! sudo ctr version >/dev/null 2>&1; then + sudo systemctl enable --now containerd + fi + sudo ctr version + + - name: Package airgap archive + working-directory: kube + env: + ARCH: amd64 + run: | + set -euo pipefail + sudo env \ + PATH="$PATH" \ + ARCH="$ARCH" \ + GOWORK=off \ + GOCACHE="$(go env GOCACHE)" \ + GOMODCACHE="$(go env GOMODCACHE)" \ + GOPATH="$(go env GOPATH)" \ + bash scripts/package-airgap + test -f build/edgelet-kube-airgap-images-amd64.tar.zst + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: edgelet-kube-linux-amd64 + path: dist/edgelet-kube-linux-amd64 + if-no-files-found: error + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: edgelet-kube-airgap-images-amd64.tar.zst + path: kube/build/edgelet-kube-airgap-images-amd64.tar.zst + if-no-files-found: error + compression-level: 0 + + conformance: + name: certified-conformance + runs-on: ubuntu-latest + needs: [artifacts] + timeout-minutes: 240 + permissions: + contents: read + actions: write + env: + CONFORMANCE_TIMEOUT_MINUTES: "240" + SONOBUOY_MODE: certified-conformance + RELEASE_NAME: ${{ github.ref_name }} + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: edgelet-kube-* + merge-multiple: true + path: dist + + - name: Free disk + run: | + sudo rm -rf \ + /usr/local/lib/android \ + /usr/share/dotnet \ + /opt/hostedtoolcache/CodeQL \ + /usr/share/swift \ + /usr/local/.ghcup || true + df -h + test -f dist/edgelet-kube-linux-amd64 + test -f dist/edgelet-kube-airgap-images-amd64.tar.zst + + - name: Run certified-conformance + env: + CONFORMANCE_RESULTS: ${{ github.workspace }}/sonobuoy-results.tar.gz + run: | + bash kube/scripts/conformance.sh \ + --binary="${GITHUB_WORKSPACE}/dist/edgelet-kube-linux-amd64" \ + --images="${GITHUB_WORKSPACE}/dist/edgelet-kube-airgap-images-amd64.tar.zst" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + if: always() + with: + name: sonobuoy-results + path: sonobuoy-results.tar.gz + if-no-files-found: ignore diff --git a/.github/workflows/govulncheck.yml b/.github/workflows/govulncheck.yml index 1236d75..1129205 100644 --- a/.github/workflows/govulncheck.yml +++ b/.github/workflows/govulncheck.yml @@ -11,7 +11,7 @@ on: permissions: read-all env: - GO_VERSION: '1.26.10' + GO_VERSION: '1.26.11' jobs: govulncheck: diff --git a/.github/workflows/release-kube.yml b/.github/workflows/release-kube.yml new file mode 100644 index 0000000..7aa290d --- /dev/null +++ b/.github/workflows/release-kube.yml @@ -0,0 +1,286 @@ +name: Release kube + +on: + push: + tags: + - 'edgelet-kube-v*\+edgelet*' + +env: + GO_VERSION: '1.26.11' + GOWORK: 'off' + +permissions: read-all + +jobs: + build: + name: Linux ${{ matrix.arch }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-latest + - arch: arm64 + runner: ubuntu-24.04-arm + - arch: arm + runner: ubuntu-latest + cross: true + - arch: riscv64 + runner: ubuntu-latest + cross: true + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: Aux build dependencies + if: matrix.cross != true + run: sudo TARGETARCH=${{ matrix.arch }} ./scripts/install-embed-build-deps + + - name: Build thin binary + if: matrix.cross != true + working-directory: kube + env: + ARCH: ${{ matrix.arch }} + run: bash scripts/build.sh + + - name: Build thin binary (cross) + if: matrix.cross == true + run: | + set -euo pipefail + docker build -f build/Dockerfile.embedded -t edgelet-embed-ci . + docker run --rm \ + -e GOFLAGS=-buildvcs=false \ + -e GOWORK=off \ + -e ARCH=${{ matrix.arch }} \ + -v "$PWD:/src" -w /src \ + edgelet-embed-ci \ + bash kube/scripts/build.sh + + - name: Reported version is the Kubernetes patch + working-directory: kube + env: + REF_NAME: ${{ github.ref_name }} + run: | + set -euo pipefail + pin=$(awk '$1 == "kubernetes" { print $2; exit }' scripts/airgap/pins.txt) + test -n "$pin" + test -f build/edgelet-kube-server + info=$(go version -m build/edgelet-kube-server) + # Both component-base and client-go are stamped on one ldflags line. + count=$(printf '%s\n' "$info" | grep -o -F "version.gitVersion=${pin}" | wc -l | tr -d ' ' || true) + test "$count" -ge 2 + if printf '%s\n' "$info" | grep -F -q "gitVersion=${REF_NAME}"; then + echo "git tag ${REF_NAME} was stamped as gitVersion" >&2 + exit 1 + fi + + - name: Stage thin binary + env: + ARCH: ${{ matrix.arch }} + run: | + set -euo pipefail + test -f kube/build/edgelet-kube + mkdir -p dist + install -m 0755 kube/build/edgelet-kube "dist/edgelet-kube-linux-${ARCH}" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: edgelet-kube-linux-${{ matrix.arch }} + path: dist/edgelet-kube-linux-${{ matrix.arch }} + if-no-files-found: error + + airgap: + name: Airgap ${{ matrix.arch }} + runs-on: ${{ matrix.runner }} + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-latest + - arch: arm64 + runner: ubuntu-24.04-arm + - arch: arm + runner: ubuntu-latest + - arch: riscv64 + runner: ubuntu-latest + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: ${{ env.GO_VERSION }} + cache-dependency-path: kube/go.sum + + - name: No Go workspace + run: test ! -f go.work + + - name: Start containerd + run: | + set -euo pipefail + if ! command -v ctr >/dev/null 2>&1; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends containerd + fi + if ! sudo ctr version >/dev/null 2>&1; then + sudo systemctl enable --now containerd + fi + sudo ctr version + + - name: Package airgap archive + working-directory: kube + env: + ARCH: ${{ matrix.arch }} + run: | + set -euo pipefail + sudo env \ + PATH="$PATH" \ + ARCH="$ARCH" \ + GOWORK=off \ + GOCACHE="$(go env GOCACHE)" \ + GOMODCACHE="$(go env GOMODCACHE)" \ + GOPATH="$(go env GOPATH)" \ + bash scripts/package-airgap + test -f "build/edgelet-kube-airgap-images-${ARCH}.tar.zst" + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: edgelet-kube-airgap-images-${{ matrix.arch }}.tar.zst + path: kube/build/edgelet-kube-airgap-images-${{ matrix.arch }}.tar.zst + if-no-files-found: error + compression-level: 0 + + package: + name: Package release assets + runs-on: ubuntu-latest + needs: [build, airgap] + steps: + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: edgelet-kube-* + merge-multiple: true + path: artifacts + + - name: Build SHA256SUMS + run: | + set -euo pipefail + mkdir -p dist + find artifacts -type f -name 'edgelet-kube-*' -exec cp -t dist {} + + chmod 0755 \ + dist/edgelet-kube-linux-amd64 \ + dist/edgelet-kube-linux-arm64 \ + dist/edgelet-kube-linux-arm \ + dist/edgelet-kube-linux-riscv64 + ( + cd dist + sha256sum \ + edgelet-kube-linux-amd64 \ + edgelet-kube-linux-arm64 \ + edgelet-kube-linux-arm \ + edgelet-kube-linux-riscv64 \ + edgelet-kube-airgap-images-amd64.tar.zst \ + edgelet-kube-airgap-images-arm64.tar.zst \ + edgelet-kube-airgap-images-arm.tar.zst \ + edgelet-kube-airgap-images-riscv64.tar.zst \ + > SHA256SUMS + ) + find dist -type f -printf '%f\n' | sort > /tmp/assets.txt + printf '%s\n' \ + SHA256SUMS \ + edgelet-kube-airgap-images-amd64.tar.zst \ + edgelet-kube-airgap-images-arm64.tar.zst \ + edgelet-kube-airgap-images-arm.tar.zst \ + edgelet-kube-airgap-images-riscv64.tar.zst \ + edgelet-kube-linux-amd64 \ + edgelet-kube-linux-arm64 \ + edgelet-kube-linux-arm \ + edgelet-kube-linux-riscv64 \ + | sort > /tmp/want.txt + diff -u /tmp/want.txt /tmp/assets.txt + ls -la dist/ + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: release-dist + path: dist/* + if-no-files-found: error + + github-release: + name: GitHub Release + runs-on: ubuntu-latest + needs: package + permissions: + contents: write + id-token: write + steps: + - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + with: + fetch-depth: 0 + + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: release-dist + path: dist + + - name: Install cosign + uses: sigstore/cosign-installer@6f9f17788090df1f26f669e9d70d6ae9567deba6 # v4.1.2 + + - name: Sign release artifacts (keyless cosign) + run: | + set -euo pipefail + for f in dist/*; do + case "$(basename "$f")" in + *.pem|*.sigstore) continue ;; + esac + [ -f "$f" ] || continue + cosign sign-blob --yes \ + --bundle "${f}.sigstore" \ + "$f" + done + shopt -s nullglob + bundles=(dist/*.sigstore) + test "${#bundles[@]}" -gt 0 + ls -la dist/ + + - name: Generate release notes + env: + GH_TOKEN: ${{ github.token }} + REF_NAME: ${{ github.ref_name }} + run: | + set -euo pipefail + gh api "repos/${GITHUB_REPOSITORY}/releases/generate-notes" \ + -f tag_name="${REF_NAME}" \ + -f target_commitish="${GITHUB_SHA}" \ + --jq '.body' > release_notes.md + printf '%s\n' \ + '' \ + '## Downloads' \ + '' \ + 'Thin binaries, the airgap image archives, and `SHA256SUMS`. Each file has a keyless cosign bundle.' \ + '' \ + '- `edgelet-kube-linux-amd64`' \ + '- `edgelet-kube-linux-arm64`' \ + '- `edgelet-kube-linux-arm`' \ + '- `edgelet-kube-linux-riscv64`' \ + '- `edgelet-kube-airgap-images-amd64.tar.zst`' \ + '- `edgelet-kube-airgap-images-arm64.tar.zst`' \ + '- `edgelet-kube-airgap-images-arm.tar.zst`' \ + '- `edgelet-kube-airgap-images-riscv64.tar.zst`' \ + '- `SHA256SUMS`' \ + >> release_notes.md + + - uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3.0.0 + with: + body_path: release_notes.md + files: dist/* + draft: false + # The product prefix contains a hyphen. A release is a pre-release only when the tag also contains -rc or -beta. + prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d923353..1018472 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,9 +4,11 @@ on: push: tags: - 'v*' + - '!edgelet-kube-*' + - '!*\+edgelet*' env: - GO_VERSION: '1.26.10' + GO_VERSION: '1.26.11' REGISTRY: ghcr.io IMAGE: ${{ vars.EDGELET_CONTAINER_IMAGE }} DEBUGGER_IMAGE: ${{ vars.DEBUGGER_CONTAINER_IMAGE }} diff --git a/.gitignore b/.gitignore index 0d0742c..0b9b2bd 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,8 @@ build/data-staging/ build/images/ build/*.tar pkg/data/embed/*.tar.zst +kube/cmd/edgelet-kube/embed/*.tar.zst +kube/build/ dist/ diff --git a/.golangci.yaml b/.golangci.yaml index b459f12..69f96e0 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -1,5 +1,5 @@ # golangci-lint configuration for Edgelet -# Target: Go 1.26.10, module github.com/eclipse-iofog/edgelet +# Target: Go 1.26.11, module github.com/eclipse-iofog/edgelet version: "2" diff --git a/CHANGELOG.md b/CHANGELOG.md index ac717ab..c8bdb92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,8 +17,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Embedded runtime:** containerd fork **v2.3.7-k3s1**, cri-api **v1.37.2-k3s1**, crun **1.30.1**, and k3s-root **v0.15.4**, matching the current k3s tree. - **Security / vulncheck:** bump `golang.org/x/net` to **v0.62.0** (with `golang.org/x/crypto` **v0.58.0** and `golang.org/x/text` **v0.43.0**) for **GO-2026-6866** and **GO-2026-6860**. Bump `github.com/klauspost/compress` to **v1.20.3** for **GHSA-fpmh-frq8-7rj8**. Bump `oras.land/oras-go/v2` to **v2.7.0** for the auth and file-store fixes; private bearer token realms stay allowed. Bump indirect `github.com/go-jose/go-jose/v4` to **v4.1.6** for **GHSA-4w3g-jfj2-cw2q**, **GHSA-vvm8-gf78-28g4**, and **GHSA-mgcc-cww5-fp2q**. These are on the Linux OCI image-encryption path (`ocicrypt` JWE). - **Go dependencies:** `golang.org/x/sync` **v0.24.0**. No edgelet API changes. Regenerated `SBOM.md`, `LICENSE-3RD-PARTY.md`, `sbom.cdx.json`, and `sbom.spdx.json`. +- **Go 1.26.11** minimum (see `go.mod`). CI and the govulncheck workflow use the same toolchain. Clears [GO-2026-6859](https://pkg.go.dev/vuln/GO-2026-6859) ( HTTP/1 server crash due to MaxBytesReader header race in `net/http`). +- Image digests refreshed for `golang:1.26-trixie`. ## [v1.1.3] diff --git a/Dockerfile b/Dockerfile index 2c9d7c0..13adaca 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,7 @@ # --build-arg VERSION=v0.0.0-test \ # -t ghcr.io/eclipse-iofog/edgelet:test . -FROM golang:1.26.10-trixie@sha256:7202554ed358a37f41c44e4910ae29bbc5ef0715f289ac637218adbb0ca132dd AS builder +FROM golang:1.26-trixie@sha256:19ce7a1fdc59527aa568805ea100c380900d059d251e914fb86e11fd0ce68952 AS builder ARG BUILDARCH ARG TARGETARCH @@ -42,7 +42,7 @@ RUN set -eux; \ test -f "build/out/data-linux-${ARCH}.tar.zst" # Unpack embed bundle + minimal rootfs. -FROM alpine:3.22@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 AS base +FROM alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f AS base RUN apk add --no-cache ca-certificates zstd tzdata ARG TARGETARCH ARG VERSION=dev diff --git a/Dockerfile.debugger b/Dockerfile.debugger index c1ae4eb..1fb0055 100644 --- a/Dockerfile.debugger +++ b/Dockerfile.debugger @@ -1,4 +1,4 @@ -FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 +FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf RUN apk add --no-cache util-linux diff --git a/LICENSE-3RD-PARTY.md b/LICENSE-3RD-PARTY.md index 0b9c501..0039c0f 100644 --- a/LICENSE-3RD-PARTY.md +++ b/LICENSE-3RD-PARTY.md @@ -11,7 +11,7 @@ GPL components are BusyBox, iproute2, iptables, nftables, ebtables, util-linux ( Components: - busybox@— (GPL-2.0-only) -- crun@1.28 (GPL-2.0-or-later) +- crun@1.30.1 (GPL-2.0-or-later) - ebtables@— (GPL-2.0-only) - iproute2@— (GPL-2.0-only) - iptables@— (GPL-2.0-or-later) @@ -364,7 +364,7 @@ Public License instead of this License. Components: -- Go@1.26.10 (BSD-3-Clause) +- Go@1.26.11 (BSD-3-Clause) - golang.org/x/crypto@v0.58.0 (BSD-3-Clause) - golang.org/x/exp/typeparams@v0.0.0-20260209203927-2842357ff358 (BSD-3-Clause) - golang.org/x/exp@v0.0.0-20241108190413-2d47ceb2692f (BSD-3-Clause) @@ -412,10 +412,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Components: -- k3s-root (amd64)@v0.15.0 (NOASSERTION) -- k3s-root (arm)@v0.15.0 (NOASSERTION) -- k3s-root (arm64)@v0.15.0 (NOASSERTION) -- k3s-root (riscv64)@v0.15.0 (NOASSERTION) +- k3s-root (amd64)@v0.15.4 (NOASSERTION) +- k3s-root (arm)@v0.15.4 (NOASSERTION) +- k3s-root (arm64)@v0.15.4 (NOASSERTION) +- k3s-root (riscv64)@v0.15.4 (NOASSERTION) ``` The k3s-root source repository at this tag is Apache-2.0 (https://github.com/k3s-io/k3s-root). That license covers the build scripts and Buildroot config. It does not license the programs inside the tarball. Those programs are the contained GPL components. @@ -460,7 +460,7 @@ uncontaminated with licensed code from other projects. Components: - cni-plugins@v1.9.1-k3s1 (Apache-2.0) -- containerd-shim-runc-v2@v2.3.2-k3s2 (Apache-2.0) +- containerd-shim-runc-v2@v2.3.7-k3s1 (Apache-2.0) - portainer/pause@sha256:df6d2fb5cff97c4070a12953a34a56422879f1e02b43400f1caf1cbd530458b1 (Apache-2.0) Standard SPDX identifier. Module copies of this license are included under their own text when the module ships a LICENSE file. @@ -691,9 +691,18 @@ Components: - github.com/containerd/zfs/v2@v2.0.0 (Apache-2.0) - github.com/envoyproxy/protoc-gen-validate@v1.3.3 (Apache-2.0) - github.com/go-jose/go-jose/v4@v4.1.6 (Apache-2.0) -- github.com/go-openapi/jsonpointer@v0.21.0 (Apache-2.0) -- github.com/go-openapi/jsonreference@v0.20.2 (Apache-2.0) -- github.com/go-openapi/swag@v0.23.0 (Apache-2.0) +- github.com/go-openapi/swag/cmdutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/conv@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/fileutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/jsonutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/loading@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/mangling@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/netutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/pools@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/stringutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/typeutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag/yamlutils@v0.27.1 (Apache-2.0) +- github.com/go-openapi/swag@v0.27.1 (Apache-2.0) - github.com/golang/mock@v1.1.1 (Apache-2.0) - github.com/google/btree@v1.1.3 (Apache-2.0) - github.com/google/certtostore@v1.0.6 (Apache-2.0) @@ -720,14 +729,14 @@ Components: - google.golang.org/genproto/googleapis/rpc@v0.0.0-20260706201446-f0a921348800 (Apache-2.0) - google.golang.org/genproto@v0.0.0-20200526211855-cb27e3aa2013 (Apache-2.0) - google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1 (Apache-2.0) -- k8s.io/api@v0.36.2 (Apache-2.0) -- k8s.io/apimachinery@v0.36.2 (Apache-2.0) -- k8s.io/client-go@v0.36.2 (Apache-2.0) -- k8s.io/component-base@v0.36.2 (Apache-2.0) -- k8s.io/cri-streaming@v0.36.2 (Apache-2.0) -- k8s.io/kube-openapi@v0.0.0-20260319004828-5883c5ee87b9 (Apache-2.0) -- k8s.io/streaming@v0.36.2 (Apache-2.0) -- k8s.io/utils@v0.0.0-20260319190234-28399d86e0b5 (Apache-2.0) +- k8s.io/api@v0.37.1 (Apache-2.0) +- k8s.io/apimachinery@v0.37.1 (Apache-2.0) +- k8s.io/client-go@v0.37.1 (Apache-2.0) +- k8s.io/component-base@v0.37.1 (Apache-2.0) +- k8s.io/cri-streaming@v0.37.1 (Apache-2.0) +- k8s.io/kube-openapi@v0.0.0-20260721132016-d427ff9ee9ad (Apache-2.0) +- k8s.io/streaming@v0.37.1 (Apache-2.0) +- k8s.io/utils@v0.0.0-20260626114624-be93311217bd (Apache-2.0) ``` @@ -2701,14 +2710,14 @@ Components: - github.com/envoyproxy/go-control-plane/ratelimit@v0.1.0 (Apache-2.0) - github.com/envoyproxy/go-control-plane@v0.14.0 (Apache-2.0) - github.com/go-logr/logr@v1.4.3 (Apache-2.0) -- github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.36.2-k3s2 (Apache-2.0) +- github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.37.2-k3s1 (Apache-2.0) - github.com/mwitkow/go-conntrack@v0.0.0-20190716064945-2f068394615f (Apache-2.0) - github.com/opencontainers/cgroups@v0.0.4 (Apache-2.0) - github.com/opencontainers/selinux@v1.13.1 (Apache-2.0) - github.com/sasha-s/go-deadlock@v0.3.5 (Apache-2.0) - github.com/yashtewari/glob-intersection@v0.2.0 (Apache-2.0) -- k8s.io/cri-client@v0.36.2 (Apache-2.0) -- sigs.k8s.io/structured-merge-diff/v6@v6.3.2 (Apache-2.0) +- k8s.io/cri-client@v0.37.1 (Apache-2.0) +- sigs.k8s.io/structured-merge-diff/v6@v6.4.2 (Apache-2.0) ``` Apache License @@ -3055,7 +3064,7 @@ Components: - github.com/containerd/fuse-overlayfs-snapshotter/v2@v2.1.7 (Apache-2.0) - github.com/containerd/imgcrypt/v2@v2.0.3 (Apache-2.0) - github.com/containerd/log@v0.1.0 (Apache-2.0) -- github.com/containerd/platforms@v1.0.0-rc.4 (Apache-2.0) +- github.com/containerd/platforms@v1.0.0-rc.5 (Apache-2.0) - github.com/containerd/plugin@v1.1.0 (Apache-2.0) - github.com/containerd/typeurl/v2@v2.3.0 (Apache-2.0) @@ -6615,7 +6624,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Components: -- github.com/fxamacker/cbor/v2@v2.9.0 (MIT) +- github.com/fxamacker/cbor/v2@v2.9.1 (MIT) ``` MIT License @@ -6933,6 +6942,511 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` +## Apache-2.0 + +Components: + +- github.com/go-openapi/jsonpointer@v1.0.0 (Apache-2.0) + +``` +--- LICENSE --- + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +--- NOTICE --- +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonpointer, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigu-399/jsonpointer +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + +## Apache-2.0 + +Components: + +- github.com/go-openapi/jsonreference@v1.0.0 (Apache-2.0) + +``` +--- LICENSE --- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +--- NOTICE --- +Copyright 2015-2025 go-swagger maintainers + +// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers +// SPDX-License-Identifier: Apache-2.0 + +This software library, github.com/go-openapi/jsonreference, includes software developed +by the go-swagger and go-openapi maintainers ("go-swagger maintainers"). + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this software except in compliance with the License. + +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0. + +This software is copied from, derived from, and inspired by other original software products. +It ships with copies of other software which license terms are recalled below. + +The original software was authored on 25-02-2013 by sigu-399 (https://github.com/sigu-399, sigu.399@gmail.com). + +github.com/sigh-399/jsonreference +=========================== + +// SPDX-FileCopyrightText: Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) +// SPDX-License-Identifier: Apache-2.0 + +Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +``` + ## MIT Components: @@ -8260,7 +8774,7 @@ Components: Components: -- github.com/grpc-ecosystem/grpc-gateway/v2@v2.28.0 (BSD-3-Clause) +- github.com/grpc-ecosystem/grpc-gateway/v2@v2.29.0 (BSD-3-Clause) ``` Copyright (c) 2015, Gengo, Inc. @@ -10457,36 +10971,6 @@ SOFTWARE. Components: -- github.com/josharian/intern@v1.0.0 (MIT) - -``` -MIT License - -Copyright (c) 2019 Josh Bleecher Snyder - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` - -## MIT - -Components: - - github.com/josharian/native@v1.1.0 (MIT) ``` @@ -10620,7 +11104,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Components: -- github.com/k3s-io/containerd/v2@v2.3.2-k3s2 (Apache-2.0) +- github.com/k3s-io/containerd/v2@v2.3.7-k3s1 (Apache-2.0) ``` --- LICENSE --- @@ -11467,22 +11951,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Components: -- github.com/mailru/easyjson@v0.7.7 (MIT) - -``` -Copyright (c) 2016 Mail.Ru Group - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` - -## MIT - -Components: - - github.com/mattn/go-colorable@v0.1.2 (MIT) ``` @@ -14621,7 +15089,7 @@ SOFTWARE. Components: -- github.com/prometheus/client_golang@v1.23.2 (Apache-2.0) +- github.com/prometheus/client_golang@v1.24.0 (Apache-2.0) ``` --- LICENSE --- @@ -15070,7 +15538,7 @@ SoundCloud Ltd. (http://soundcloud.com/). Components: -- github.com/prometheus/common@v0.67.5 (Apache-2.0) +- github.com/prometheus/common@v0.70.0 (Apache-2.0) ``` --- LICENSE --- @@ -15288,7 +15756,7 @@ SoundCloud Ltd. (http://soundcloud.com/). Components: -- github.com/prometheus/procfs@v0.19.2 (Apache-2.0) +- github.com/prometheus/procfs@v0.21.1 (Apache-2.0) ``` --- LICENSE --- @@ -16681,7 +17149,7 @@ SOFTWARE. Components: -- github.com/stretchr/objx@v0.5.2 (MIT) +- github.com/stretchr/objx@v0.5.3 (MIT) ``` The MIT License @@ -18432,9 +18900,9 @@ Components: - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.69.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc@v1.42.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp@v1.42.0 (Apache-2.0 OR BSD-3-Clause) -- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc@v1.43.0 (Apache-2.0 OR BSD-3-Clause) +- go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc@v1.44.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp@v1.43.0 (Apache-2.0 OR BSD-3-Clause) -- go.opentelemetry.io/otel/exporters/otlp/otlptrace@v1.43.0 (Apache-2.0 OR BSD-3-Clause) +- go.opentelemetry.io/otel/exporters/otlp/otlptrace@v1.44.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/exporters/prometheus@v0.60.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/exporters/stdout/stdoutmetric@v1.42.0 (Apache-2.0 OR BSD-3-Clause) - go.opentelemetry.io/otel/metric@v1.44.0 (Apache-2.0 OR BSD-3-Clause) @@ -18739,7 +19207,7 @@ THE SOFTWARE. Components: -- go.yaml.in/yaml/v2@v2.4.3 (Apache-2.0) +- go.yaml.in/yaml/v2@v2.4.4 (Apache-2.0) - gopkg.in/yaml.v2@v2.4.0 (Apache-2.0) ``` diff --git a/Makefile b/Makefile index 5b9dc5b..c541467 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: build build-cli build-daemon build-daemon-embedded build-edgelet build-edgelet-linux build-edgelet-local deps test test-linux test-linux-race test-linux-race-arm64 test-linux-race-amd64 test-race lint lint-fix clean docker-build install install-dev start-dev stop-dev setup-dev-env export-dev-env fmt vet static staticcheck staticcheck-standalone install-staticcheck help build-all-archs build-release-matrix build-linux-amd64 build-linux-arm64 build-linux-arm build-linux-riscv64 release-binaries build-desktop-darwin build-desktop-windows test-embedded test-embedded-ci cli-docs cli-docs-check cli-help-check cli-completion test-embedded-docker ci-docker quality-linux quality-linux-arm64 quality-linux-amd64 install-scripts install-scripts-check test-lifecycle test-lifecycle-race test-deadlock pre-it +.PHONY: build build-cli build-daemon build-daemon-embedded build-edgelet build-edgelet-linux build-edgelet-local deps test test-linux test-linux-race test-linux-race-arm64 test-linux-race-amd64 test-race lint lint-fix clean docker-build install install-dev start-dev stop-dev setup-dev-env export-dev-env fmt vet static staticcheck staticcheck-standalone install-staticcheck help build-all-archs build-release-matrix build-linux-amd64 build-linux-arm64 build-linux-arm build-linux-riscv64 release-binaries build-desktop-darwin build-desktop-windows test-embedded test-embedded-ci cli-docs cli-docs-check cli-help-check cli-completion test-embedded-docker ci-docker quality-linux quality-linux-arm64 quality-linux-amd64 vet-kube lint-kube quality-linux-kube install-scripts install-scripts-check test-lifecycle test-lifecycle-race test-deadlock pre-it GOBIN ?= $(shell go env GOBIN) ifeq ($(GOBIN),) @@ -542,9 +542,10 @@ build-size: build ## Show binary sizes @echo "Binary sizes:" @ls -lh build/edgelet* 2>/dev/null | awk '{print $$5 "\t" $$9}' || true -# Security tooling — pinned govulncheck; gosec scoped to edgelet module trees only. +# Security tooling — pinned govulncheck; gosec on the root module, then the kube module. GOVULNCHECK_VERSION ?= v1.1.4 GOSEC_SCOPE := ./cmd/... ./internal/... ./pkg/... +GOSEC_KUBE_SCOPE := ./cmd/... ./internal/... vulncheck: ## Run dependency vulnerability scan (govulncheck + go mod verify) @echo "🔐 Running govulncheck..." @@ -564,6 +565,20 @@ security-code: ## Run static Go security analysis (gosec) go install github.com/securego/gosec/v2/cmd/gosec@latest; \ fi @gosec -exclude-dir=build $(GOSEC_SCOPE) + @echo "🔍 Running Go static security analysis (kube)..." + @cd kube && GOWORK=off gosec $(GOSEC_KUBE_SCOPE) + +vet-kube: ## Run go vet in the kube module + @echo "Running go vet (kube)..." + @cd kube && GOWORK=off go vet ./... + +lint-kube: $(GOLANGCI_LINT) ## Run golangci-lint in the kube module + @echo "Running golangci-lint $(GOLANGCI_LINT_VERSION) (kube)..." + @cd kube && GOWORK=off $(GOLANGCI_LINT) run --config .golangci.yaml + +quality-linux-kube: ## Vet and lint the kube module (Docker on macOS) + @chmod +x kube/scripts/quality-linux.sh + @kube/scripts/quality-linux.sh quality-linux-arm64: test-linux ## Run test-linux and then lint, vulncheck, security-code in Linux arm64 Docker @chmod +x scripts/quality-linux.sh diff --git a/SBOM.md b/SBOM.md index af55113..6b09391 100644 --- a/SBOM.md +++ b/SBOM.md @@ -16,7 +16,7 @@ Container image attestations are not in this document. | optional | Compiled into tests only | | excluded | Present in `go list -m all` and compiled into nothing here | -Required 169, optional 0, excluded 223. +Required 169, optional 0, excluded 232. ## Inventory @@ -26,17 +26,17 @@ Required 169, optional 0, excluded 223. | --- | --- | --- | --- | | busybox | — | GPL-2.0-only | linux | | ebtables | — | GPL-2.0-only | linux | -| Go | 1.26.10 | BSD-3-Clause | — | +| Go | 1.26.11 | BSD-3-Clause | — | | iproute2 | — | GPL-2.0-only | linux | | iptables | — | GPL-2.0-or-later | linux | -| k3s-root (amd64) | v0.15.0 | NOASSERTION | linux | -| k3s-root (arm) | v0.15.0 | NOASSERTION | linux | -| k3s-root (arm64) | v0.15.0 | NOASSERTION | linux | -| k3s-root (riscv64) | v0.15.0 | NOASSERTION | linux | +| k3s-root (amd64) | v0.15.4 | NOASSERTION | linux | +| k3s-root (arm) | v0.15.4 | NOASSERTION | linux | +| k3s-root (arm64) | v0.15.4 | NOASSERTION | linux | +| k3s-root (riscv64) | v0.15.4 | NOASSERTION | linux | | nftables | — | GPL-2.0-only | linux | | SQLite | 3.53.4 | LicenseRef-SQLite-PublicDomain | darwin, linux-fat, windows | | util-linux | — | GPL-2.0-or-later | linux | -| crun | 1.28 | GPL-2.0-or-later | linux | +| crun | 1.30.1 | GPL-2.0-or-later | linux | | cni-plugins | v1.9.1-k3s1 | Apache-2.0 | linux | | dario.cat/mergo | v1.0.2 | BSD-3-Clause | linux-fat | | github.com/Microsoft/go-winio | v0.6.3-0.20251027160822-ad3df93bed29 | MIT | windows | @@ -63,7 +63,7 @@ Required 169, optional 0, excluded 223. | github.com/containerd/log | v0.1.0 | Apache-2.0 | linux-fat | | github.com/containerd/nri | v0.12.0 | Apache-2.0 | linux-fat | | github.com/containerd/otelttrpc | v0.1.0 | Apache-2.0 | linux-fat | -| github.com/containerd/platforms | v1.0.0-rc.4 | Apache-2.0 | linux-fat | +| github.com/containerd/platforms | v1.0.0-rc.5 | Apache-2.0 | linux-fat | | github.com/containerd/plugin | v1.1.0 | Apache-2.0 | linux-fat | | github.com/containerd/ttrpc | v1.2.8 | Apache-2.0 | linux-fat | | github.com/containerd/typeurl/v2 | v2.3.0 | Apache-2.0 | linux-fat | @@ -85,7 +85,7 @@ Required 169, optional 0, excluded 223. | github.com/fatih/color | v1.7.0 | MIT | darwin, linux-thin, windows | | github.com/felixge/httpsnoop | v1.1.0 | MIT | darwin, linux-fat, windows | | github.com/fsnotify/fsnotify | v1.10.1 | BSD-3-Clause | darwin, linux-fat, linux-thin, windows | -| github.com/fxamacker/cbor/v2 | v2.9.0 | MIT | linux-fat | +| github.com/fxamacker/cbor/v2 | v2.9.1 | MIT | linux-fat | | github.com/go-jose/go-jose/v4 | v4.1.6 | Apache-2.0 | linux-fat | | github.com/go-logr/logr | v1.4.3 | Apache-2.0 | darwin, linux-fat, windows | | github.com/go-logr/stdr | v1.2.2 | Apache-2.0 | darwin, linux-fat, windows | @@ -98,9 +98,9 @@ Required 169, optional 0, excluded 223. | github.com/grpc-ecosystem/go-grpc-middleware/v2 | v2.1.0 | Apache-2.0 | linux-fat | | github.com/inconshreveable/mousetrap | v1.1.0 | Apache-2.0 | windows | | github.com/intel/goresctrl | v0.12.0 | Apache-2.0 | linux-fat | -| github.com/k3s-io/containerd/v2 | v2.3.2-k3s2 | Apache-2.0 | linux-fat | -| containerd-shim-runc-v2 | v2.3.2-k3s2 | Apache-2.0 | linux | -| github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api | v1.36.2-k3s2 | Apache-2.0 | linux-fat | +| github.com/k3s-io/containerd/v2 | v2.3.7-k3s1 | Apache-2.0 | linux-fat | +| containerd-shim-runc-v2 | v2.3.7-k3s1 | Apache-2.0 | linux | +| github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api | v1.37.2-k3s1 | Apache-2.0 | linux-fat | | github.com/klauspost/compress | v1.20.3 | Apache-2.0 OR BSD-3-Clause OR MIT | linux-fat, linux-thin | | github.com/knqyf263/go-plugin | v0.9.0 | MIT | linux-fat | | github.com/mattn/go-colorable | v0.1.2 | MIT | darwin, linux-thin, windows | @@ -130,10 +130,10 @@ Required 169, optional 0, excluded 223. | github.com/opencontainers/selinux | v1.13.1 | Apache-2.0 | linux-fat | | github.com/pelletier/go-toml/v2 | v2.3.0 | MIT | linux-fat | | github.com/pelletier/go-toml | v1.9.5 | Apache-2.0 OR MIT | darwin, linux-fat, windows | -| github.com/prometheus/client_golang | v1.23.2 | Apache-2.0 | linux-fat | +| github.com/prometheus/client_golang | v1.24.0 | Apache-2.0 | linux-fat | | github.com/prometheus/client_model | v0.6.2 | Apache-2.0 | linux-fat | -| github.com/prometheus/common | v0.67.5 | Apache-2.0 | linux-fat | -| github.com/prometheus/procfs | v0.19.2 | Apache-2.0 | linux-fat | +| github.com/prometheus/common | v0.70.0 | Apache-2.0 | linux-fat | +| github.com/prometheus/procfs | v0.21.1 | Apache-2.0 | linux-fat | | github.com/remyoudompheng/bigfft | v0.0.0-20230129092748-24d4a6f8daec | BSD-3-Clause | darwin, linux-fat, windows | | github.com/russross/blackfriday/v2 | v2.1.0 | BSD-2-Clause | darwin, linux-fat, linux-thin, windows | | github.com/shirou/gopsutil/v4 | v4.26.9 | BSD-3-Clause | darwin, linux-fat, windows | @@ -161,7 +161,7 @@ Required 169, optional 0, excluded 223. | go.opentelemetry.io/otel/metric | v1.44.0 | Apache-2.0 OR BSD-3-Clause | darwin, linux-fat, windows | | go.opentelemetry.io/otel/trace | v1.44.0 | Apache-2.0 OR BSD-3-Clause | darwin, linux-fat, windows | | go.opentelemetry.io/otel | v1.44.0 | Apache-2.0 OR BSD-3-Clause | darwin, linux-fat, windows | -| go.yaml.in/yaml/v2 | v2.4.3 | Apache-2.0 | linux-fat | +| go.yaml.in/yaml/v2 | v2.4.4 | Apache-2.0 | linux-fat | | go.yaml.in/yaml/v3 | v3.0.5 | Apache-2.0 OR MIT | darwin, linux-fat, linux-thin, windows | | golang.org/x/crypto | v0.58.0 | BSD-3-Clause | darwin, linux-fat, windows | | golang.org/x/mod | v0.41.0 | BSD-3-Clause | linux-fat | @@ -177,12 +177,12 @@ Required 169, optional 0, excluded 223. | gopkg.in/inf.v0 | v0.9.1 | BSD-3-Clause | linux-fat | | gopkg.in/tomb.v1 | v1.0.0-20141024135613-dd632973f1e7 | BSD-3-Clause | linux-fat | | gopkg.in/yaml.v3 | v3.0.1 | Apache-2.0 OR MIT | darwin, linux-fat, linux-thin, windows | -| k8s.io/apimachinery | v0.36.2 | Apache-2.0 | linux-fat | -| k8s.io/client-go | v0.36.2 | Apache-2.0 | linux-fat | -| k8s.io/cri-streaming | v0.36.2 | Apache-2.0 | linux-fat | +| k8s.io/apimachinery | v0.37.1 | Apache-2.0 | linux-fat | +| k8s.io/client-go | v0.37.1 | Apache-2.0 | linux-fat | +| k8s.io/cri-streaming | v0.37.1 | Apache-2.0 | linux-fat | | k8s.io/klog/v2 | v2.140.0 | Apache-2.0 | linux-fat | -| k8s.io/streaming | v0.36.2 | Apache-2.0 | linux-fat | -| k8s.io/utils | v0.0.0-20260319190234-28399d86e0b5 | Apache-2.0 | linux-fat | +| k8s.io/streaming | v0.37.1 | Apache-2.0 | linux-fat | +| k8s.io/utils | v0.0.0-20260626114624-be93311217bd | Apache-2.0 | linux-fat | | modernc.org/libc | v1.77.1 | BSD-3-Clause | darwin, linux-fat, windows | | modernc.org/mathutil | v1.7.1 | BSD-3-Clause | darwin, linux-fat, windows | | modernc.org/memory | v1.12.1 | BSD-3-Clause | darwin, linux-fat, windows | @@ -259,9 +259,20 @@ Required 169, optional 0, excluded 223. | github.com/go-ini/ini | v1.67.0 | Apache-2.0 | — | | github.com/go-kit/kit | v0.8.0 | MIT | — | | github.com/go-logfmt/logfmt | v0.4.0 | MIT | — | -| github.com/go-openapi/jsonpointer | v0.21.0 | Apache-2.0 | — | -| github.com/go-openapi/jsonreference | v0.20.2 | Apache-2.0 | — | -| github.com/go-openapi/swag | v0.23.0 | Apache-2.0 | — | +| github.com/go-openapi/jsonpointer | v1.0.0 | Apache-2.0 | — | +| github.com/go-openapi/jsonreference | v1.0.0 | Apache-2.0 | — | +| github.com/go-openapi/swag/cmdutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/conv | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/fileutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/jsonutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/loading | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/mangling | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/netutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/pools | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/stringutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/typeutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag/yamlutils | v0.27.1 | Apache-2.0 | — | +| github.com/go-openapi/swag | v0.27.1 | Apache-2.0 | — | | github.com/go-quicktest/qt | v1.101.1-0.20240301121107-c6c8733fa1e6 | MIT | — | | github.com/go-stack/stack | v1.8.0 | MIT | — | | github.com/go-task/slim-sprig/v3 | v3.0.0 | MIT | — | @@ -286,7 +297,7 @@ Required 169, optional 0, excluded 223. | github.com/googleapis/gax-go/v2 | v2.17.0 | BSD-3-Clause | — | | github.com/gorilla/mux | v1.8.1 | BSD-3-Clause | — | | github.com/grafana/regexp | v0.0.0-20240518133315-a468a5bfb3bc | BSD-3-Clause | — | -| github.com/grpc-ecosystem/grpc-gateway/v2 | v2.28.0 | BSD-3-Clause | — | +| github.com/grpc-ecosystem/grpc-gateway/v2 | v2.29.0 | BSD-3-Clause | — | | github.com/hanwen/go-fuse/v2 | v2.9.0 | BSD-3-Clause | — | | github.com/hashicorp/errwrap | v1.1.0 | MPL-2.0 | — | | github.com/hashicorp/go-cleanhttp | v0.5.2 | MPL-2.0 | — | @@ -295,7 +306,6 @@ Required 169, optional 0, excluded 223. | github.com/hashicorp/golang-lru/v2 | v2.0.7 | MPL-2.0 | — | | github.com/insomniacslk/dhcp | v0.0.0-20240829085014-a3a4c1f04475 | BSD-3-Clause | — | | github.com/josephspurrier/goversioninfo | v1.5.0 | MIT | — | -| github.com/josharian/intern | v1.0.0 | MIT | — | | github.com/josharian/native | v1.1.0 | MIT | — | | github.com/jpillora/backoff | v1.0.0 | MIT | — | | github.com/jsimonetti/rtnetlink/v2 | v2.0.1 | MIT | — | @@ -315,7 +325,6 @@ Required 169, optional 0, excluded 223. | github.com/lestrrat-go/option | v1.0.1 | MIT | — | | github.com/linuxkit/virtsock | v0.0.0-20241009230534-cb6a20cc0422 | Apache-2.0 | — | | github.com/lufia/plan9stats | v0.0.0-20211012122336-39d0f177ccd0 | BSD-3-Clause | — | -| github.com/mailru/easyjson | v0.7.7 | MIT | — | | github.com/mattn/go-shellwords | v1.0.12 | MIT | — | | github.com/matttproud/golang_protobuf_extensions | v1.0.1 | Apache-2.0 | — | | github.com/mdlayher/netlink | v1.7.2 | MIT | — | @@ -355,7 +364,7 @@ Required 169, optional 0, excluded 223. | github.com/seccomp/libseccomp-golang | v0.10.0 | BSD-2-Clause | — | | github.com/spiffe/go-spiffe/v2 | v2.7.0 | Apache-2.0 | — | | github.com/stoewer/go-strcase | v1.3.0 | MIT | — | -| github.com/stretchr/objx | v0.5.2 | MIT | — | +| github.com/stretchr/objx | v0.5.3 | MIT | — | | github.com/stretchr/testify | v1.12.1 | MIT | — | | github.com/u-root/uio | v0.0.0-20240224005618-d2acac8f3701 | BSD-3-Clause | — | | github.com/ulikunitz/xz | v0.5.15 | BSD-2-Clause | — | @@ -374,9 +383,9 @@ Required 169, optional 0, excluded 223. | go.opentelemetry.io/contrib/detectors/gcp | v1.44.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc | v1.42.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp | v1.42.0 | Apache-2.0 OR BSD-3-Clause | — | -| go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc | v1.43.0 | Apache-2.0 OR BSD-3-Clause | — | +| go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc | v1.44.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp | v1.43.0 | Apache-2.0 OR BSD-3-Clause | — | -| go.opentelemetry.io/otel/exporters/otlp/otlptrace | v1.43.0 | Apache-2.0 OR BSD-3-Clause | — | +| go.opentelemetry.io/otel/exporters/otlp/otlptrace | v1.44.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/exporters/prometheus | v0.60.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/exporters/stdout/stdoutmetric | v1.42.0 | Apache-2.0 OR BSD-3-Clause | — | | go.opentelemetry.io/otel/sdk/metric | v1.44.0 | Apache-2.0 OR BSD-3-Clause | — | @@ -403,10 +412,10 @@ Required 169, optional 0, excluded 223. | gopkg.in/yaml.v2 | v2.4.0 | Apache-2.0 | — | | gotest.tools/v3 | v3.5.2 | Apache-2.0 | — | | honnef.co/go/tools | v0.7.0 | BSD-3-Clause OR MIT | — | -| k8s.io/api | v0.36.2 | Apache-2.0 | — | -| k8s.io/component-base | v0.36.2 | Apache-2.0 | — | -| k8s.io/cri-client | v0.36.2 | Apache-2.0 | — | -| k8s.io/kube-openapi | v0.0.0-20260319004828-5883c5ee87b9 | Apache-2.0 | — | +| k8s.io/api | v0.37.1 | Apache-2.0 | — | +| k8s.io/component-base | v0.37.1 | Apache-2.0 | — | +| k8s.io/cri-client | v0.37.1 | Apache-2.0 | — | +| k8s.io/kube-openapi | v0.0.0-20260721132016-d427ff9ee9ad | Apache-2.0 | — | | modernc.org/cc/v4 | v4.29.7 | BSD-3-Clause | — | | modernc.org/ccgo/v4 | v4.36.1 | BSD-3-Clause | — | | modernc.org/fileutil | v1.4.0 | BSD-3-Clause | — | @@ -420,7 +429,7 @@ Required 169, optional 0, excluded 223. | pgregory.net/rapid | v1.2.0 | MPL-2.0 | — | | sigs.k8s.io/knftables | v0.0.18 | Apache-2.0 | — | | sigs.k8s.io/randfill | v1.0.0 | Apache-2.0 | — | -| sigs.k8s.io/structured-merge-diff/v6 | v6.3.2 | Apache-2.0 | — | +| sigs.k8s.io/structured-merge-diff/v6 | v6.4.2 | Apache-2.0 | — | ## Embed bundle diff --git a/build/Dockerfile.embedded b/build/Dockerfile.embedded index 123b7e2..7785396 100644 --- a/build/Dockerfile.embedded +++ b/build/Dockerfile.embedded @@ -2,7 +2,7 @@ # macOS dev: # docker build -f build/Dockerfile.embedded -t edgelet-embed-ci . # docker run --rm -v "$(pwd)":/src -w /src edgelet-embed-ci ./scripts/ci -FROM golang:1.26.10-trixie@sha256:909771fef53e3dcb0950255f0c9a8b4728c3b841e61509c7b29b098de7ee02d4 +FROM golang:1.26-trixie@sha256:19ce7a1fdc59527aa568805ea100c380900d059d251e914fb86e11fd0ce68952 COPY scripts/install-embed-build-deps /usr/local/bin/install-embed-build-deps RUN chmod +x /usr/local/bin/install-embed-build-deps \ diff --git a/go.mod b/go.mod index 0c56a73..c1eaa7d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/eclipse-iofog/edgelet -go 1.26.10 +go 1.26.11 require ( github.com/bmatcuk/doublestar/v4 v4.10.3 @@ -37,7 +37,7 @@ require ( golang.org/x/term v0.47.0 google.golang.org/grpc v1.83.2 gopkg.in/yaml.v3 v3.0.1 - k8s.io/cri-api v0.36.2 + k8s.io/cri-api v0.37.1 modernc.org/sqlite v1.60.1 oras.land/oras-go/v2 v2.7.0 ) @@ -65,7 +65,7 @@ require ( github.com/containerd/log v0.1.0 // indirect github.com/containerd/nri v0.12.0 // indirect github.com/containerd/otelttrpc v0.1.0 // indirect - github.com/containerd/platforms v1.0.0-rc.4 // indirect + github.com/containerd/platforms v1.0.0-rc.5 // indirect github.com/containerd/plugin v1.1.0 // indirect github.com/containerd/ttrpc v1.2.8 // indirect github.com/containernetworking/cni v1.3.0 // indirect @@ -85,7 +85,7 @@ require ( github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/fatih/color v1.7.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect - github.com/fxamacker/cbor/v2 v2.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-jose/go-jose/v4 v4.1.6 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect @@ -122,10 +122,10 @@ require ( github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect + github.com/prometheus/client_golang v1.24.0 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.19.2 // indirect + github.com/prometheus/common v0.70.0 // indirect + github.com/prometheus/procfs v0.21.1 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sasha-s/go-deadlock v0.3.5 // indirect @@ -150,7 +150,7 @@ require ( go.opentelemetry.io/otel v1.44.0 // indirect go.opentelemetry.io/otel/metric v1.44.0 // indirect go.opentelemetry.io/otel/trace v1.44.0 // indirect - go.yaml.in/yaml/v2 v2.4.3 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/mod v0.41.0 // indirect golang.org/x/net v0.62.0 // indirect @@ -161,12 +161,12 @@ require ( google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect - k8s.io/apimachinery v0.36.2 // indirect - k8s.io/client-go v0.36.2 // indirect - k8s.io/cri-streaming v0.36.2 // indirect + k8s.io/apimachinery v0.37.1 // indirect + k8s.io/client-go v0.37.1 // indirect + k8s.io/cri-streaming v0.37.1 // indirect k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/streaming v0.36.2 // indirect - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 // indirect + k8s.io/streaming v0.37.1 // indirect + k8s.io/utils v0.0.0-20260626114624-be93311217bd // indirect modernc.org/libc v1.77.1 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect @@ -178,7 +178,7 @@ require ( replace ( github.com/containerd/containerd/api => github.com/containerd/containerd/api v1.11.1 - github.com/containerd/containerd/v2 => github.com/k3s-io/containerd/v2 v2.3.2-k3s2 + github.com/containerd/containerd/v2 => github.com/k3s-io/containerd/v2 v2.3.7-k3s1 - k8s.io/cri-api => github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.36.2-k3s2 + k8s.io/cri-api => github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1 ) diff --git a/go.sum b/go.sum index d7164bb..cd5f00b 100644 --- a/go.sum +++ b/go.sum @@ -71,8 +71,8 @@ github.com/containerd/nri v0.12.0 h1:RvZtyCM64XOB1UmMAFOlfReTTwCd+hE2IEQ5XEpkKA0 github.com/containerd/nri v0.12.0/go.mod h1:TGAfPLH4a+qwbv0PxsefPiR+PobYecDj2aXMtz7GQcg= github.com/containerd/otelttrpc v0.1.0 h1:UOX68eVTE8H/T45JveIg+I22Ev2aFj4qPITCmXsskjw= github.com/containerd/otelttrpc v0.1.0/go.mod h1:XhoA2VvaGPW1clB2ULwrBZfXVuEWuyOd2NUD1IM0yTg= -github.com/containerd/platforms v1.0.0-rc.4 h1:M42JrUT4zfZTqtkUwkr0GzmUWbfyO5VO0Q5b3op97T4= -github.com/containerd/platforms v1.0.0-rc.4/go.mod h1:lKlMXyLybmBedS/JJm11uDofzI8L2v0J2ZbYvNsbq1A= +github.com/containerd/platforms v1.0.0-rc.5 h1:vXd569rDrz8LeMXzAnBsy6LADV5YtsD8oyaRarxdmSU= +github.com/containerd/platforms v1.0.0-rc.5/go.mod h1:lKlMXyLybmBedS/JJm11uDofzI8L2v0J2ZbYvNsbq1A= github.com/containerd/plugin v1.1.0 h1:O+7lczNJVMy8rz0YNx3xGB8tTf5qY4i5abF041Ew19U= github.com/containerd/plugin v1.1.0/go.mod h1:qBTum+A8lJ6lO44A19Eo7y1OlcLj4OWFH1DA/vnHmcc= github.com/containerd/ttrpc v1.2.8 h1:xbVu6D4qF2jihdh9rDVOKqUMiFBQk6YctTdo1zk087Y= @@ -125,8 +125,8 @@ github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= -github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= -github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= +github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= @@ -209,10 +209,10 @@ github.com/jsimonetti/rtnetlink/v2 v2.0.1/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsT github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/k3s-io/containerd/v2 v2.3.2-k3s2 h1:d+bZCem1meQ6dhRmSmm/QCvSsCRiwGz3T9Z87ds3Fck= -github.com/k3s-io/containerd/v2 v2.3.2-k3s2/go.mod h1:w0vk2xH0tWd9lLZyBeYQdbs8ITcWqAIVQcraVInLarM= -github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.36.2-k3s2 h1:YYohH3LUebcOeSI6DZdAPBrElFlWkBC/LZ8WoKHEvCQ= -github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.36.2-k3s2/go.mod h1:1gMX7udEAiRCWGS4uxscdbxq6vufwhZt38Ri+XH6P00= +github.com/k3s-io/containerd/v2 v2.3.7-k3s1 h1:ofqwSFvzR4IixfgpDUAEdhFpcW2nio8Lapm2CNdRYPg= +github.com/k3s-io/containerd/v2 v2.3.7-k3s1/go.mod h1:Ht5zD+4jdudh/ODrXGVJoFVs2BkiUeTuxOhHtHFSYWs= +github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1 h1:TsMLMSe0ahpSZFqjFUH9Dyh5uQSvNBBk8yth4Z3h1MU= +github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1/go.mod h1:6V8Gb6wznJYVPToj8CLxgbxsFeeGIswNZCE7cy+xT90= github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/knqyf263/go-plugin v0.9.0 h1:CQs2+lOPIlkZVtcb835ZYDEoyyWJWLbSTWeCs0EwTwI= @@ -307,8 +307,8 @@ github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:Om github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_golang v1.24.0 h1:5XStIklKuAtJSNpdD3s8XJj/Yv78IQmE1kbNk87JrAI= +github.com/prometheus/client_golang v1.24.0/go.mod h1:QcsNdotprC2nS4BTM2ucbcqxd2CeXTEa9jW7zHO9iDE= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -316,13 +316,13 @@ github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNw github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= +github.com/prometheus/common v0.70.0 h1:bcpru3tWPVnxGnETLgOV5jbp/JRXgYEyv65CuBLAMMI= +github.com/prometheus/common v0.70.0/go.mod h1:S/SFasQmgGiYH6C81LKCtYa8QACgthGg5zxL2udV7SY= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= -github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws= -github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw= +github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= +github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= @@ -349,8 +349,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= @@ -414,8 +414,8 @@ go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= -go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0= -go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= @@ -578,18 +578,18 @@ gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -k8s.io/apimachinery v0.36.2 h1:0PE/W/WNy1UX61NLbXY5TMbJ6UwLL6E6lAPkYrKFxbQ= -k8s.io/apimachinery v0.36.2/go.mod h1:fvf/HOLXq9RId0rnDIbN1OEBvHXdQbLMM8nu0LcBUf4= -k8s.io/client-go v0.36.2 h1:bfgxmFKc9CgqsgX4xKLAAdmTQlWee7Ob/HlDOrJ5TBI= -k8s.io/client-go v0.36.2/go.mod h1:1vgO4OAlfPnoLcb+Rze2GF5rAr14w8qjrYMoyXJzQj0= -k8s.io/cri-streaming v0.36.2 h1:1eXIgzl3XYA3ObqK73Ii+6VoEooaUdmX8jI6AsnjqrI= -k8s.io/cri-streaming v0.36.2/go.mod h1:myni055WrrzVdEVXN1b9OIZqUXy17NzEHLUVoixaH8w= +k8s.io/apimachinery v0.37.1 h1:hGCYyvKHCwtwMitj2vU4vYx0Z16N9GyZk9BBnz0wDAE= +k8s.io/apimachinery v0.37.1/go.mod h1:jF84AyUi/IRIXRot5f+lm6MpxoWI+F1XgjaMmwCdTFw= +k8s.io/client-go v0.37.1 h1:QTv/5ha4jAHtW9qxxVBkQVFBRDb4jHfFopQqqMdc+wM= +k8s.io/client-go v0.37.1/go.mod h1:dnAPtTnCNY38Ho04D2KdY1F4IKausa9UbqaAZKl60SY= +k8s.io/cri-streaming v0.37.1 h1:Yop1OqAUkoFeF0ZXwRo8HKM9+JtfLJrnsB16yfDMvMQ= +k8s.io/cri-streaming v0.37.1/go.mod h1:Hk737tU6Hz1yWB2pQrvGcTJkYlW83q161kgZdFN/k3I= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/streaming v0.36.2 h1:NSKthPPg9UFSKsRauVJUVGH2Dvn8fhKmY4qrMkw/p98= -k8s.io/streaming v0.36.2/go.mod h1:z6fV3D+NVkoeqRMtWwlUZK6U17SY/LqNzOxWL6GyR/s= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +k8s.io/streaming v0.37.1 h1:TpzVfQeFuVndn2g9mFqxy1UcUYPwDzqjUmwR/IzJCWc= +k8s.io/streaming v0.37.1/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= +k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= +k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg= modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE= diff --git a/kube/.golangci.yaml b/kube/.golangci.yaml new file mode 100644 index 0000000..621fd15 --- /dev/null +++ b/kube/.golangci.yaml @@ -0,0 +1,77 @@ +# golangci-lint configuration for edgelet-kube +# Target: Go 1.26.11, module github.com/eclipse-iofog/edgelet-kube + +version: "2" + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - ^build/ + - ^vendor/ + +linters: + default: none + enable: + - govet + - revive + - staticcheck + - errcheck + - misspell + - errorlint + settings: + revive: + enable-all-rules: true + rules: + - {name: add-constant, disabled: true} + - {name: argument-limit, disabled: true} + - {name: cognitive-complexity, disabled: true} + - {name: confusing-naming, disabled: true} + - {name: confusing-results, disabled: true} + - {name: cyclomatic, disabled: true} + - {name: early-return, disabled: true} + - {name: empty-block, disabled: true} + - {name: enforce-switch-style, disabled: true} + - {name: flag-parameter, disabled: true} + - {name: function-length, disabled: true} + - {name: function-result-limit, disabled: true} + - {name: import-shadowing, disabled: true} + - {name: line-length-limit, disabled: true} + - {name: max-control-nesting, disabled: true} + - {name: max-public-structs, disabled: true} + - {name: redundant-import-alias, disabled: true} + - {name: unsecure-url-scheme, disabled: true} + - {name: unused-parameter, disabled: true} + - {name: unused-receiver, disabled: true} + - {name: use-waitgroup-go, disabled: true} + - {name: var-naming, disabled: true} + staticcheck: + checks: + - all + - -SA1019 + misspell: + locale: US + errorlint: + errorf: true + asserts: true + comparison: true + exclusions: + generated: lax + paths: + - ^build/ + - ^vendor/ + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + +run: + timeout: 5m diff --git a/kube/cmd/edgelet-kube-server/main.go b/kube/cmd/edgelet-kube-server/main.go new file mode 100644 index 0000000..57a514a --- /dev/null +++ b/kube/cmd/edgelet-kube-server/main.go @@ -0,0 +1,171 @@ +//go:build linux && cgo + +// Package main is the fat runtime. +// server starts containerd, imports images, opens the datastore, and then +// starts kube-apiserver, the bridge conflist, kube-controller-manager, +// kube-scheduler, kubelet, and kube-proxy. Addon manifests are applied +// after the API server is ready. The load balancer controller starts then +// and writes the node IP onto LoadBalancer Services. +// The containerd child serves containerd and returns. +// kubectl, ctr, and crictl are recognized from argv0. +package main + +/* +static void edgeletKubeRuntime(void) {} +*/ +import "C" + +import ( + "context" + "errors" + "fmt" + "os" + "os/signal" + "path/filepath" + "strings" + "syscall" + + "github.com/eclipse-iofog/edgelet-kube/internal/boot" + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/containerd" + "github.com/eclipse-iofog/edgelet-kube/internal/control" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + "github.com/eclipse-iofog/edgelet-kube/internal/dispatch" + "github.com/eclipse-iofog/edgelet-kube/internal/kubectl" +) + +const readyLine = "edgelet-kube runtime" + +func main() { + // Keep cgo linked into the fat runtime. + C.edgeletKubeRuntime() + if handled, err := containerd.MaybeRunChild(os.Args); handled { + if err != nil { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", err) + os.Exit(1) + } + return + } + name, ok := commandName(os.Args) + if !ok { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", dispatch.ErrUsage) + os.Exit(2) + } + if containerd.WantsClient(name, os.Args) { + var err error + switch name { + case "ctr": + err = containerd.RunCtr(os.Args[1:]) + case "crictl": + err = containerd.RunCrictl(os.Args[1:]) + } + if err != nil { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", err) + os.Exit(1) + } + return + } + if name == "kubectl" { + if err := kubectl.Run(os.Args[1:]); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", err) + os.Exit(1) + } + return + } + if name == bundle.ServerCommand { + if err := serve(); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", err) + os.Exit(1) + } + return + } + _, _ = fmt.Printf("%s %s\n", readyLine, name) +} + +// serve starts containerd and imports images before the datastore opens. +// The bridge conflist is written before kubelet. kubelet and kube-proxy start +// with kube-controller-manager and kube-scheduler, after image import returns. +// Addon manifests are applied once the API server is ready. The load +// balancer controller starts with them. +// Without permission to create the runtime directories, serve returns after +// the ready line and does not open the API port. +func serve() error { + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + loaded, err := config.Load(os.Args, os.LookupEnv) + if err != nil { + return err + } + if err := control.CheckSELinux(loaded.SELinux); err != nil { + return err + } + // The containerd child inherits PATH. The bridge plugin looks up iptables there. + if err := control.PreferBundledBin(loaded.PreferBundledBin); err != nil { + return err + } + var store *datastore.Store + proc, err := boot.Start(ctx, boot.Config{ + RegistryFile: loaded.PrivateRegistry, + DisableDefaultEndpoint: loaded.DisableDefaultRegistryEndpoint, + PauseImage: loaded.PauseImage, + Registry: loaded.SystemDefaultRegistry, + Datastore: func(ctx context.Context) error { + opened, err := datastore.Open(ctx, datastore.Config{ + DataDir: loaded.DataDir, + Endpoint: loaded.DatastoreEndpoint, + CAFile: loaded.DatastoreCAFile, + CertFile: loaded.DatastoreCertFile, + KeyFile: loaded.DatastoreKeyFile, + NATSCreds: loaded.DatastoreNATSCreds, + SecretsEncryption: loaded.SecretsEncryption, + }) + if err != nil { + return err + } + store = opened + return nil + }, + }) + if err != nil { + if store != nil { + store.Close() + } + if ctx.Err() != nil || errors.Is(err, os.ErrPermission) { + _, _ = fmt.Printf("%s %s\n", readyLine, bundle.ServerCommand) + return nil + } + return err + } + defer proc.Stop() + defer store.Close() + api, err := control.Start(ctx, control.Config{Server: loaded, Store: store}) + if err != nil { + return err + } + defer api.Stop() + _, _ = fmt.Printf("%s %s\n", readyLine, bundle.ServerCommand) + <-ctx.Done() + return nil +} + +func commandName(args []string) (string, bool) { + if len(args) == 0 { + return "", false + } + base := filepath.Base(args[0]) + if bundle.Client(base) { + return base, true + } + flag := "--" + bundle.DataDirFlag + for i := 1; i < len(args); i++ { + switch { + case args[i] == flag: + i++ + case strings.HasPrefix(args[i], flag+"="): + case args[i] == bundle.ServerCommand: + return bundle.ServerCommand, true + } + } + return "", false +} diff --git a/kube/cmd/edgelet-kube/embed.go b/kube/cmd/edgelet-kube/embed.go new file mode 100644 index 0000000..0e4ef82 --- /dev/null +++ b/kube/cmd/edgelet-kube/embed.go @@ -0,0 +1,33 @@ +//go:build linux && !cgo + +package main + +import ( + "embed" + "fmt" + "strings" + + "github.com/eclipse-iofog/edgelet/pkg/data/bindata" +) + +//go:embed embed/* +var embedFS embed.FS + +var embedded = bindata.Bindata{FS: &embedFS, Prefix: "embed"} + +func embeddedBundle() (string, error) { + var match string + for _, name := range embedded.AssetNames() { + if strings.HasSuffix(name, ".tar.zst") { + match = name + } + } + if match == "" { + return "", fmt.Errorf("no embedded runtime bundle") + } + return match, nil +} + +func assetBytes(name string) ([]byte, error) { + return embedded.Asset(name) +} diff --git a/kube/cmd/edgelet-kube/extract.go b/kube/cmd/edgelet-kube/extract.go new file mode 100644 index 0000000..57dafa8 --- /dev/null +++ b/kube/cmd/edgelet-kube/extract.go @@ -0,0 +1,103 @@ +//go:build linux && !cgo + +package main + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet/pkg/datadir" + "github.com/eclipse-iofog/edgelet/pkg/dataverify" + "github.com/eclipse-iofog/edgelet/pkg/flock" + "github.com/eclipse-iofog/edgelet/pkg/untar" +) + +// extract unpacks this binary's embedded runtime with the shared untar and lock helpers. +func extract(dataDir string) (string, error) { + asset, err := embeddedBundle() + if err != nil { + return "", err + } + root, err := datadir.BundleRoot(dataDir) + if err != nil { + return "", err + } + hash := strings.TrimSuffix(filepath.Base(asset), ".tar.zst") + if !validHash(hash) { + return "", fmt.Errorf("embedded bundle %s has no hash name", asset) + } + dir := filepath.Join(root, hash) + if bundleReady(dir) { + return dir, nil + } + if err := os.MkdirAll(root, 0o755); err != nil { // #nosec G301 -- data root must be traversable + return "", fmt.Errorf("mkdir data root: %w", err) + } + lock, err := flock.Acquire(filepath.Join(root, ".lock")) + if err != nil { + return "", fmt.Errorf("acquire extract lock: %w", err) + } + defer func() { _ = flock.Release(lock) }() + if bundleReady(dir) { + return dir, nil + } + return unpack(asset, dir) +} + +func unpack(asset, dir string) (out string, err error) { + content, err := assetBytes(asset) + if err != nil { + return "", fmt.Errorf("load embedded runtime: %w", err) + } + tempDest := dir + "-tmp" + if err = os.RemoveAll(tempDest); err != nil { + return "", fmt.Errorf("remove extract temp dir: %w", err) + } + defer func() { + if err != nil { + _ = os.RemoveAll(tempDest) + } + }() + if err = untar.Untar(bytes.NewReader(content), tempDest); err != nil { + return "", fmt.Errorf("untar runtime bundle: %w", err) + } + fat := filepath.Join(tempDest, "bin", bundle.FatName) + ok, readErr := dataverify.IsELF(fat) + if readErr != nil { + return "", fmt.Errorf("read runtime: %w", readErr) + } + if !ok { + return "", fmt.Errorf("runtime is not an ELF binary") + } + if err = os.Chmod(fat, 0o755); err != nil { // #nosec G302 -- runtime binary must be executable + return "", fmt.Errorf("chmod runtime: %w", err) + } + if err = os.RemoveAll(dir); err != nil { + return "", fmt.Errorf("remove incomplete bundle: %w", err) + } + if err = os.Rename(tempDest, dir); err != nil { + return "", fmt.Errorf("rename extracted bundle: %w", err) + } + return dir, nil +} + +func bundleReady(dir string) bool { + ok, err := dataverify.IsELF(filepath.Join(dir, "bin", bundle.FatName)) + return err == nil && ok +} + +func validHash(hash string) bool { + if len(hash) != 64 { + return false + } + for _, c := range hash { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} diff --git a/kube/cmd/edgelet-kube/main.go b/kube/cmd/edgelet-kube/main.go new file mode 100644 index 0000000..94dea7b --- /dev/null +++ b/kube/cmd/edgelet-kube/main.go @@ -0,0 +1,41 @@ +//go:build linux && !cgo + +// Package main is the thin edgelet-kube binary. It extracts the embedded runtime and execs it. +package main + +import ( + "fmt" + "os" + "path/filepath" + "syscall" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/dispatch" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" +) + +func main() { + if err := run(os.Args); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "edgelet-kube: %v\n", err) + os.Exit(1) + } +} + +func run(args []string) error { + cmd, err := dispatch.Parse(args, os.Getenv(bundle.DataDirEnv)) + if err != nil { + return err + } + dir, err := extract(cmd.DataDir) + if err != nil { + return err + } + if _, err := paths.Place(dir); err != nil { + return err + } + fat := filepath.Join(dir, "bin", bundle.FatName) + if err := syscall.Exec(fat, cmd.Args, os.Environ()); err != nil { // #nosec G204 -- fat is the extracted runtime + return fmt.Errorf("exec runtime: %w", err) + } + return nil +} diff --git a/kube/go.mod b/kube/go.mod new file mode 100644 index 0000000..8d5058f --- /dev/null +++ b/kube/go.mod @@ -0,0 +1,362 @@ +module github.com/eclipse-iofog/edgelet-kube + +go 1.26.11 + +require ( + github.com/containerd/containerd/v2 v2.3.2 + github.com/containerd/errdefs v1.0.0 + github.com/containernetworking/plugins v1.9.1 + github.com/eclipse-iofog/edgelet v0.0.0 + github.com/fsnotify/fsnotify v1.10.1 + github.com/k3s-io/helm-controller v0.17.9 + github.com/k3s-io/kine v0.17.5 + github.com/klauspost/compress v1.20.3 + github.com/opencontainers/go-digest v1.0.0 + github.com/opencontainers/image-spec v1.1.1 + github.com/opencontainers/selinux v1.15.1 + github.com/pelletier/go-toml v1.9.5 + github.com/rancher/lasso v0.2.7 + github.com/rancher/wrangler/v3 v3.5.1 + github.com/sirupsen/logrus v1.10.2 + github.com/spf13/pflag v1.0.10 + go.yaml.in/yaml/v3 v3.0.5 + golang.org/x/sys v0.49.0 + google.golang.org/grpc v1.85.0 + k8s.io/api v0.37.2 + k8s.io/apimachinery v0.37.2 + k8s.io/apiserver v0.37.2 + k8s.io/client-go v0.37.2 + k8s.io/component-base v0.37.2 + k8s.io/cri-api v0.37.2 + k8s.io/klog/v2 v2.140.0 + k8s.io/kube-aggregator v0.35.0 + k8s.io/kubectl v0.36.6 + k8s.io/kubernetes v1.37.2 + k8s.io/metrics v0.37.2 +) + +require ( + cel.dev/expr v0.25.3 // indirect + cyphar.com/go-pathrs v0.2.5 // indirect + dario.cat/mergo v1.0.2 // indirect + filippo.io/edwards25519 v1.2.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect + github.com/DataDog/zstd v1.4.5 // indirect + github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab // indirect + github.com/MakeNowJust/heredoc v1.0.0 // indirect + github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 // indirect + github.com/Microsoft/hcsshim v0.15.0-rc.1 // indirect + github.com/Microsoft/hnslib v0.1.3 // indirect + github.com/NYTimes/gziphandler v1.1.1 // indirect + github.com/ProtonMail/go-crypto v1.4.1 // indirect + github.com/Rican7/retry v0.3.1 // indirect + github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect + github.com/alexflint/go-filemutex v1.3.0 // indirect + github.com/antithesishq/antithesis-sdk-go v0.8.0 // indirect + github.com/antlr4-go/antlr/v4 v4.13.1 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/blang/semver/v4 v4.0.0 // indirect + github.com/cenkalti/backoff/v5 v5.0.3 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/chai2010/gettext-go v1.0.2 // indirect + github.com/checkpoint-restore/checkpointctl v1.5.0 // indirect + github.com/checkpoint-restore/go-criu/v7 v7.2.0 // indirect + github.com/cilium/ebpf v0.22.0 // indirect + github.com/cloudflare/circl v1.6.3 // indirect + github.com/cockroachdb/errors v1.11.3 // indirect + github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce // indirect + github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect + github.com/cockroachdb/pebble v1.1.5 // indirect + github.com/cockroachdb/redact v1.1.5 // indirect + github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect + github.com/container-storage-interface/spec v1.12.1-0.20260720052920-cd9e7ad1ae09 // indirect + github.com/containerd/cgroups/v3 v3.1.3 // indirect + github.com/containerd/console v1.0.5 // indirect + github.com/containerd/containerd/api v1.11.1 // indirect + github.com/containerd/continuity v0.5.0 // indirect + github.com/containerd/errdefs/pkg v0.3.0 // indirect + github.com/containerd/fifo v1.1.0 // indirect + github.com/containerd/go-cni v1.1.13 // indirect + github.com/containerd/go-runc v1.1.0 // indirect + github.com/containerd/imgcrypt/v2 v2.0.3 // indirect + github.com/containerd/log v0.1.0 // indirect + github.com/containerd/nri v0.12.0 // indirect + github.com/containerd/otelttrpc v0.1.0 // indirect + github.com/containerd/platforms v1.0.0-rc.5 // indirect + github.com/containerd/plugin v1.1.0 // indirect + github.com/containerd/ttrpc v1.2.9 // indirect + github.com/containerd/typeurl/v2 v2.3.0 // indirect + github.com/containernetworking/cni v1.3.0 // indirect + github.com/containers/ocicrypt v1.3.2 // indirect + github.com/coreos/go-iptables v0.8.0 // indirect + github.com/coreos/go-oidc v2.5.0+incompatible // indirect + github.com/coreos/go-semver v0.3.1 // indirect + github.com/coreos/go-systemd/v22 v22.7.0 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.7 // indirect + github.com/cyphar/filepath-securejoin v0.7.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/distribution/reference v0.6.0 // indirect + github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect + github.com/docker/go-metrics v0.0.1 // indirect + github.com/docker/go-units v0.5.0 // indirect + github.com/dustin/go-humanize v1.1.0 // indirect + github.com/emicklei/go-restful/v3 v3.13.0 // indirect + github.com/evanphx/json-patch v5.9.11+incompatible // indirect + github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f // indirect + github.com/expr-lang/expr v1.17.8 // indirect + github.com/fatih/camelcase v1.0.0 // indirect + github.com/felixge/httpsnoop v1.1.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.1 // indirect + github.com/getsentry/sentry-go v0.27.0 // indirect + github.com/ghodss/yaml v1.0.0 // indirect + github.com/go-errors/errors v1.4.2 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect + github.com/go-logr/logr v1.4.4 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/go-openapi/jsonpointer v1.0.0 // indirect + github.com/go-openapi/jsonreference v1.0.0 // indirect + github.com/go-openapi/swag v0.28.0 // indirect + github.com/go-openapi/swag/cmdutils v0.28.0 // indirect + github.com/go-openapi/swag/conv v0.28.0 // indirect + github.com/go-openapi/swag/fileutils v0.28.0 // indirect + github.com/go-openapi/swag/jsonutils v0.28.0 // indirect + github.com/go-openapi/swag/loading v0.28.0 // indirect + github.com/go-openapi/swag/mangling v0.28.0 // indirect + github.com/go-openapi/swag/netutils v0.28.0 // indirect + github.com/go-openapi/swag/pools v0.28.0 // indirect + github.com/go-openapi/swag/stringutils v0.28.0 // indirect + github.com/go-openapi/swag/typeutils v0.28.0 // indirect + github.com/go-openapi/swag/yamlutils v0.28.0 // indirect + github.com/go-sql-driver/mysql v1.10.1 // indirect + github.com/godbus/dbus/v5 v5.2.2 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect + github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/btree v1.1.3 // indirect + github.com/google/cadvisor/lib v0.60.5 // indirect + github.com/google/cel-go v0.29.2 // indirect + github.com/google/certtostore v1.0.6 // indirect + github.com/google/deck v0.0.0-20230104221208-105ad94aa8ae // indirect + github.com/google/gnostic-models v0.7.0 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/go-tpm v0.9.8 // indirect + github.com/google/nftables v0.3.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 // indirect + github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/intel/goresctrl v0.12.0 // indirect + github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.12.0 // indirect + github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/jonboulle/clockwork v0.5.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/crc32 v1.3.0 // indirect + github.com/knqyf263/go-plugin v0.9.0 // indirect + github.com/kr/pretty v0.3.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect + github.com/lithammer/dedent v1.1.0 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mattn/go-sqlite3 v1.14.52 // indirect + github.com/mdlayher/netlink v1.11.2 // indirect + github.com/mdlayher/socket v0.6.1 // indirect + github.com/mdlayher/vsock v1.2.1 // indirect + github.com/miekg/pkcs11 v1.1.2 // indirect + github.com/minio/crc64nvme v1.1.1 // indirect + github.com/minio/highwayhash v1.0.4 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/minio/minio-go/v7 v7.3.0 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect + github.com/moby/ipvs v1.1.0 // indirect + github.com/moby/locker v1.0.1 // indirect + github.com/moby/spdystream v0.5.1 // indirect + github.com/moby/sys/capability v0.4.0 // indirect + github.com/moby/sys/mountinfo v0.7.2 // indirect + github.com/moby/sys/sequential v0.6.0 // indirect + github.com/moby/sys/signal v0.7.1 // indirect + github.com/moby/sys/symlink v0.3.0 // indirect + github.com/moby/sys/user v0.4.1 // indirect + github.com/moby/sys/userns v0.1.0 // indirect + github.com/moby/term v0.5.2 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect + github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect + github.com/nats-io/jsm.go v0.5.1 // indirect + github.com/nats-io/jwt/v2 v2.8.2 // indirect + github.com/nats-io/nats-server/v2 v2.15.2 // indirect + github.com/nats-io/nats.go v1.55.0 // indirect + github.com/nats-io/nkeys v0.4.16 // indirect + github.com/nats-io/nuid v1.0.1 // indirect + github.com/ncruces/go-strftime v1.1.0 // indirect + github.com/opencontainers/cgroups v0.0.7 // indirect + github.com/opencontainers/runtime-spec v1.3.0 // indirect + github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 // indirect + github.com/pelletier/go-toml/v2 v2.3.1 // indirect + github.com/peterbourgon/diskv v2.0.1+incompatible // indirect + github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/pquerna/cachecontrol v0.1.0 // indirect + github.com/prometheus/client_golang v1.25.0 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.72.1 // indirect + github.com/prometheus/procfs v0.23.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/robfig/cron/v3 v3.0.1 // indirect + github.com/rogpeppe/go-internal v1.14.1 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/safchain/ethtool v0.6.2 // indirect + github.com/sasha-s/go-deadlock v0.3.5 // indirect + github.com/shengdoushi/base58 v1.0.0 // indirect + github.com/smallstep/pkcs7 v0.2.1 // indirect + github.com/soheilhy/cmux v0.1.5 // indirect + github.com/spf13/cobra v1.10.2 // indirect + github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect + github.com/t4db/t4 v1.1.16 // indirect + github.com/tchap/go-patricia/v2 v2.3.3 // indirect + github.com/tetratelabs/wazero v1.11.0 // indirect + github.com/tidwall/btree v1.8.2 // indirect + github.com/tinylib/msgp v1.6.4 // indirect + github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 // indirect + github.com/urfave/cli/v2 v2.27.7 // indirect + github.com/vishvananda/netlink v1.3.1 // indirect + github.com/vishvananda/netns v0.0.5 // indirect + github.com/x448/float16 v0.8.4 // indirect + github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 // indirect + github.com/xlab/treeprint v1.2.0 // indirect + github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect + github.com/zeebo/xxh3 v1.1.0 // indirect + go.etcd.io/bbolt v1.5.0 // indirect + go.etcd.io/etcd/api/v3 v3.7.3 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.7.3 // indirect + go.etcd.io/etcd/client/v3 v3.7.3 // indirect + go.etcd.io/etcd/pkg/v3 v3.7.3 // indirect + go.etcd.io/etcd/server/v3 v3.7.3 // indirect + go.etcd.io/raft/v3 v3.7.0 // indirect + go.opencensus.io v0.24.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful v0.69.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 // indirect + go.opentelemetry.io/otel v1.46.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 // indirect + go.opentelemetry.io/otel/metric v1.46.0 // indirect + go.opentelemetry.io/otel/sdk v1.46.0 // indirect + go.opentelemetry.io/otel/trace v1.46.0 // indirect + go.opentelemetry.io/proto/otlp v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.28.0 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/oauth2 v0.37.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/term v0.47.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/time v0.16.0 // indirect + golang.org/x/tools v0.52.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261104224025-d1e00e9f33ab // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b // indirect + google.golang.org/protobuf v1.36.12 // indirect + gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect + gopkg.in/go-jose/go-jose.v2 v2.6.3 // indirect + gopkg.in/inf.v0 v0.9.1 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect + gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + k8s.io/apiextensions-apiserver v0.35.8 // indirect + k8s.io/cli-runtime v0.37.2 // indirect + k8s.io/cloud-provider v0.37.2 // indirect + k8s.io/cluster-bootstrap v0.0.0 // indirect + k8s.io/component-helpers v0.37.2 // indirect + k8s.io/controller-manager v0.37.2 // indirect + k8s.io/cri-client v0.37.1 // indirect + k8s.io/cri-streaming v0.37.1 // indirect + k8s.io/csi-translation-lib v0.0.0 // indirect + k8s.io/dynamic-resource-allocation v0.37.2 // indirect + k8s.io/endpointslice v0.0.0 // indirect + k8s.io/externaljwt v0.0.0 // indirect + k8s.io/kms v0.37.2 // indirect + k8s.io/kube-controller-manager v0.0.0 // indirect + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + k8s.io/kube-proxy v0.0.0 // indirect + k8s.io/kube-scheduler v0.0.0 // indirect + k8s.io/kubelet v0.37.2 // indirect + k8s.io/mount-utils v0.0.0 // indirect + k8s.io/pod-security-admission v0.0.0 // indirect + k8s.io/streaming v0.37.2 // indirect + k8s.io/utils v0.0.0-20260626114624-be93311217bd // indirect + modernc.org/libc v1.79.0 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.12.1 // indirect + modernc.org/sqlite v1.61.0 // indirect + sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 // indirect + sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect + sigs.k8s.io/knftables v0.0.22 // indirect + sigs.k8s.io/kustomize/api v0.21.1 // indirect + sigs.k8s.io/kustomize/kustomize/v5 v5.8.1 // indirect + sigs.k8s.io/kustomize/kyaml v0.21.1 // indirect + sigs.k8s.io/randfill v1.0.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect + tags.cncf.io/container-device-interface v1.1.0 // indirect + tags.cncf.io/container-device-interface/specs-go v1.1.0 // indirect +) + +replace github.com/eclipse-iofog/edgelet => ../ + +replace ( + github.com/containerd/containerd/api => github.com/containerd/containerd/api v1.11.1 + github.com/containerd/containerd/v2 => github.com/k3s-io/containerd/v2 v2.3.7-k3s1 + k8s.io/api => k8s.io/api v0.37.2 + k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.37.2 + k8s.io/apimachinery => k8s.io/apimachinery v0.37.2 + k8s.io/apiserver => k8s.io/apiserver v0.37.2 + k8s.io/cli-runtime => k8s.io/cli-runtime v0.37.2 + k8s.io/client-go => k8s.io/client-go v0.37.2 + k8s.io/cloud-provider => k8s.io/cloud-provider v0.37.2 + k8s.io/cluster-bootstrap => k8s.io/cluster-bootstrap v0.37.2 + k8s.io/code-generator => k8s.io/code-generator v0.37.2 + k8s.io/component-base => k8s.io/component-base v0.37.2 + k8s.io/component-helpers => k8s.io/component-helpers v0.37.2 + k8s.io/controller-manager => k8s.io/controller-manager v0.37.2 + k8s.io/cri-api => github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1 + k8s.io/cri-client => k8s.io/cri-client v0.37.2 + k8s.io/cri-streaming => k8s.io/cri-streaming v0.37.2 + k8s.io/csi-translation-lib => k8s.io/csi-translation-lib v0.37.2 + k8s.io/dynamic-resource-allocation => k8s.io/dynamic-resource-allocation v0.37.2 + k8s.io/endpointslice => k8s.io/endpointslice v0.37.2 + k8s.io/externaljwt => k8s.io/externaljwt v0.37.2 + k8s.io/kms => k8s.io/kms v0.37.2 + k8s.io/kube-aggregator => k8s.io/kube-aggregator v0.37.2 + k8s.io/kube-controller-manager => k8s.io/kube-controller-manager v0.37.2 + k8s.io/kube-proxy => k8s.io/kube-proxy v0.37.2 + k8s.io/kube-scheduler => k8s.io/kube-scheduler v0.37.2 + k8s.io/kubectl => k8s.io/kubectl v0.37.2 + k8s.io/kubelet => k8s.io/kubelet v0.37.2 + k8s.io/metrics => k8s.io/metrics v0.37.2 + k8s.io/mount-utils => k8s.io/mount-utils v0.37.2 + k8s.io/pod-security-admission => k8s.io/pod-security-admission v0.37.2 + k8s.io/sample-apiserver => k8s.io/sample-apiserver v0.37.2 + k8s.io/sample-cli-plugin => k8s.io/sample-cli-plugin v0.37.2 + k8s.io/sample-controller => k8s.io/sample-controller v0.37.2 + k8s.io/streaming => k8s.io/streaming v0.37.2 +) diff --git a/kube/go.sum b/kube/go.sum new file mode 100644 index 0000000..73bf4ad --- /dev/null +++ b/kube/go.sum @@ -0,0 +1,952 @@ +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cyphar.com/go-pathrs v0.2.5 h1:SnX9FBvnoyn3lUs1dkMgZ52bAETpirNu3FTRh5HlRik= +cyphar.com/go-pathrs v0.2.5/go.mod h1:y8f1EMG7r+hCuFf/rXsKqMJrJAUoADZGNh5/vZPKcGc= +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg= +github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab h1:UKkYhof1njT1/xq4SEg5z+VpTgjmNeHwPGRQl7takDI= +github.com/JeffAshton/win_pdh v0.0.0-20161109143554-76bb4ee9f0ab/go.mod h1:3VYc5hodBMJ5+l/7J4xAyMeuM2PNuepvHlGs8yilUCA= +github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= +github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= +github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29 h1:0kQAzHq8vLs7Pptv+7TxjdETLf/nIqJpIB4oC6Ba4vY= +github.com/Microsoft/go-winio v0.6.3-0.20251027160822-ad3df93bed29/go.mod h1:ZWa7ssZJT30CCDGJ7fk/2SBTq9BIQrrVjrcss0UW2s0= +github.com/Microsoft/hcsshim v0.15.0-rc.1 h1:FbbwtQmiD+BVHynGkx5S65JkLyhkEiiTP8nrpmg2SZw= +github.com/Microsoft/hcsshim v0.15.0-rc.1/go.mod h1:HWvvUPIy9HF6LotILj1G4VyS065rcLQ6tqj6tMUdOfI= +github.com/Microsoft/hnslib v0.1.3 h1:OCD8uA1IIqaaOV00qwbL8GwHEVCk8UPS8tiUb6pJzTQ= +github.com/Microsoft/hnslib v0.1.3/go.mod h1:5vTyBey4N/VI2ZTNh2gdWhkPMefSbCFYjpvVwye+qtI= +github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= +github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM= +github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo= +github.com/Rican7/retry v0.3.1 h1:scY4IbO8swckzoA/11HgBwaZRJEyY9vaNJshcdhp1Mc= +github.com/Rican7/retry v0.3.1/go.mod h1:CxSDrhAyXmTMeEuRAnArMu1FHu48vtfjLREWqVl7Vw0= +github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk= +github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alexflint/go-filemutex v1.3.0 h1:LgE+nTUWnQCyRKbpoceKZsPQbs84LivvgwUymZXdOcM= +github.com/alexflint/go-filemutex v1.3.0/go.mod h1:U0+VA/i30mGBlLCrFPGtTe9y6wGQfNAWPBTekHQ+c8A= +github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4= +github.com/antithesishq/antithesis-sdk-go v0.8.0/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI= +github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= +github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= +github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= +github.com/brianvoe/gofakeit/v7 v7.12.1 h1:df1tiI4SL1dR5Ix4D/r6a3a+nXBJ/OBGU5jEKRBmmqg= +github.com/brianvoe/gofakeit/v7 v7.12.1/go.mod h1:QXuPeBw164PJCzCUZVmgpgHJ3Llj49jSLVkKPMtxtxA= +github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM= +github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chai2010/gettext-go v1.0.2 h1:1Lwwip6Q2QGsAdl/ZKPCwTe9fe0CjlUbqj5bFNSjIRk= +github.com/chai2010/gettext-go v1.0.2/go.mod h1:y+wnP2cHYaVj19NZhYKAwEMH2CI1gNHeQQ+5AjwawxA= +github.com/checkpoint-restore/checkpointctl v1.5.0 h1:Uu+D2cOf/GUyCMk23Y8L69P6YoATTe6pH+Au64O3y28= +github.com/checkpoint-restore/checkpointctl v1.5.0/go.mod h1:y5HRs1ZWQUZGyEuthlTHmTJN9PUMOjlaH6JvVaNq9kE= +github.com/checkpoint-restore/go-criu/v7 v7.2.0 h1:qGiWA4App1gGlEfIJ68WR9jbezV9J7yZdjzglezcqKo= +github.com/checkpoint-restore/go-criu/v7 v7.2.0/go.mod h1:u0LCWLg0w4yqqu14aXhiB4YD3a1qd8EcCEg7vda5dwo= +github.com/cilium/ebpf v0.22.0 h1:v2ktp0roffpMOj2MMf3idtCQZOsAoC4BJbAJN+ke2bY= +github.com/cilium/ebpf v0.22.0/go.mod h1:CDzZbe2hC5JjlDC+CY3KFCzlYwN4gbxppYM+Z10bQt4= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8= +github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4= +github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU= +github.com/cockroachdb/errors v1.11.3 h1:5bA+k2Y6r+oz/6Z/RFlNeVCesGARKuC6YymtcDrbC/I= +github.com/cockroachdb/errors v1.11.3/go.mod h1:m4UIW4CDjx+R5cybPsNrRbreomiFqt8o1h1wUVazSd8= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce h1:giXvy4KSc/6g/esnpM7Geqxka4WSqI1SZc7sMJFd3y4= +github.com/cockroachdb/fifo v0.0.0-20240606204812-0bbfbd93a7ce/go.mod h1:9/y3cnZ5GKakj/H4y9r9GTjCvAFta7KLgSHPJJYc52M= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZeQy818SGhaone5OnYfxFR/+AzdY3sf5aE= +github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= +github.com/cockroachdb/pebble v1.1.5 h1:5AAWCBWbat0uE0blr8qzufZP5tBjkRyy/jWe1QWLnvw= +github.com/cockroachdb/pebble v1.1.5/go.mod h1:17wO9el1YEigxkP/YtV8NtCivQDgoCyBg5c4VR/eOWo= +github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= +github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= +github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06/go.mod h1:7nc4anLGjupUW/PeY5qiNYsdNXj7zopG+eqsS7To5IQ= +github.com/container-storage-interface/spec v1.12.1-0.20260720052920-cd9e7ad1ae09 h1:wmRsAxwkfle3i2KIubElYZIuz1rgN3vtkIlf8kAS/hA= +github.com/container-storage-interface/spec v1.12.1-0.20260720052920-cd9e7ad1ae09/go.mod h1:apAI5+IWKBXTKh293aCL8t3f2Z9qzjhwaI3ghwGoR94= +github.com/containerd/cgroups/v3 v3.1.3 h1:eUNflyMddm18+yrDmZPn3jI7C5hJ9ahABE5q6dyLYXQ= +github.com/containerd/cgroups/v3 v3.1.3/go.mod h1:PKZ2AcWmSBsY/tJUVhtS/rluX0b1uq1GmPO1ElCmbOw= +github.com/containerd/console v1.0.5 h1:R0ymNeydRqH2DmakFNdmjR2k0t7UPuiOV/N/27/qqsc= +github.com/containerd/console v1.0.5/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk= +github.com/containerd/containerd/api v1.11.1 h1:h8nfoDW9+fNsC/9TwiAHj8B1GzXKtR4eFtkhi/X5RLU= +github.com/containerd/containerd/api v1.11.1/go.mod h1:CaQFRu+N1MtbgL6JDOJLUB1hCKESU1lD6MuTJhgtdlw= +github.com/containerd/continuity v0.5.0 h1:7a85HZpCSs+1Zps0Ee3DPSuAWY+0SJM1JNM51nlEVDg= +github.com/containerd/continuity v0.5.0/go.mod h1:/lNJvtJKUQStBzpVQ1+rasXO1LAWtUQssk28EZvJ3nE= +github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= +github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= +github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= +github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk= +github.com/containerd/fifo v1.1.0 h1:4I2mbh5stb1u6ycIABlBw9zgtlK8viPI9QkQNRQEEmY= +github.com/containerd/fifo v1.1.0/go.mod h1:bmC4NWMbXlt2EZ0Hc7Fx7QzTFxgPID13eH0Qu+MAb2o= +github.com/containerd/go-cni v1.1.13 h1:eFSGOKlhoYNxpJ51KRIMHZNlg5UgocXEIEBGkY7Hnis= +github.com/containerd/go-cni v1.1.13/go.mod h1:nTieub0XDRmvCZ9VI/SBG6PyqT95N4FIhxsauF1vSBI= +github.com/containerd/go-runc v1.1.0 h1:OX4f+/i2y5sUT7LhmcJH7GYrjjhHa1QI4e8yO0gGleA= +github.com/containerd/go-runc v1.1.0/go.mod h1:xJv2hFF7GvHtTJd9JqTS2UVxMkULUYw4JN5XAUZqH5U= +github.com/containerd/imgcrypt/v2 v2.0.3 h1:yM6//IOTtca9TpxPP8prJqLDuidbF/VhUQujLw7UQ3w= +github.com/containerd/imgcrypt/v2 v2.0.3/go.mod h1:Sjfd3uOiBWtb1dUo1yS5Z/ZxdfMU7MpBr2pzs9HoRDs= +github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I= +github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo= +github.com/containerd/nri v0.12.0 h1:RvZtyCM64XOB1UmMAFOlfReTTwCd+hE2IEQ5XEpkKA0= +github.com/containerd/nri v0.12.0/go.mod h1:TGAfPLH4a+qwbv0PxsefPiR+PobYecDj2aXMtz7GQcg= +github.com/containerd/otelttrpc v0.1.0 h1:UOX68eVTE8H/T45JveIg+I22Ev2aFj4qPITCmXsskjw= +github.com/containerd/otelttrpc v0.1.0/go.mod h1:XhoA2VvaGPW1clB2ULwrBZfXVuEWuyOd2NUD1IM0yTg= +github.com/containerd/platforms v1.0.0-rc.5 h1:vXd569rDrz8LeMXzAnBsy6LADV5YtsD8oyaRarxdmSU= +github.com/containerd/platforms v1.0.0-rc.5/go.mod h1:lKlMXyLybmBedS/JJm11uDofzI8L2v0J2ZbYvNsbq1A= +github.com/containerd/plugin v1.1.0 h1:O+7lczNJVMy8rz0YNx3xGB8tTf5qY4i5abF041Ew19U= +github.com/containerd/plugin v1.1.0/go.mod h1:qBTum+A8lJ6lO44A19Eo7y1OlcLj4OWFH1DA/vnHmcc= +github.com/containerd/ttrpc v1.2.9 h1:ha0ak962T0s3CA/RoZ6S6xiWZQF24GrBaEpiGX1uihg= +github.com/containerd/ttrpc v1.2.9/go.mod h1:jjtQRwXm4DL3KsHKW8vDiUOV6wO0hi6IPhmJhxU7aEs= +github.com/containerd/typeurl/v2 v2.3.0 h1:HZHPhRWo5XMy3QGQoPrUzbW/2ckwjfweHmOwlkIrPAQ= +github.com/containerd/typeurl/v2 v2.3.0/go.mod h1:Qk+PAdUYArVj41TnGi6rJ+48RF0PkcTc4i/taoBcK0w= +github.com/containernetworking/cni v1.3.0 h1:v6EpN8RznAZj9765HhXQrtXgX+ECGebEYEmnuFjskwo= +github.com/containernetworking/cni v1.3.0/go.mod h1:Bs8glZjjFfGPHMw6hQu82RUgEPNGEaBb9KS5KtNMnJ4= +github.com/containernetworking/plugins v1.9.1 h1:8oU6WsIsU3bpnNZuvHp74a6cE1MJwbj2P7s4/yTUNlA= +github.com/containernetworking/plugins v1.9.1/go.mod h1:fj7kS55qg3o/RgS+WGsF3+ZxwIImMPusQZKzBpcSr4c= +github.com/containers/ocicrypt v1.3.2 h1:MuqHSfiPpGzoAQdgDSX85FgixSgIm9mSDXTLTgugY5E= +github.com/containers/ocicrypt v1.3.2/go.mod h1:ntBZabYG0rlvstB/1rK/ba2laaU5EHE0pD5ioHoPTq4= +github.com/coreos/go-iptables v0.8.0 h1:MPc2P89IhuVpLI7ETL/2tx3XZ61VeICZjYqDEgNsPRc= +github.com/coreos/go-iptables v0.8.0/go.mod h1:Qe8Bv2Xik5FyTXwgIbLAnv2sWSBmvWdFETJConOQ//Q= +github.com/coreos/go-oidc v2.5.0+incompatible h1:6W0vGJR3Tu0r0PwfmjOrRZSlfxeEln8dsejt3ZWIvwo= +github.com/coreos/go-oidc v2.5.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= +github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= +github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= +github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= +github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo= +github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= +github.com/cyphar/filepath-securejoin v0.7.0 h1:s0Y3ITPy6sQn5xt54DuYvTF8hu134ooYLUb58DX/HjE= +github.com/cyphar/filepath-securejoin v0.7.0/go.mod h1:ymLGms/u3BYaviIiuKFnUx8EkQEZeK6cInNoAPJA3o4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= +github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c h1:+pKlWGMw7gf6bQ+oDZB4KHQFypsfjYlq/C4rfL7D3g8= +github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= +github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= +github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= +github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= +github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/erofs/go-erofs v0.3.0 h1:o/W5ABAA3sHYl97WL93dacKEfeDpJhdFf3c2snAti7I= +github.com/erofs/go-erofs v0.3.0/go.mod h1:XkSeN9MHszGd4+3gcEjadJLYHCQpWzJ7/8yznzMuzJs= +github.com/evanphx/json-patch v5.9.11+incompatible h1:ixHHqfcGvxhWkniF1tWxBHA0yb4Z+d1UQi45df52xW8= +github.com/evanphx/json-patch v5.9.11+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f h1:Wl78ApPPB2Wvf/TIe2xdyJxTlb6obmF18d8QdkxNDu4= +github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f/go.mod h1:OSYXu++VVOHnXeitef/D8n/6y4QV8uLHSFXX4NeXMGc= +github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM= +github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4= +github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= +github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= +github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= +github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= +github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= +github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= +github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= +github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps= +github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= +github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= +github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= +github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= +github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= +github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= +github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= +github.com/go-openapi/swag v0.28.0 h1:xkgbOSKj6DZziNpyqRRAOt3GJGtgjgsd2RoyT30VWuw= +github.com/go-openapi/swag v0.28.0/go.mod h1:4qYnT3Cqr1p1VknOdPo70evN4rgQnAg6jwApHyxSGIg= +github.com/go-openapi/swag/cmdutils v0.28.0 h1:7TOeNtkYru1SG8Y34tDh9WBbLsMqGnptuxWiHREPZ4Q= +github.com/go-openapi/swag/cmdutils v0.28.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8= +github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k= +github.com/go-openapi/swag/fileutils v0.28.0 h1:Z04XWQD7R8Eq+7GnOrjovBxPPmZzsS4gt2H2GPGIViU= +github.com/go-openapi/swag/fileutils v0.28.0/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= +github.com/go-openapi/swag/jsonutils v0.28.0 h1:YIch6FwO7RXzeAnbO8Tu7dWBZeUEH+4nA0HXltVTnv4= +github.com/go-openapi/swag/jsonutils v0.28.0/go.mod h1:CYM3WlTUcagR2ZoHdz54di/cbBqt82tuxuXgAjxw+mg= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0 h1:qV+VVUAx5Oro8WjVWpZeql7YReTKhT4smR4zhcOQZr0= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= +github.com/go-openapi/swag/loading v0.28.0 h1:td8QZdZC9MIYGGSnSPKShKiK22I2tU5UQvuUhIBPRLU= +github.com/go-openapi/swag/loading v0.28.0/go.mod h1:rXB0QiQX5mMveXEA7ouM4KiiM9jVJe4K6BVbwhD1M4k= +github.com/go-openapi/swag/mangling v0.28.0 h1:pH8eyeNO9SLYsTMWJrurnNfKmDa28XrlA+HePVD53VM= +github.com/go-openapi/swag/mangling v0.28.0/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= +github.com/go-openapi/swag/netutils v0.28.0 h1:YXN6TALEi2pzts8/8GNm6T61HTAZsieukGZidap989k= +github.com/go-openapi/swag/netutils v0.28.0/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= +github.com/go-openapi/swag/pools v0.28.0 h1:HPMZWSAfce3rdVTFcjFiCIBtDg9h4x2QlRrHipwhxeU= +github.com/go-openapi/swag/pools v0.28.0/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= +github.com/go-openapi/swag/stringutils v0.28.0 h1:ixsc9iYgDPubHL/8nSkbnryEHpD2VRlBMLKpQyPXcDU= +github.com/go-openapi/swag/stringutils v0.28.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= +github.com/go-openapi/swag/typeutils v0.28.0 h1:nRBKSBXjDgf01VDPB3fWeD9nQuhCOVeIYAkUx2tbkyY= +github.com/go-openapi/swag/typeutils v0.28.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= +github.com/go-openapi/swag/yamlutils v0.28.0 h1:TV3JXH6DS46KUroDtMLAYHGkdWf5VDq3wVWFirmzROY= +github.com/go-openapi/swag/yamlutils v0.28.0/go.mod h1:x0q/yndZHEgk9Rx3DyDqzFUmHy55KTvIZldvF2dTJXs= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= +github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= +github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6 h1:teYtXy9B7y5lHTp8V9KPxpYRAVA7dozigQcMiBust1s= +github.com/go-quicktest/qt v1.101.1-0.20240301121107-c6c8733fa1e6/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI= +github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/godbus/dbus/v5 v5.2.2 h1:TUR3TgtSVDmjiXOgAAyaZbYmIeP3DPkld3jgKGV8mXQ= +github.com/godbus/dbus/v5 v5.2.2/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= +github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg= +github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/cadvisor/lib v0.60.5 h1:C2Ty0ccuKDQnFW4vCSa58wmjc26jL6GiwGEY00pQcIg= +github.com/google/cadvisor/lib v0.60.5/go.mod h1:htHKT0OSYO6zaik+iLOo3Wj1mf/5l8uV5TJaqLz13oM= +github.com/google/cel-go v0.29.2 h1:ZtDxkeiMmz0mxbKDYiNkE5Lk7V5edMRcaaDf2jX002k= +github.com/google/cel-go v0.29.2/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= +github.com/google/certtostore v1.0.6 h1:LlCIgyTvDxTlcncMPTSYZGo6lCsiHzO6Dy7ff6ltk/0= +github.com/google/certtostore v1.0.6/go.mod h1:2N0ZPLkGvQWhYvXaiBGq02r71fnSLfq78VKIWQHr1wo= +github.com/google/deck v0.0.0-20230104221208-105ad94aa8ae h1:Iy1Ad7L9qPtNAFJad+Ch2kwDXrcwu7QUBR0bfChjnEM= +github.com/google/deck v0.0.0-20230104221208-105ad94aa8ae/go.mod h1:DoDv8G58DuLNZF0KysYn0bA/6ZWhmRW3fZE2VnGEH0w= +github.com/google/gnostic-models v0.7.0 h1:qwTtogB15McXDaNqTZdzPJRHvaVJlAl+HVQnLmJEJxo= +github.com/google/gnostic-models v0.7.0/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo= +github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/nftables v0.3.0 h1:bkyZ0cbpVeMHXOrtlFc8ISmfVqq5gPJukoYieyVmITg= +github.com/google/nftables v0.3.0/go.mod h1:BCp9FsrbF1Fn/Yu6CLUc9GGZFw/+hsxfluNXXmxBfRM= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50 h1:PlNWJRxu5APSV0pWqfIsZ0qt9OOGHSWfZQ4zvx+WgWs= +github.com/google/pprof v0.0.0-20261016150608-1facf8f91b50/go.mod h1:yUo1AMMpsPIDFGuwDK8nLcf8+vvAd5l2O6JDZ6hpwrM= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo= +github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= +github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0 h1:QGLs/O40yoNK9vmy4rhUGBVyMf1lISBGtXRpsu/Qu/o= +github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus v1.1.0/go.mod h1:hM2alZsMUni80N33RBe6J0e423LB+odMj7d3EMP9l20= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3 h1:B+8ClL/kCQkRiU82d9xajRPKYMrB7E0MbtzWVi1K4ns= +github.com/grpc-ecosystem/go-grpc-middleware/v2 v2.3.3/go.mod h1:NbCUVmiS4foBGBHOYlCT25+YmGpJ32dZPi75pGEUpj4= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/intel/goresctrl v0.12.0 h1:F44m7jiVgOdqWfTTWaREF+5HTeX3i06qhvpuzpnrBko= +github.com/intel/goresctrl v0.12.0/go.mod h1:5GWtmPY4BWl/a9rU8apGED9Xul5b5WoLtg/qOWaghWU= +github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0= +github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.12.0 h1:hWwax8YiGT0YiN50U1oIDn5kgR7KC2tG3rmavwpPkxY= +github.com/jackc/pgx/v5 v5.12.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= +github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= +github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= +github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= +github.com/jsimonetti/rtnetlink/v2 v2.0.1 h1:xda7qaHDSVOsADNouv7ukSuicKZO7GgVUCXxpaIEIlM= +github.com/jsimonetti/rtnetlink/v2 v2.0.1/go.mod h1:7MoNYNbb3UaDHtF8udiJo/RH6VsTKP1pqKLUTVCvToE= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/k3s-io/containerd/v2 v2.3.7-k3s1 h1:ofqwSFvzR4IixfgpDUAEdhFpcW2nio8Lapm2CNdRYPg= +github.com/k3s-io/containerd/v2 v2.3.7-k3s1/go.mod h1:Ht5zD+4jdudh/ODrXGVJoFVs2BkiUeTuxOhHtHFSYWs= +github.com/k3s-io/helm-controller v0.17.9 h1:HhZTiFhVDzhbAYeb/aSlExWhJTnDTpHypMqu5Mh8Uow= +github.com/k3s-io/helm-controller v0.17.9/go.mod h1:iNhJkyNxQo3sG9PHvTDw/FFm0eVDo/CSsDjl1Gls3Pg= +github.com/k3s-io/kine v0.17.5 h1:QHFCxnRqLvpstdUE86BAUCPiJjOxxV3mBe6pb/fOeYQ= +github.com/k3s-io/kine v0.17.5/go.mod h1:S20DYl8Mn/tV5bc5hXxIosjUlleR70fr6OoflL6hhAU= +github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1 h1:TsMLMSe0ahpSZFqjFUH9Dyh5uQSvNBBk8yth4Z3h1MU= +github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api v1.37.2-k3s1/go.mod h1:6V8Gb6wznJYVPToj8CLxgbxsFeeGIswNZCE7cy+xT90= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= +github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= +github.com/knqyf263/go-plugin v0.9.0 h1:CQs2+lOPIlkZVtcb835ZYDEoyyWJWLbSTWeCs0EwTwI= +github.com/knqyf263/go-plugin v0.9.0/go.mod h1:2z5lCO1/pez6qGo8CvCxSlBFSEat4MEp1DrnA+f7w8Q= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= +github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= +github.com/lithammer/dedent v1.1.0 h1:VNzHMVCBNG1j0fh3OrsFRkVUwStdDArbgBWoPAffktY= +github.com/lithammer/dedent v1.1.0/go.mod h1:jrXYCQtgg0nJiN+StA2KgR7w6CiQNv9Fd/Z9BP0jIOc= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U= +github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/mdlayher/netlink v1.11.2 h1:HKh2jqe+omdSWcQ88nrT7INE61B0NXfiSPFdgL4YbNI= +github.com/mdlayher/netlink v1.11.2/go.mod h1:uT2Yc/QLaZubzDpZIBi9d4GoeLwtp3x1AMeqSRrK2sA= +github.com/mdlayher/socket v0.6.1 h1:M7uj2NtuujUY4mYr1C57NmfNiRHbkKpnBxO856lsc3A= +github.com/mdlayher/socket v0.6.1/go.mod h1:+/SGtqc9V+5dAuRgQsU0fGBI+oRDiW7O2Obx10OIWfg= +github.com/mdlayher/vsock v1.2.1 h1:pC1mTJTvjo1r9n9fbm7S1j04rCgCzhCOS5DY0zqHlnQ= +github.com/mdlayher/vsock v1.2.1/go.mod h1:NRfCibel++DgeMD8z/hP+PPTjlNJsdPOmxcnENvE+SE= +github.com/miekg/pkcs11 v1.1.2 h1:/VxmeAX5qU6Q3EwafypogwWbYryHFmF2RpkJmw3m4MQ= +github.com/miekg/pkcs11 v1.1.2/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4= +github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.3.0 h1:HM4pFCSQq/TK+j0/zmorSh5ddh81iDgRgU0BG0Vz/YU= +github.com/minio/minio-go/v7 v7.3.0/go.mod h1:KUPWdecEO1LWyUz+sTGXAuf2jZHrPh5fCsRH86QbPfk= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/moby/ipvs v1.1.0 h1:ONN4pGaZQgAx+1Scz5RvWV4Q7Gb+mvfRh3NsPS+1XQQ= +github.com/moby/ipvs v1.1.0/go.mod h1:4VJMWuf098bsUMmZEiD4Tjk/O7mOn3l1PTD3s4OoYAs= +github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg= +github.com/moby/locker v1.0.1/go.mod h1:S7SDdo5zpBK84bzzVlKr2V0hz+7x9hWbYC/kq7oQppc= +github.com/moby/spdystream v0.5.1 h1:9sNYeYZUcci9R6/w7KDaFWEWeV4LStVG78Mpyq/Zm/Y= +github.com/moby/spdystream v0.5.1/go.mod h1:xBAYlnt/ay+11ShkdFKNAG7LsyK/tmNBVvVOwrfMgdI= +github.com/moby/sys/capability v0.4.0 h1:4D4mI6KlNtWMCM1Z/K0i7RV1FkX+DBDHKVJpCndZoHk= +github.com/moby/sys/capability v0.4.0/go.mod h1:4g9IK291rVkms3LKCDOoYlnV8xKwoDTpIrNEE35Wq0I= +github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg= +github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= +github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU= +github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko= +github.com/moby/sys/signal v0.7.1 h1:PrQxdvxcGijdo6UXXo/lU/TvHUWyPhj7UOpSo8tuvk0= +github.com/moby/sys/signal v0.7.1/go.mod h1:Se1VGehYokAkrSQwL4tDzHvETwUZlnY7S5XtQ50mQp8= +github.com/moby/sys/symlink v0.3.0 h1:GZX89mEZ9u53f97npBy4Rc3vJKj7JBDj/PN2I22GrNU= +github.com/moby/sys/symlink v0.3.0/go.mod h1:3eNdhduHmYPcgsJtZXW1W4XUJdZGBIkttZ8xKqPUJq0= +github.com/moby/sys/user v0.4.1 h1:RgjRlaDKi/Xmyrz4t8lyzXT6v2ooFeO/7xtchmhVWE0= +github.com/moby/sys/user v0.4.1/go.mod h1:E9QsW5WRe1kUAf7kW8hXKwu1uhsZEAdPLYHYSDudF4Y= +github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g= +github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= +github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= +github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= +github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= +github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f h1:y5//uYreIhSUg3J1GEMiLbxo1LJaP8RfCpH6pymGZus= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/nats-io/jsm.go v0.5.1 h1:RK474bN3qXYGrOHN61reeH3HPKWyH/l2aD8gMWwMuhc= +github.com/nats-io/jsm.go v0.5.1/go.mod h1:c8sdR16B2iX6LRQMHueeEiHYykEaAEkRdsiryceIpwE= +github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc= +github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc= +github.com/nats-io/nats-server/v2 v2.15.2 h1:yLsgt2kslgymvxvjFq1WGWck5hkat2YYfbXvQ145tzU= +github.com/nats-io/nats-server/v2 v2.15.2/go.mod h1:VXHCZgDglV5wO2B8ZE58yG2HzqxQxYUbQqibUh5Xcr8= +github.com/nats-io/nats.go v1.55.0 h1:Ng8QKHdvdHIWoaiq0+d/aH1BWkxvcJxWJ0Y/9BPKx3M= +github.com/nats-io/nats.go v1.55.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k= +github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg= +github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= +github.com/onsi/ginkgo/v2 v2.32.1 h1:6tlvcDm/3sE8lGJbZ4+d4mO3RLy24/tQWOFzVSQNIfw= +github.com/onsi/ginkgo/v2 v2.32.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= +github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I= +github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg= +github.com/opencontainers/cgroups v0.0.7 h1:FqhggFhigAMgKKwy39jweWX3h7Ha6VBF/qNR6Sso3oc= +github.com/opencontainers/cgroups v0.0.7/go.mod h1:hPBRvnBhLZueEN0eJyozMeM3HeFGYlZW9KnO//px6G4= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= +github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= +github.com/opencontainers/runtime-spec v1.3.0 h1:YZupQUdctfhpZy3TM39nN9Ika5CBWT5diQ8ibYCRkxg= +github.com/opencontainers/runtime-spec v1.3.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116 h1:tAKu3NkKWZYpqBSOJKwTxT1wIGueiF7gcmcNgr5pNTY= +github.com/opencontainers/runtime-tools v0.9.1-0.20251114084447-edf4cb3d2116/go.mod h1:DKDEfzxvRkoQ6n9TGhxQgg2IM1lY4aM0eaQP4e3oElw= +github.com/opencontainers/selinux v1.15.1 h1:ERxeh5caJvCzNAKdI8WQbJmB1LDTn4BuaAg8wihLBpA= +github.com/opencontainers/selinux v1.15.1/go.mod h1:LenyElirjUHszfxrjuFqC85HIeXZKumHcKMQtnaDlQQ= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= +github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc= +github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7 h1:Dx7Ovyv/SFnMFw3fD4oEoeorXc6saIiQ23LrGLth0Gw= +github.com/petermattis/goid v0.0.0-20240813172612-4fcff4a6cae7/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pquerna/cachecontrol v0.1.0 h1:yJMy84ti9h/+OEWa752kBTKv4XC30OtVVHYv/8cTqKc= +github.com/pquerna/cachecontrol v0.1.0/go.mod h1:NrUG3Z7Rdu85UNR3vm7SOsl1nFIeSiQnrHV5K9mBcUI= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= +github.com/prometheus/common v0.72.1 h1:ZAiQed/nk8IIcsdzb2TlJu23NEUDyDLQ9TXTN2WRK6Y= +github.com/prometheus/common v0.72.1/go.mod h1:1IoBY4IRaJnhs2ESjNzjilP1cJ/P8pimGoomq7zRXrA= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= +github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= +github.com/rancher/lasso v0.2.7 h1:N56Pm8KJSk7gRVYILSGb35QBfjcDDeGFMfwUCivsbeg= +github.com/rancher/lasso v0.2.7/go.mod h1:L3ol8PdO21KoMhNa3RWjpR3ZBnE70JCAod1nJuOvT1E= +github.com/rancher/wrangler/v3 v3.5.1 h1:o2iLDoqTTkwVenZ521YhcH/0N2CFktp8aXb0f96aYMU= +github.com/rancher/wrangler/v3 v3.5.1/go.mod h1:G5moxB9PpU5MUXavc89NS6Mpfgr8Nfmf9DZ3BkGgeYM= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/safchain/ethtool v0.6.2 h1:O3ZPFAKEUEfbtE6J/feEe2Ft7dIJ2Sy8t4SdMRiIMHY= +github.com/safchain/ethtool v0.6.2/go.mod h1:VS7cn+bP3Px3rIq55xImBiZGHVLNyBh5dqG6dDQy8+I= +github.com/sasha-s/go-deadlock v0.3.5 h1:tNCOEEDG6tBqrNDOX35j/7hL5FcFViG6awUGROb2NsU= +github.com/sasha-s/go-deadlock v0.3.5/go.mod h1:bugP6EGbdGYObIlx7pUZtWqlvo8k9H6vCBBsiChJQ5U= +github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= +github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/shengdoushi/base58 v1.0.0 h1:tGe4o6TmdXFJWoI31VoSWvuaKxf0Px3gqa3sUWhAxBs= +github.com/shengdoushi/base58 v1.0.0/go.mod h1:m5uIILfzcKMw6238iWAhP4l3s5+uXyF3+bJKUNhAL9I= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo= +github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= +github.com/smallstep/pkcs7 v0.2.1 h1:6Kfzr/QizdIuB6LSv8y1LJdZ3aPSfTNhTLqAx9CTLfA= +github.com/smallstep/pkcs7 v0.2.1/go.mod h1:RcXHsMfL+BzH8tRhmrF1NkkpebKpq3JEM66cOFxanf0= +github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js= +github.com/soheilhy/cmux v0.1.5/go.mod h1:T7TcVDs9LWfQgPlPsdngu6I6QIoyIFZDDC6sNE1GqG0= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 h1:pnnLyeX7o/5aX8qUQ69P/mLojDqwda8hFOCBTmP/6hw= +github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6/go.mod h1:39R/xuhNgVhi+K0/zst4TLrJrVmbm6LVgl4A0+ZFS5M= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/t4db/t4 v1.1.16 h1:UmZ+7azdjC3dCEF1x6yiMgrjwPD/EP4soLKWGhdzr10= +github.com/t4db/t4 v1.1.16/go.mod h1:sEVCjPeOt4xRB2T7zaQJekPloiRys+mAWNekKBLEXhM= +github.com/tchap/go-patricia/v2 v2.3.3 h1:xfNEsODumaEcCcY3gI0hYPZ/PcpVv5ju6RMAhgwZDDc= +github.com/tchap/go-patricia/v2 v2.3.3/go.mod h1:VZRHKAb53DLaG+nA9EaYYiaEx6YztwDlLElMsnSHD4k= +github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA= +github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU= +github.com/tidwall/btree v1.8.2 h1:mTY5iM4UTh2e80TG7RHDQQmnAY3xGNQA/DbU0olkhkA= +github.com/tidwall/btree v1.8.2/go.mod h1:jBbTdUWhSZClZWoDg54VnvV7/54modSOzDN7VXftj1A= +github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= +github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= +github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75 h1:6fotK7otjonDflCTK0BCfls4SPy3NcCVb5dqqmbRknE= +github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75/go.mod h1:KO6IkyS8Y3j8OdNO85qEYBsRPuteD+YciPomcXdrMnk= +github.com/urfave/cli/v2 v2.27.7 h1:bH59vdhbjLv3LAvIu6gd0usJHgoTTPhCFib8qqOwXYU= +github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4= +github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0= +github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4= +github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY= +github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510 h1:S2dVYn90KE98chqDkyE9Z4N61UnQd+KOfgp5Iu53llk= +github.com/xiang90/probing v0.0.0-20221125231312-a49e3df8f510/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xlab/treeprint v1.2.0 h1:HzHnuAF1plUN2zGlAFHbSQP2qJ0ZAD3XF5XD7OesXRQ= +github.com/xlab/treeprint v1.2.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4= +github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= +github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU= +go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk= +go.etcd.io/etcd/api/v3 v3.7.3 h1:2tumepXe+wi7Wab64uUO71K7ISQyUWLGC1DJbbc59sY= +go.etcd.io/etcd/api/v3 v3.7.3/go.mod h1:HOR9Qn4gb/1/hVAmYprmlLpvTe6ZgfgNS9Z/+Ty65po= +go.etcd.io/etcd/client/pkg/v3 v3.7.3 h1:5zMwNu3ycrzCeA5NwOfQbxFRhqq974chq1DrYMua4QI= +go.etcd.io/etcd/client/pkg/v3 v3.7.3/go.mod h1:/OhzqYrF0U7d1NOk55VMyUQGbYD1WoIe4bJwxb47wOk= +go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q= +go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE= +go.etcd.io/etcd/pkg/v3 v3.7.3 h1:FoxH2JLECo/PYEHilgBFqz7Zlyiv5Sd20OlOOYESUos= +go.etcd.io/etcd/pkg/v3 v3.7.3/go.mod h1:KMluxIriMegJqCjcmNmt1rdzyzZHvzsojBGmkN0ArYI= +go.etcd.io/etcd/server/v3 v3.7.3 h1:KcTZ/aEZrOiQe0/kdr7iYYcvyfbEoOwDOacHkz8xwZc= +go.etcd.io/etcd/server/v3 v3.7.3/go.mod h1:NElta3Kom1fQux/MhT9Vw5YRQMSaXk6d0MHkvLMpzO8= +go.etcd.io/raft/v3 v3.7.0 h1:BGzlwx07bLv8PW6OU5HObuz1y4hlPZUXA07pM1mPUh4= +go.etcd.io/raft/v3 v3.7.0/go.mod h1:6gX6T2X907DjnjsFLODnTxba77stjs84W9gTTI0GUNA= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful v0.69.0 h1:GwgkQ+Ucm8Bx9LRrrix54FPksT775nYDN+9M20SI3XU= +go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful v0.69.0/go.mod h1:z5qVAACw5BI1yBkWfJRcU4qp+JDQ4fdFmdS4hTJVhH0= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0 h1:B2h3uqicet1CT2N5TOFhS+Gq++9i0/CLmaxvhmhtP5s= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.71.0/go.mod h1:dylvB+ZiiwMvsDij9O84Uy7SijLgHMX4mbkncds+4Sw= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04= +go.opentelemetry.io/contrib/propagators/b3 v1.44.0 h1:1IFH4oFKK8KupzIelCl3u+bkxpGRps1oWRjQI2+TTWs= +go.opentelemetry.io/contrib/propagators/b3 v1.44.0/go.mod h1:JqWFXsc7VDaqIyubFhEd2cPHqsrzqP0Lvn783SUwyro= +go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= +go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0 h1:w53CDeOA/Kurp7yRsegSr6pbbr759dOvJ+yNmWM6Hxs= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.46.0/go.mod h1:BOmGMCbAtvcJiSJ+hLuhgPLdDbimnraSl8irz3iY8sY= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0 h1:lsA/S1bxgdbyFGkTj+3meEdJ6ADVU7QoFstV6MXgE68= +go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0/go.mod h1:L7u+MirGoB1bjeLH66+xDykF4RC8C3RN7lIFpBiewUo= +go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= +go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= +go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= +go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= +go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= +go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= +go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= +go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= +go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= +go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= +go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211123203042-d83791d6bcd9/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk= +golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98= +golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= +golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto/googleapis/api v0.0.0-20261104224025-d1e00e9f33ab h1:n6IDWZ1RzI/NberLoLLFNrjl1H45uhc4+WYsUf5lPPc= +google.golang.org/genproto/googleapis/api v0.0.0-20261104224025-d1e00e9f33ab/go.mod h1:vHV3wJM9WZyfV7GyB+OQGq5dWVrFwCDxapPK4WlRD88= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b h1:6WNWHZk91dp4gZ25642OALkuG1UVNZbwENJD19DnB8k= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261019180522-ce908d29299b/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnfEbYzo= +gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= +gopkg.in/go-jose/go-jose.v2 v2.6.3 h1:nt80fvSDlhKWQgSWyHyy5CfmlQr+asih51R8PTWNKKs= +gopkg.in/go-jose/go-jose.v2 v2.6.3/go.mod h1:zzZDPkNNw/c9IE7Z9jr11mBZQhKQTMzoEEIoEdZlFBI= +gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw= +gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= +gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= +gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +k8s.io/api v0.37.2 h1:PnxqnUFy93jr2GcpWDkKOm8wfy25kT9wa572MuQS8oc= +k8s.io/api v0.37.2/go.mod h1:+NVRLft99kx+Jg9v34GmHw867Dapim89TSyCsn2hK+M= +k8s.io/apiextensions-apiserver v0.37.2 h1:myaUiAlm1NRLYdpAvWYTqdgeiCepFupJiRFVVueMUYw= +k8s.io/apiextensions-apiserver v0.37.2/go.mod h1:BFl1aPC89HsgFgYI+3xpFtckvkAeenDTZP84njA9yw4= +k8s.io/apimachinery v0.37.2 h1:G4t9RGoPDbQML38hz/kQQiltttgd3egg2ODCR8aIc2o= +k8s.io/apimachinery v0.37.2/go.mod h1:qaAvSNvgU2x07wRM95MSHSJTPQ/ob/LeNAGbeDgqQJg= +k8s.io/apiserver v0.37.2 h1:9Jq73PeHAA0RThpW7ou6lBcO2+SxLcPrAgleONSMUNQ= +k8s.io/apiserver v0.37.2/go.mod h1:d0P4WZtt6XMYAo6VN8dDPRnvY3O34quI3pOuxtfgAgM= +k8s.io/cli-runtime v0.37.2 h1:EpE50B2FmXz8SxkYqoS2q0piDk1qe7g9dGZGIW+apws= +k8s.io/cli-runtime v0.37.2/go.mod h1:0IDMrrzVnj1cqBlCll8oGSOb2js6mSy0ALtbh0MsYyc= +k8s.io/client-go v0.37.2 h1:sgFtyRZukGkOrsu+QgS7LYnbFFJ5ut3MchdBNduD//E= +k8s.io/client-go v0.37.2/go.mod h1:bo3LFC8YbCtKFPX21Yj8puMsoJLAv/+SvuOODma0s54= +k8s.io/cloud-provider v0.37.2 h1:o3rfu8SBGTm7ut/OlTR7VtDsz/cutoYs7U7dC+OSSxY= +k8s.io/cloud-provider v0.37.2/go.mod h1:kI8o8BEwF1vy+jJFSEdd967U91OokcQ/YTlY76xqZAQ= +k8s.io/cluster-bootstrap v0.37.2 h1:lw5dFPHIPFylnMktkPrPqRQFo6jcXG/BwWXcIns9bPY= +k8s.io/cluster-bootstrap v0.37.2/go.mod h1:AJqybtMW+7anKr/GcDw5V6BMkhcviOHZC5WkQa0l8YU= +k8s.io/component-base v0.37.2 h1:Ia9IKTg1yWrUntJU5lVetapkC9pXlLg9L6P3R1IkbcY= +k8s.io/component-base v0.37.2/go.mod h1:qq+ueHZyLfzRJzxyDoyxHWNhF1JPv4zm3hcaddXWDvY= +k8s.io/component-helpers v0.37.2 h1:TQBsmHFs8gpfiyPFvyMaxqTgojtcXR2mVj+knnycln0= +k8s.io/component-helpers v0.37.2/go.mod h1:HZMT6lvkix4wkgYYXZJ/45BbYM1TZoOlANisHn7FoVY= +k8s.io/controller-manager v0.37.2 h1:i6v/0wHbTNnUfi2HTFcoZRCitZk+pyFi90FdUs+u8+E= +k8s.io/controller-manager v0.37.2/go.mod h1:fdhg25yxep7J33eYVVc8MOKCaS8G6TMVHMeJiPKvCUg= +k8s.io/cri-client v0.37.2 h1:tksqy98CYh/5wDxgWHflZ4QKU7cF50ES+gsZi/ybPik= +k8s.io/cri-client v0.37.2/go.mod h1:RpdqQcggeZyjkpNJk8McIgeBBuRCrdLgoZ4XtmTyAOE= +k8s.io/cri-streaming v0.37.2 h1:0SqyYSI4EEmePinyIv57hZqK0ELfBaa0seB+ld/dLkk= +k8s.io/cri-streaming v0.37.2/go.mod h1:4HAIG+9rxyxGas0z8IKpTYpe63h3LZx/JQPE2VY/tI8= +k8s.io/csi-translation-lib v0.37.2 h1:SfDJ0/2gyBSvmEqVsw+xlgA3ac2kD4vK4GNeULO+uNk= +k8s.io/csi-translation-lib v0.37.2/go.mod h1:LEIQHiEIAsllV0z+d6Ro06r+poBK9mJIqduON7FFedw= +k8s.io/dynamic-resource-allocation v0.37.2 h1:HpaB0hW3oBDNVhpDYnceTanFeaRcDRmduTpdbf4kjAs= +k8s.io/dynamic-resource-allocation v0.37.2/go.mod h1:h4l9zHFE6Rhyv3JDcIa+wrlj2HUNsIuzKj5La0zCgCI= +k8s.io/endpointslice v0.37.2 h1:sKKzhCXpPaEbc0d7nYHDh9beabNxpcMmc/I5SlHFB88= +k8s.io/endpointslice v0.37.2/go.mod h1:pPygn+c02e9r5KTLCeXLt6EJdaVIvT282fm6PVBcifY= +k8s.io/externaljwt v0.37.2 h1:egsM4R0CHSGwsy1zpa1td1Q38V/1B2W31efYYv21LyY= +k8s.io/externaljwt v0.37.2/go.mod h1:MfUIWFM2xxGdIMdh3aOsMAZj8sFgHbngEd+ajFzD1qk= +k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= +k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= +k8s.io/kms v0.37.2 h1:d9u/eizxE9pSa3jjnvoaLvvb9LwiypwkZ9xD4I4ZbTo= +k8s.io/kms v0.37.2/go.mod h1:0U6zfwLkfJr9O/jLgz2GARnKLh2uIhkq2EeaU66J5ow= +k8s.io/kube-aggregator v0.37.2 h1:cUT/C/WM3UtoREoTYthSCFxldpdG3y5q9UniWYxcmPE= +k8s.io/kube-aggregator v0.37.2/go.mod h1:GsqVEKZkXn49ObCHg5NvYngIhM18Uup1Bg6Q3Lzu89A= +k8s.io/kube-controller-manager v0.37.2 h1:N/yqaHHyiiyEID4TLtjUn8j1mtnlFsUkM0llsmsKlEs= +k8s.io/kube-controller-manager v0.37.2/go.mod h1:5AFrerglQQR5RvzUtJePOOZv7iirJkCFxZDTocl7IjE= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/kube-proxy v0.37.2 h1:8SLRQGq7H/4Or3AF4NOQvVjgpsiZ5/fsIpfc2ZA5MDo= +k8s.io/kube-proxy v0.37.2/go.mod h1:cUG2cHe/3MBOgsI7tOCykuXPO7UJzlA7A7V2rmC8fqk= +k8s.io/kube-scheduler v0.37.2 h1:MC2G83PTIN0KM7RppCLaqL93iPhuKvCbwfnDiAFbFpw= +k8s.io/kube-scheduler v0.37.2/go.mod h1:axqVY5gSJ3HKjTljVQCnNPw9+mgSLN6OEuAP+W5ZXAM= +k8s.io/kubectl v0.37.2 h1:AGGIhrGSsXtrL6BZWf7Hp2K9yB+2qdx7wovsOP1MiCg= +k8s.io/kubectl v0.37.2/go.mod h1:0nyX9up426PgGMcGkWjF1DeipLkd41eKZHoLDgop20k= +k8s.io/kubelet v0.37.2 h1:AaRApKAcqmMD4pxmsxdghJHbTNfOxYOIlPCARw8+01A= +k8s.io/kubelet v0.37.2/go.mod h1:dh6HRbWZOHzvIIAkLy1U62//2wqQ86GCxkqL0ZDVDGI= +k8s.io/kubernetes v1.37.2 h1:A2VDEiObzkYqFTKhSsn0ZEb0RlLEXpHWj93gi2HqEwE= +k8s.io/kubernetes v1.37.2/go.mod h1:zAK7e3i5feyBL/bhucQnA5VRKuyrS8F+ijHJkZzQaWw= +k8s.io/metrics v0.37.2 h1:CeIZd07BO8vuraDyd0ooQmsLi2Rutj76zThEf72rcWU= +k8s.io/metrics v0.37.2/go.mod h1:9HzCbIyPruAmoKmjoBjLEYAlLhAapAj1vvzkbhBDg6E= +k8s.io/mount-utils v0.37.2 h1:OUmG8B4N09N1DcJPd3jADyxQoC4212cDtVAGox7Oe3g= +k8s.io/mount-utils v0.37.2/go.mod h1:uGJRC7u42QGYbHlHxt/5J2rXrfgv3XNYU3I0ZXVnAck= +k8s.io/pod-security-admission v0.37.2 h1:mnfCR7fUzsvtiSiYZD9HTcTJ9cpJDMnQn++9Rq1mlrc= +k8s.io/pod-security-admission v0.37.2/go.mod h1:k0fkpWwMOyBNAkKjcg8MIC107TPYTSXbfWECcG90zks= +k8s.io/streaming v0.37.2 h1:xmzp9nbqIbjvsRcqrBYa+K5XPQ6Jy/Dm3zZ8mN916AI= +k8s.io/streaming v0.37.2/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= +k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= +k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +modernc.org/cc/v4 v4.30.3 h1:aDq8gIX1X7+VFgO/JYYji6pLWL2H4tv3g8WatT3KCys= +modernc.org/cc/v4 v4.30.3/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.37.0 h1:BAuJCUtIHIxFIYaFhqXIw5YaoMBlNCUlFovejHfMip4= +modernc.org/ccgo/v4 v4.37.0/go.mod h1:/8627VhwWtAbqUXmPORxFQU5SgLrAx2jl9seLw9GBhY= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.2.0 h1:/Y3LGDMQaoYf55PebP1qsZ5FDGgAZyG1RYKEHeQzh1o= +modernc.org/gc/v3 v3.2.0/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.79.0 h1:9Dvvv++bAMSkSuBzuOFAatbTV5OIoq6Y6FohmD3e7q8= +modernc.org/libc v1.79.0/go.mod h1:uT3kR61NsbeKJSLqq83GJwSnZMVLlSjyAz4DfTaBy1M= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.61.0 h1:sQi63oLQ9uquAUA4CzOisH35Q3pEszkPBuHM0tFL8CY= +modernc.org/sqlite v1.61.0/go.mod h1:f4gr5tbpx2umklaT/QVtbi/50hNdM+4ng+2zMo8KXJ0= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0 h1:/YpDJ4vReG7ZmzSpBGxduXgywWkJU9zHubgJG03MT+Y= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.36.0/go.mod h1:tJo1aepTXyR+8Xs3sUsGBDk4Ub2AM5dPAPKJx0mpm5c= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= +sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= +sigs.k8s.io/knftables v0.0.22 h1:RMbBSxQb4t730I6m492NDzWTOaActPpF9OCACQmF9bE= +sigs.k8s.io/knftables v0.0.22/go.mod h1:tig4GDnk1aG8sNsKW/iqid/PGgVLxJLEZkuUlO5C44Y= +sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= +sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= +sigs.k8s.io/kustomize/kustomize/v5 v5.8.1 h1:Pgsg5psubpVEy7Nf6S89PARg5VmmWUC1l9dC6Dl4PG0= +sigs.k8s.io/kustomize/kustomize/v5 v5.8.1/go.mod h1:0vFa5pQ/elNEQMyiAJuGku9rhAMzz7u9+61hRqFKiwY= +sigs.k8s.io/kustomize/kyaml v0.21.1 h1:IVlbmhC076nf6foyL6Taw4BkrLuEsXUXNpsE+ScX7fI= +sigs.k8s.io/kustomize/kyaml v0.21.1/go.mod h1:hmxADesM3yUN2vbA5z1/YTBnzLJ1dajdqpQonwBL1FQ= +sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= +sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= +sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= +tags.cncf.io/container-device-interface v1.1.0 h1:RnxNhxF1JOu6CJUVpetTYvrXHdxw9j9jFYgZpI+anSY= +tags.cncf.io/container-device-interface v1.1.0/go.mod h1:76Oj0Yqp9FwTx/pySDc8Bxjpg+VqXfDb50cKAXVJ34Q= +tags.cncf.io/container-device-interface/specs-go v1.1.0 h1:QRZVeAceQM+zTZe12eyfuJuuzp524EKYwhmvLd+h+yQ= +tags.cncf.io/container-device-interface/specs-go v1.1.0/go.mod h1:u86hoFWqnh3hWz3esofRFKbI261bUlvUfLKGrDhJkgQ= diff --git a/kube/internal/boot/doc.go b/kube/internal/boot/doc.go new file mode 100644 index 0000000..51ea0f6 --- /dev/null +++ b/kube/internal/boot/doc.go @@ -0,0 +1,3 @@ +// Package boot starts containerd, imports images, and then opens the datastore. +// Image import finishes before Start returns. Kubelet is not started here. +package boot diff --git a/kube/internal/boot/start_linux.go b/kube/internal/boot/start_linux.go new file mode 100644 index 0000000..34c1bc5 --- /dev/null +++ b/kube/internal/boot/start_linux.go @@ -0,0 +1,186 @@ +//go:build linux && cgo + +package boot + +import ( + "context" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "sync" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/containerd" + "github.com/eclipse-iofog/edgelet-kube/internal/images" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" +) + +// Config is the containerd child and the images directory. +// Empty paths use the installed runtime directories. +type Config struct { + // Socket is the containerd gRPC socket. + Socket string + // Root is the containerd persistent directory. + Root string + // State is the containerd transient directory. + State string + // CNIConfDir is the CNI configuration directory. + CNIConfDir string + // ImagesDir is the directory of image archives. + ImagesDir string + // Pull replaces the registry fetch used when ImagesDir is empty. + Pull func(ctx context.Context, ref string) error + // RegistryFile is the registries file. A missing file uses upstream endpoints. + RegistryFile string + // DisableDefaultEndpoint omits the upstream registry for names listed in RegistryFile. + DisableDefaultEndpoint bool + // PauseImage is the sandbox image. + PauseImage string + // Registry prefixes pin-list images. Empty leaves those names unchanged. + Registry string + // Settle is how long a new archive must stay unchanged before import. + Settle time.Duration + // Log receives containerd output. A nil Log uses standard output and error. + Log io.Writer + // Datastore opens the database after image import. Nil leaves it unopened. + // Kube-apiserver is not started. + Datastore func(ctx context.Context) error +} + +// Process is the containerd child started before image import. +type Process struct { + cmd *exec.Cmd + stop sync.Once +} + +// Pid is the containerd child process id. +func (p *Process) Pid() int { + if p == nil || p.cmd == nil || p.cmd.Process == nil { + return 0 + } + return p.cmd.Process.Pid +} + +// Stop ends the containerd child. +func (p *Process) Stop() { + if p == nil { + return + } + p.stop.Do(func() { + containerd.StopChild(p.cmd) + }) +} + +// Start starts the containerd child, imports and pins images, then opens the +// datastore when Config.Datastore is set. An empty images directory pulls the +// pinned list. Start returns after that import and the datastore open. The +// images directory stays watched until ctx is canceled. Image import finishes +// before Start returns. Kubelet is not started. +func Start(ctx context.Context, cfg Config) (*Process, error) { + socket, root, state, cniConf, imagesDir := cfg.paths() + for _, dir := range []string{root, state, cniConf, filepath.Dir(socket), imagesDir} { + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- containerd and CNI traverse these directories + return nil, fmt.Errorf("create runtime directory %s: %w", dir, err) + } + } + stdout, stderr := io.Writer(os.Stdout), io.Writer(os.Stderr) + if cfg.Log != nil { + stdout, stderr = cfg.Log, cfg.Log + } + cmd, err := containerd.StartChild(childArgs(cfg), stdout, stderr) + if err != nil { + return nil, err + } + proc := &Process{cmd: cmd} + if err := waitReady(ctx, socket); err != nil { + proc.Stop() + return nil, err + } + if err := images.Run(ctx, images.Config{ + Dir: imagesDir, + Socket: socket, + Pull: cfg.Pull, + Registry: cfg.Registry, + Settle: cfg.Settle, + Log: cfg.Log, + }); err != nil { + proc.Stop() + return nil, err + } + if cfg.Datastore != nil { + if err := cfg.Datastore(ctx); err != nil { + proc.Stop() + return nil, err + } + } + go func() { + <-ctx.Done() + proc.Stop() + }() + return proc, nil +} + +func (cfg Config) paths() (socket, root, state, cniConf, imagesDir string) { + socket = cfg.Socket + if socket == "" { + socket = paths.ContainerdSocket + } + root = cfg.Root + if root == "" { + root = paths.ContainerdRoot + } + state = cfg.State + if state == "" { + state = paths.ContainerdState + } + cniConf = cfg.CNIConfDir + if cniConf == "" { + cniConf = paths.CNIConfDir + } + imagesDir = cfg.ImagesDir + if imagesDir == "" { + imagesDir = paths.ImagesDir + } + return socket, root, state, cniConf, imagesDir +} + +func childArgs(cfg Config) []string { + var args []string + add := func(name, value string) { + if value != "" { + args = append(args, "--"+name, value) + } + } + add("address", cfg.Socket) + add("root", cfg.Root) + add("state", cfg.State) + add("cni-conf-dir", cfg.CNIConfDir) + add("private-registry", cfg.RegistryFile) + add("pause-image", cfg.PauseImage) + if cfg.DisableDefaultEndpoint { + args = append(args, "--disable-default-registry-endpoint=true") + } + return args +} + +func waitReady(ctx context.Context, socket string) error { + deadline := time.NewTimer(45 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + if _, last = containerd.RuntimeVersion(ctx, socket); last == nil { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return fmt.Errorf("containerd did not become ready: %w", last) + case <-ticker.C: + } + } +} diff --git a/kube/internal/boot/start_linux_test.go b/kube/internal/boot/start_linux_test.go new file mode 100644 index 0000000..2ad1dad --- /dev/null +++ b/kube/internal/boot/start_linux_test.go @@ -0,0 +1,282 @@ +//go:build linux && cgo + +package boot + +import ( + "archive/tar" + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + containerd "github.com/containerd/containerd/v2/client" + "github.com/containerd/containerd/v2/core/images" + "github.com/containerd/containerd/v2/pkg/namespaces" + "github.com/containerd/errdefs" + kubecontainerd "github.com/eclipse-iofog/edgelet-kube/internal/containerd" + kubeimages "github.com/eclipse-iofog/edgelet-kube/internal/images" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "github.com/opencontainers/go-digest" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "golang.org/x/sys/unix" +) + +func TestMain(m *testing.M) { + handled, err := kubecontainerd.MaybeRunChild(os.Args) + if handled { + if err != nil { + fmt.Fprintf(os.Stderr, "containerd child: %v\n", err) + unix.Exit(1) + } + unix.Exit(0) + } + m.Run() +} + +func TestEmptyDirectoryPinsListBeforeKubelet(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-images-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + logFile, err := os.Create(filepath.Join(dir, "child.log")) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = logFile.Close() + }() + + imagesDir := filepath.Join(dir, "images") + sock := filepath.Join(dir, "containerd.sock") + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + + want := airgap.ImagesFor(runtime.GOARCH) + var pulled []string + importedBeforeDatastore := false + proc, err := Start(ctx, Config{ + Socket: sock, + Root: filepath.Join(dir, "root"), + State: filepath.Join(dir, "state"), + CNIConfDir: filepath.Join(dir, "net.d"), + ImagesDir: imagesDir, + Settle: 200 * time.Millisecond, + Log: logFile, + Pull: func(ctx context.Context, ref string) error { + pulled = append(pulled, ref) + return seedImage(ctx, sock, ref) + }, + Datastore: func(context.Context) error { + importedBeforeDatastore = imagePinned(t, sock, want[0]) + return nil + }, + }) + if err != nil { + body, _ := os.ReadFile(logFile.Name()) + t.Fatalf("start: %v\n%s", err, body) + } + t.Cleanup(proc.Stop) + if !importedBeforeDatastore { + t.Fatal("datastore opened before image import") + } + if strings.Join(pulled, "\n") != strings.Join(want, "\n") { + t.Fatalf("pulled %v", pulled) + } + assertPinned(t, sock, want) + assertAbsentFromDefaultNamespace(t, sock, want[0]) + if kubeletRunning() { + t.Fatal("kubelet is running") + } + pid := proc.Pid() + cmdline := processCmdline(t, pid) + if !strings.Contains(cmdline, kubecontainerd.ChildArg) { + t.Fatalf("cmdline %q", cmdline) + } + + const added = "example.com/edgelet-kube-added:1" + if err := os.WriteFile(filepath.Join(imagesDir, "added.tar"), dockerTar(t, added), 0o644); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(15 * time.Second) + for !imagePinned(t, sock, added) { + if time.Now().After(deadline) { + body, _ := os.ReadFile(logFile.Name()) + names := imageNames(t, sock) + t.Fatalf("added image was not imported, have %v\n%s", names, body) + } + time.Sleep(50 * time.Millisecond) + } + if proc.Pid() != pid { + t.Fatalf("containerd pid %d, was %d", proc.Pid(), pid) + } + if processCmdline(t, pid) == "" { + t.Fatal("containerd process exited") + } + if kubeletRunning() { + t.Fatal("kubelet is running") + } +} + +func seedImage(ctx context.Context, socket, ref string) error { + client, err := containerd.New(socket, containerd.WithDefaultNamespace(kubeimages.Namespace)) + if err != nil { + return err + } + defer func() { + _ = client.Close() + }() + ctx = namespaces.WithNamespace(ctx, kubeimages.Namespace) + _, err = client.ImageService().Create(ctx, images.Image{ + Name: ref, + Target: ocispec.Descriptor{ + MediaType: ocispec.MediaTypeImageManifest, + Digest: digest.FromString(ref), + Size: int64(len(ref)), + }, + }) + if err != nil && !errdefs.IsAlreadyExists(err) { + return err + } + return nil +} + +func assertPinned(t *testing.T, socket string, names []string) { + t.Helper() + for _, name := range names { + if !imagePinned(t, socket, name) { + t.Fatalf("%s is not pinned in %s, have %v", name, kubeimages.Namespace, imageNames(t, socket)) + } + } +} + +func imagePinned(t *testing.T, socket, name string) bool { + t.Helper() + client := imageClient(t, socket) + defer func() { + _ = client.Close() + }() + ctx := namespaces.WithNamespace(t.Context(), kubeimages.Namespace) + image, err := client.ImageService().Get(ctx, name) + if err != nil { + if errdefs.IsNotFound(err) { + return false + } + t.Fatal(err) + } + return image.Labels[kubeimages.PinnedLabel] == kubeimages.PinnedValue +} + +func assertAbsentFromDefaultNamespace(t *testing.T, socket, name string) { + t.Helper() + client, err := containerd.New(socket, containerd.WithDefaultNamespace("default")) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = client.Close() + }() + ctx := namespaces.WithNamespace(t.Context(), "default") + _, err = client.ImageService().Get(ctx, name) + if err == nil { + t.Fatalf("%s is visible outside %s", name, kubeimages.Namespace) + } +} + +func imageNames(t *testing.T, socket string) []string { + t.Helper() + client := imageClient(t, socket) + defer func() { + _ = client.Close() + }() + ctx := namespaces.WithNamespace(t.Context(), kubeimages.Namespace) + listed, err := client.ImageService().List(ctx) + if err != nil { + t.Fatal(err) + } + names := make([]string, 0, len(listed)) + for _, image := range listed { + names = append(names, image.Name) + } + return names +} + +func imageClient(t *testing.T, socket string) *containerd.Client { + t.Helper() + client, err := containerd.New(socket, containerd.WithDefaultNamespace(kubeimages.Namespace)) + if err != nil { + t.Fatal(err) + } + return client +} + +func processCmdline(t *testing.T, pid int) string { + t.Helper() + body, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + if err != nil { + if os.IsNotExist(err) { + return "" + } + t.Fatal(err) + } + return string(body) +} + +func kubeletRunning() bool { + entries, err := os.ReadDir("/proc") + if err != nil { + return false + } + for _, entry := range entries { + if _, err := strconv.Atoi(entry.Name()); err != nil { + continue + } + body, err := os.ReadFile("/proc/" + entry.Name() + "/cmdline") + if err != nil || len(body) == 0 { + continue + } + argv0 := strings.TrimRight(string(body), "\x00") + if i := strings.IndexByte(argv0, 0); i >= 0 { + argv0 = argv0[:i] + } + if filepath.Base(argv0) == "kubelet" { + return true + } + } + return false +} + +func dockerTar(t *testing.T, ref string) []byte { + t.Helper() + config := []byte(`{"architecture":"amd64","os":"linux","config":{},"rootfs":{"type":"layers","diff_ids":[]}}`) + manifest := []byte(fmt.Sprintf(`[{"Config":"config.json","RepoTags":[%q],"Layers":[]}]`, ref)) + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for _, file := range []struct { + name string + body []byte + }{ + {name: "config.json", body: config}, + {name: "manifest.json", body: manifest}, + } { + hdr := &tar.Header{Name: file.name, Mode: 0o644, Size: int64(len(file.body))} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(file.body); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} diff --git a/kube/internal/bundle/archive.go b/kube/internal/bundle/archive.go new file mode 100644 index 0000000..3e6f393 --- /dev/null +++ b/kube/internal/bundle/archive.go @@ -0,0 +1,323 @@ +package bundle + +import ( + "archive/tar" + "bytes" + "cmp" + "fmt" + "io" + "io/fs" + "os" + "path" + "path/filepath" + "slices" + "strings" + "time" + + "github.com/klauspost/compress/zstd" +) + +// Member is one path stored in the zstd bundle. +type Member struct { + Name string + Link string + Dir bool +} + +// Pack writes the stage directory as a zstd tar. +// The stage holds bin/edgelet-kube, the containerd shim, crun, the CNI +// multicall and its four symlinks, and the selective aux set. +// An OCI image is rejected. +func Pack(stageDir string) ([]byte, error) { + entries, err := collect(stageDir) + if err != nil { + return nil, err + } + if err := validate(entries); err != nil { + return nil, err + } + return archive(entries) +} + +// Contents lists the members of a bundle written by Pack. +func Contents(packed []byte) ([]Member, error) { + zr, err := zstd.NewReader(bytes.NewReader(packed)) + if err != nil { + return nil, fmt.Errorf("zstd reader: %w", err) + } + defer zr.Close() + tr := tar.NewReader(zr) + var members []Member + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return nil, fmt.Errorf("tar read: %w", err) + } + members = append(members, Member{ + Name: strings.TrimSuffix(hdr.Name, "/"), + Link: hdr.Linkname, + Dir: hdr.FileInfo().IsDir(), + }) + } + slices.SortFunc(members, func(a, b Member) int { + return cmp.Compare(a.Name, b.Name) + }) + return members, nil +} + +type entry struct { + name string + path string + mode os.FileMode + link string + size int64 +} + +func collect(stageDir string) ([]entry, error) { + stageDir = filepath.Clean(stageDir) + info, err := os.Stat(stageDir) + if err != nil { + return nil, fmt.Errorf("stage: %w", err) + } + if !info.IsDir() { + return nil, fmt.Errorf("stage %s is not a directory", stageDir) + } + var entries []entry + err = filepath.WalkDir(stageDir, func(p string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if p == stageDir { + return nil + } + rel, err := filepath.Rel(stageDir, p) + if err != nil { + return err + } + rel = filepath.ToSlash(rel) + info, err := d.Info() + if err != nil { + return err + } + e := entry{name: rel, path: p, mode: info.Mode()} + switch { + case info.Mode()&os.ModeSymlink != 0: + target, err := os.Readlink(p) + if err != nil { + return fmt.Errorf("read link %s: %w", rel, err) + } + e.link = target + case info.IsDir(): + case info.Mode().IsRegular(): + e.size = info.Size() + default: + return fmt.Errorf("bundle member %s has an unsupported type", rel) + } + entries = append(entries, e) + return nil + }) + if err != nil { + return nil, err + } + slices.SortFunc(entries, func(a, b entry) int { + return cmp.Compare(a.name, b.name) + }) + return entries, nil +} + +func validate(entries []entry) error { + byName := make(map[string]entry, len(entries)) + for _, e := range entries { + if !validBundlePath(e.name) { + return fmt.Errorf("bundle path %s is invalid", e.name) + } + if imageMember(e.name) { + return fmt.Errorf("bundle member %s is an OCI image", e.name) + } + if flannelMember(e.name) { + return fmt.Errorf("bundle member %s is flannel", e.name) + } + if e.link != "" && linkEscapes(e.name, e.link) { + return fmt.Errorf("bundle link %s -> %s leaves the bundle", e.name, e.link) + } + parts := strings.Split(e.name, "/") + if parts[0] != "bin" { + return fmt.Errorf("bundle member %s is outside bin", e.name) + } + if len(parts) == 2 && !allowedBinChild(parts[1]) { + return fmt.Errorf("bundle member %s is not a runtime binary", e.name) + } + byName[e.name] = e + } + for _, name := range requiredFiles { + e, ok := byName[name] + if !ok || !e.mode.IsRegular() { + return fmt.Errorf("bundle is missing %s", name) + } + if e.size == 0 { + return fmt.Errorf("bundle member %s is empty", name) + } + } + for _, link := range requiredLinks { + e, ok := byName[link.name] + if !ok || e.mode&os.ModeSymlink == 0 { + return fmt.Errorf("bundle is missing %s", link.name) + } + if e.link != link.target { + return fmt.Errorf("bundle link %s -> %s, want %s", link.name, e.link, link.target) + } + } + return nil +} + +func archive(entries []entry) ([]byte, error) { + var buf bytes.Buffer + zw, err := zstd.NewWriter(&buf, + zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(16)), + zstd.WithWindowSize(1<<25), + ) + if err != nil { + return nil, fmt.Errorf("zstd writer: %w", err) + } + tw := tar.NewWriter(zw) + modTime := time.Unix(0, 0) + for _, e := range entries { + hdr := &tar.Header{ + Name: e.name, + ModTime: modTime, + Mode: int64(e.mode.Perm()), + } + switch { + case e.mode&os.ModeSymlink != 0: + hdr.Typeflag = tar.TypeSymlink + hdr.Linkname = e.link + case e.mode.IsDir(): + hdr.Typeflag = tar.TypeDir + hdr.Mode = 0o755 + default: + hdr.Typeflag = tar.TypeReg + hdr.Size = e.size + if hdr.Mode&0o111 == 0 { + hdr.Mode = 0o755 + } + } + if err := tw.WriteHeader(hdr); err != nil { + return nil, fmt.Errorf("tar header %s: %w", e.name, err) + } + if hdr.Typeflag != tar.TypeReg { + continue + } + f, err := os.Open(e.path) + if err != nil { + return nil, fmt.Errorf("read %s: %w", e.name, err) + } + n, copyErr := io.Copy(tw, f) + closeErr := f.Close() + if copyErr != nil { + return nil, fmt.Errorf("tar write %s: %w", e.name, copyErr) + } + if closeErr != nil { + return nil, fmt.Errorf("close %s: %w", e.name, closeErr) + } + if n != e.size { + return nil, fmt.Errorf("wrote %d bytes to %s; expected %d", n, e.name, e.size) + } + } + if err := tw.Close(); err != nil { + return nil, fmt.Errorf("tar close: %w", err) + } + if err := zw.Close(); err != nil { + return nil, fmt.Errorf("zstd close: %w", err) + } + return buf.Bytes(), nil +} + +type linkSpec struct { + name string + target string +} + +var requiredFiles = []string{ + FatPath, + "bin/containerd-shim-runc-v2", + "bin/crun", + "bin/cni", + "bin/aux/xtables-nft-multi", + "bin/ip", + "bin/busybox", +} + +var requiredLinks = []linkSpec{ + {name: "bin/bridge", target: "cni"}, + {name: "bin/host-local", target: "cni"}, + {name: "bin/loopback", target: "cni"}, + {name: "bin/portmap", target: "cni"}, + {name: "bin/aux/iptables", target: "xtables-nft-multi"}, + {name: "bin/aux/iptables-save", target: "xtables-nft-multi"}, + {name: "bin/aux/iptables-restore", target: "xtables-nft-multi"}, + {name: "bin/aux/ip6tables", target: "xtables-nft-multi"}, + {name: "bin/aux/ip6tables-save", target: "xtables-nft-multi"}, + {name: "bin/aux/ip6tables-restore", target: "xtables-nft-multi"}, + {name: "bin/modprobe", target: "busybox"}, +} + +func allowedBinChild(name string) bool { + switch name { + case "edgelet-kube", "containerd-shim-runc-v2", "crun", "cni", + "bridge", "host-local", "loopback", "portmap", + "aux", "ip", "busybox", "modprobe": + return true + default: + return false + } +} + +func validBundlePath(name string) bool { + if name == "" || path.IsAbs(name) || strings.Contains(name, "\\") { + return false + } + for _, part := range strings.Split(name, "/") { + if part == "" || part == "." || part == ".." { + return false + } + } + return true +} + +func imageMember(name string) bool { + base := path.Base(name) + switch base { + case "oci-layout", "index.json", "manifest.json", "pause.tar", "pause.tar.gz": + return true + } + if strings.HasSuffix(base, ".tar") || strings.HasSuffix(base, ".tar.gz") || strings.HasSuffix(base, ".tar.zst") { + return true + } + if name == "images" || strings.HasPrefix(name, "images/") || strings.Contains(name, "/images/") { + return true + } + if name == "blobs" || strings.HasPrefix(name, "blobs/") || strings.Contains(name, "/blobs/") { + return true + } + return false +} + +func flannelMember(name string) bool { + for _, part := range strings.Split(name, "/") { + if part == "flannel" { + return true + } + } + return false +} + +func linkEscapes(name, target string) bool { + if target == "" || path.IsAbs(target) || strings.Contains(target, "\\") { + return true + } + cleaned := path.Clean(path.Join(path.Dir(name), target)) + return cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.HasPrefix(cleaned, "/") +} diff --git a/kube/internal/bundle/archive_test.go b/kube/internal/bundle/archive_test.go new file mode 100644 index 0000000..ba85a70 --- /dev/null +++ b/kube/internal/bundle/archive_test.go @@ -0,0 +1,275 @@ +package bundle + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "github.com/eclipse-iofog/edgelet/pkg/untar" +) + +func TestPackListsMembers(t *testing.T) { + packed := packStage(t, writeStage(t)) + got := listMembers(t, packed) + const want = `bin/ +bin/aux/ +bin/aux/ip6tables -> xtables-nft-multi +bin/aux/ip6tables-restore -> xtables-nft-multi +bin/aux/ip6tables-save -> xtables-nft-multi +bin/aux/iptables -> xtables-nft-multi +bin/aux/iptables-restore -> xtables-nft-multi +bin/aux/iptables-save -> xtables-nft-multi +bin/aux/xtables-nft-multi +bin/bridge -> cni +bin/busybox +bin/cni +bin/containerd-shim-runc-v2 +bin/crun +bin/edgelet-kube +bin/host-local -> cni +bin/ip +bin/loopback -> cni +bin/modprobe -> busybox +bin/portmap -> cni +` + if got != want { + t.Fatalf("bundle members:\n%s", got) + } + for _, line := range strings.Split(strings.TrimSuffix(got, "\n"), "\n") { + name := line + if i := strings.Index(name, " -> "); i >= 0 { + name = name[:i] + } + name = strings.TrimSuffix(name, "/") + if ociName(name) { + t.Fatalf("OCI image layer %s", line) + } + } + + dir := t.TempDir() + if err := untar.Untar(bytes.NewReader(packed), dir); err != nil { + t.Fatal(err) + } + assertLink(t, filepath.Join(dir, "bin", "aux", "iptables"), "xtables-nft-multi") + assertLink(t, filepath.Join(dir, "bin", "aux", "iptables-save"), "xtables-nft-multi") + assertLink(t, filepath.Join(dir, "bin", "aux", "iptables-restore"), "xtables-nft-multi") + assertLink(t, filepath.Join(dir, "bin", "modprobe"), "busybox") + for _, name := range []string{"bridge", "host-local", "loopback", "portmap"} { + assertLink(t, filepath.Join(dir, "bin", name), "cni") + } + body, err := os.ReadFile(filepath.Join(dir, "bin", "crun")) + if err != nil { + t.Fatal(err) + } + if string(body) != "crun\n" { + t.Fatalf("crun body %q", body) + } +} + +func TestPackKeepsSelectiveAux(t *testing.T) { + dir := writeStage(t) + extra := filepath.Join(dir, "bin", "aux", "iptables-apply") + if err := os.WriteFile(extra, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + got := listMembers(t, packStage(t, dir)) + if !strings.Contains(got, "bin/aux/iptables-apply\n") { + t.Fatalf("bundle members:\n%s", got) + } + if !strings.Contains(got, "bin/aux/iptables -> xtables-nft-multi\n") { + t.Fatalf("bundle members:\n%s", got) + } +} + +// func TestEmbeddedRuntimeHasNoImage(t *testing.T) { +// matches, err := filepath.Glob(filepath.Join("..", "..", "cmd", "edgelet-kube", "embed", "*.tar.zst")) +// if err != nil { +// t.Fatal(err) +// } +// if len(matches) != 1 { +// t.Fatalf("embed archives %v", matches) +// } +// if strings.Contains(filepath.Base(matches[0]), "airgap") { +// t.Fatalf("embed name %s", matches[0]) +// } +// body, err := os.ReadFile(matches[0]) +// if err != nil { +// t.Fatal(err) +// } +// members, err := Contents(body) +// if err != nil { +// t.Fatal(err) +// } +// if len(members) == 0 { +// t.Fatal("embed archive is empty") +// } +// for _, member := range members { +// if imageMember(member.Name) || strings.Contains(member.Name, "airgap") || strings.Contains(member.Name, "pause") { +// t.Fatalf("image in bundle: %s", member.Name) +// } +// } +// } + +func TestPackRejectsAirgapArchive(t *testing.T) { + dir := writeStage(t) + if err := os.WriteFile(filepath.Join(dir, "bin", airgap.AssetAMD64), []byte("images"), 0o644); err != nil { + t.Fatal(err) + } + _, err := Pack(dir) + if err == nil || !strings.Contains(err.Error(), "OCI image") { + t.Fatalf("got %v", err) + } +} + +func TestPackRejectsOCIImage(t *testing.T) { + dir := writeStage(t) + image := filepath.Join(dir, "images") + if err := os.MkdirAll(image, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(image, "pause.tar.gz"), []byte("not-an-image"), 0o644); err != nil { + t.Fatal(err) + } + _, err := Pack(dir) + if err == nil || !strings.Contains(err.Error(), "OCI image") { + t.Fatalf("got %v", err) + } +} + +func TestPackRejectsImageInsideAux(t *testing.T) { + dir := writeStage(t) + if err := os.WriteFile(filepath.Join(dir, "bin", "aux", "pause.tar"), []byte("layer"), 0o644); err != nil { + t.Fatal(err) + } + _, err := Pack(dir) + if err == nil || !strings.Contains(err.Error(), "OCI image") { + t.Fatalf("got %v", err) + } +} + +func TestPackRejectsFlannel(t *testing.T) { + dir := writeStage(t) + if err := os.Symlink("cni", filepath.Join(dir, "bin", "flannel")); err != nil { + t.Fatal(err) + } + _, err := Pack(dir) + if err == nil || !strings.Contains(err.Error(), "flannel") { + t.Fatalf("got %v", err) + } +} + +func TestPackRejectsExtraCNIPlugin(t *testing.T) { + dir := writeStage(t) + if err := os.Symlink("cni", filepath.Join(dir, "bin", "tuning")); err != nil { + t.Fatal(err) + } + _, err := Pack(dir) + if err == nil || !strings.Contains(err.Error(), "not a runtime binary") { + t.Fatalf("got %v", err) + } +} + +func packStage(t *testing.T, dir string) []byte { + t.Helper() + packed, err := Pack(dir) + if err != nil { + t.Fatal(err) + } + return packed +} + +func writeStage(t *testing.T) string { + t.Helper() + dir := t.TempDir() + bin := filepath.Join(dir, "bin") + if err := os.MkdirAll(filepath.Join(bin, "aux"), 0o755); err != nil { + t.Fatal(err) + } + files := []string{ + "edgelet-kube", + "containerd-shim-runc-v2", + "crun", + "cni", + "ip", + "busybox", + filepath.Join("aux", "xtables-nft-multi"), + } + for _, name := range files { + path := filepath.Join(bin, name) + if err := os.WriteFile(path, []byte(filepath.Base(name)+"\n"), 0o755); err != nil { + t.Fatal(err) + } + } + links := []struct{ name, target string }{ + {"bridge", "cni"}, + {"host-local", "cni"}, + {"loopback", "cni"}, + {"portmap", "cni"}, + {"modprobe", "busybox"}, + {filepath.Join("aux", "iptables"), "xtables-nft-multi"}, + {filepath.Join("aux", "iptables-save"), "xtables-nft-multi"}, + {filepath.Join("aux", "iptables-restore"), "xtables-nft-multi"}, + {filepath.Join("aux", "ip6tables"), "xtables-nft-multi"}, + {filepath.Join("aux", "ip6tables-save"), "xtables-nft-multi"}, + {filepath.Join("aux", "ip6tables-restore"), "xtables-nft-multi"}, + } + for _, link := range links { + if err := os.Symlink(link.target, filepath.Join(bin, link.name)); err != nil { + t.Fatal(err) + } + } + return dir +} + +func listMembers(t *testing.T, packed []byte) string { + t.Helper() + members, err := Contents(packed) + if err != nil { + t.Fatal(err) + } + var b strings.Builder + for _, m := range members { + switch { + case m.Dir: + fmt.Fprintf(&b, "%s/\n", m.Name) + case m.Link != "": + fmt.Fprintf(&b, "%s -> %s\n", m.Name, m.Link) + default: + fmt.Fprintf(&b, "%s\n", m.Name) + } + } + return b.String() +} + +func assertLink(t *testing.T, path, want string) { + t.Helper() + got, err := os.Readlink(path) + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("%s -> %s, want %s", path, got, want) + } +} + +func ociName(name string) bool { + base := filepath.Base(name) + switch base { + case "oci-layout", "index.json", "manifest.json", "pause.tar", "pause.tar.gz": + return true + } + if strings.HasSuffix(base, ".tar") || strings.HasSuffix(base, ".tar.gz") || strings.HasSuffix(base, ".tar.zst") { + return true + } + if strings.HasPrefix(name, "images/") || strings.Contains(name, "/images/") { + return true + } + if strings.HasPrefix(name, "blobs/") || strings.Contains(name, "/blobs/") { + return true + } + return false +} diff --git a/kube/internal/bundle/bundle.go b/kube/internal/bundle/bundle.go new file mode 100644 index 0000000..0fa0166 --- /dev/null +++ b/kube/internal/bundle/bundle.go @@ -0,0 +1,29 @@ +// Package bundle names the runtime file stored in the thin binary's zstd bundle. +package bundle + +const ( + // FatName is the fat runtime file name. + FatName = "edgelet-kube" + // FatPath is the fat runtime path inside the bundle. + FatPath = "bin/" + FatName + + // DefaultDataDir is the data directory when no flag or environment variable is set. + DefaultDataDir = "/var/lib/edgelet-kube" + // DataDirEnv is the environment variable for the data directory. + DataDirEnv = "EDGELET_KUBE_DATA_DIR" + // DataDirFlag is the command-line flag for the data directory. + DataDirFlag = "data-dir" + + // ServerCommand extracts the bundle and runs the fat runtime. + ServerCommand = "server" +) + +// Client reports whether name is a multicall tool dispatched to the fat runtime. +func Client(name string) bool { + switch name { + case "kubectl", "ctr", "crictl": + return true + default: + return false + } +} diff --git a/kube/internal/charts/cert-manager-v1.21.3.tgz b/kube/internal/charts/cert-manager-v1.21.3.tgz new file mode 100644 index 0000000..8d3ce55 Binary files /dev/null and b/kube/internal/charts/cert-manager-v1.21.3.tgz differ diff --git a/kube/internal/charts/charts.go b/kube/internal/charts/charts.go new file mode 100644 index 0000000..450a1a4 --- /dev/null +++ b/kube/internal/charts/charts.go @@ -0,0 +1,86 @@ +package charts + +import ( + "embed" + "fmt" + "io/fs" + "net/http" + "strconv" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +//go:embed *.tgz +var files embed.FS + +// Prefix is the API server path the chart tarballs are served on. +const Prefix = "/static/charts/" + +// Names returns the embedded chart file names. The versions come from the pin file. +func Names() ([]string, error) { + var names []string + for _, chart := range []string{"traefik", "traefik-crd", "gateway-api-crd", "cert-manager"} { + version := airgap.ChartVersion(chart) + if version == "" { + return nil, fmt.Errorf("chart %s has no pinned version", chart) + } + names = append(names, chart+"-"+version+".tgz") + } + return names, nil +} + +// Read returns one embedded chart tarball. +func Read(name string) ([]byte, error) { + names, err := Names() + if err != nil { + return nil, err + } + if !listed(names, name) { + return nil, fs.ErrNotExist + } + body, err := files.ReadFile(name) + if err != nil { + return nil, err + } + return body, nil +} + +// Handler serves Prefix and delegates every other request to next. +func Handler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + name, ok := strings.CutPrefix(r.URL.Path, Prefix) + if !ok { + next.ServeHTTP(w, r) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodHead { + w.Header().Set("Allow", http.MethodGet+", "+http.MethodHead) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + body, err := Read(name) + if err != nil { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/gzip") + w.Header().Set("Content-Length", strconv.Itoa(len(body))) + if r.Method == http.MethodHead { + return + } + _, _ = w.Write(body) // #nosec G705 -- response is an embedded chart archive, not HTML + }) +} + +func listed(names []string, name string) bool { + if name == "" || strings.Contains(name, "/") { + return false + } + for _, item := range names { + if item == name { + return true + } + } + return false +} diff --git a/kube/internal/charts/charts_test.go b/kube/internal/charts/charts_test.go new file mode 100644 index 0000000..9f7177b --- /dev/null +++ b/kube/internal/charts/charts_test.go @@ -0,0 +1,146 @@ +package charts + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "go.yaml.in/yaml/v3" +) + +func TestChartsMatchPins(t *testing.T) { + names, err := Names() + if err != nil { + t.Fatal(err) + } + if len(names) != 4 { + t.Fatalf("charts %v", names) + } + entries, err := files.ReadDir(".") + if err != nil { + t.Fatal(err) + } + if len(entries) != len(names) { + t.Fatalf("embedded files %d", len(entries)) + } + seen := map[string]bool{} + for _, name := range names { + for _, bad := range []string{"datasance", "iofog", "potctl"} { + if strings.Contains(strings.ToLower(name), bad) { + t.Fatalf("chart %s", name) + } + } + body, err := Read(name) + if err != nil { + t.Fatal(err) + } + if len(body) < 2 || body[0] != 0x1f || body[1] != 0x8b { + t.Fatalf("%s is not a gzip tarball", name) + } + version := chartVersion(t, body) + chart := strings.TrimSuffix(name, ".tgz") + pinName := chart + for _, candidate := range []string{"traefik-crd", "traefik", "gateway-api-crd", "cert-manager"} { + if strings.HasPrefix(chart, candidate+"-") { + pinName = candidate + break + } + } + if version != airgap.ChartVersion(pinName) { + t.Fatalf("%s version %s", name, version) + } + seen[name] = true + } + for _, entry := range entries { + if !seen[entry.Name()] { + t.Fatalf("unexpected chart %s", entry.Name()) + } + } + for _, image := range airgap.Images() { + if strings.Contains(image, ".tgz") { + t.Fatalf("chart tarball is on the image list: %s", image) + } + } +} + +func TestHandlerServesChartsAndDelegates(t *testing.T) { + names, err := Names() + if err != nil { + t.Fatal(err) + } + var delegated []string + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + delegated = append(delegated, r.URL.Path) + w.WriteHeader(http.StatusNoContent) + }) + handler := Handler(next) + for _, name := range names { + body, err := Read(name) + if err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, Prefix+name, nil)) + if rec.Code != http.StatusOK { + t.Fatalf("%s status %d", name, rec.Code) + } + if rec.Header().Get("Content-Type") != "application/gzip" { + t.Fatalf("%s type %s", name, rec.Header().Get("Content-Type")) + } + if !bytes.Equal(rec.Body.Bytes(), body) { + t.Fatalf("%s body mismatch", name) + } + } + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil)) + if rec.Code != http.StatusNoContent || len(delegated) != 1 || delegated[0] != "/readyz" { + t.Fatalf("delegate status %d paths %v", rec.Code, delegated) + } + rec = httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, Prefix+"other.tgz", nil)) + if rec.Code != http.StatusNotFound { + t.Fatalf("unknown chart status %d", rec.Code) + } +} + +func chartVersion(t *testing.T, body []byte) string { + t.Helper() + gz, err := gzip.NewReader(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + defer gz.Close() + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(hdr.Name, "/Chart.yaml") && hdr.Name != "Chart.yaml" { + continue + } + raw, err := io.ReadAll(tr) + if err != nil { + t.Fatal(err) + } + var doc struct { + Version string `yaml:"version"` + } + if err := yaml.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + return doc.Version + } + t.Fatal("Chart.yaml was not in the tarball") + return "" +} diff --git a/kube/internal/charts/doc.go b/kube/internal/charts/doc.go new file mode 100644 index 0000000..1c62146 --- /dev/null +++ b/kube/internal/charts/doc.go @@ -0,0 +1,2 @@ +// Package charts serves the embedded Helm chart tarballs from the API server. +package charts diff --git a/kube/internal/charts/gateway-api-crd-1.6.301.tgz b/kube/internal/charts/gateway-api-crd-1.6.301.tgz new file mode 100644 index 0000000..01327fb Binary files /dev/null and b/kube/internal/charts/gateway-api-crd-1.6.301.tgz differ diff --git a/kube/internal/charts/traefik-41.6.101+up41.6.1.tgz b/kube/internal/charts/traefik-41.6.101+up41.6.1.tgz new file mode 100644 index 0000000..32f23ce Binary files /dev/null and b/kube/internal/charts/traefik-41.6.101+up41.6.1.tgz differ diff --git a/kube/internal/charts/traefik-crd-41.6.101+up41.6.1.tgz b/kube/internal/charts/traefik-crd-41.6.101+up41.6.1.tgz new file mode 100644 index 0000000..af2b776 Binary files /dev/null and b/kube/internal/charts/traefik-crd-41.6.101+up41.6.1.tgz differ diff --git a/kube/internal/config/config.go b/kube/internal/config/config.go new file mode 100644 index 0000000..ec61829 --- /dev/null +++ b/kube/internal/config/config.go @@ -0,0 +1,298 @@ +// Package config loads server options from the config file and its drop-ins. +package config + +import ( + "errors" + "os" + "path/filepath" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +const ( + // DefaultConfigFile is the config file when --config and EDGELET_KUBE_CONFIG_FILE are unset. + DefaultConfigFile = "/etc/edgelet-kube/config.yaml" + // EnvConfigFile is the environment variable that moves the config file. + EnvConfigFile = "EDGELET_KUBE_CONFIG_FILE" + + // DefaultKubeconfig is the admin kubeconfig path. + DefaultKubeconfig = "/etc/edgelet-kube/edgelet-kube.yaml" + // DefaultKubeconfigMode is the admin kubeconfig file mode. + DefaultKubeconfigMode = "0600" + // DefaultBindAddress is the API bind address. + DefaultBindAddress = "0.0.0.0" + // DefaultHTTPSListenPort is the API listen port. + DefaultHTTPSListenPort = 6443 + + // DefaultClusterCIDR is the pod network when cluster-cidr is unset. + DefaultClusterCIDR = "10.42.0.0/16" + // DefaultServiceCIDR is the service network when service-cidr is unset. + DefaultServiceCIDR = "10.43.0.0/16" + // DefaultClusterDNS is the cluster DNS address of the default service network. + DefaultClusterDNS = "10.43.0.10" + // DefaultNodePodCIDR is this node's pod range when cluster-cidr is unset. + DefaultNodePodCIDR = "10.42.0.0/24" + // DefaultClusterDomain is the cluster domain when cluster-domain is unset. + DefaultClusterDomain = "cluster.local" + // DefaultServiceNodePortRange is the NodePort range. + DefaultServiceNodePortRange = "30000-32767" + // DefaultPauseImage is the pause image on the airgap list, without the digest. + // It is the portainer/pause image the Edgelet agent imports. + DefaultPauseImage = "docker.io/portainer/pause:latest" + + // DefaultSnapshotter is the container snapshot driver. + DefaultSnapshotter = "overlayfs" + // DefaultPrivateRegistry is the registries file. + DefaultPrivateRegistry = "/etc/edgelet-kube/registries.yaml" + // DefaultLocalStoragePath is the local-path volume directory. + DefaultLocalStoragePath = bundle.DefaultDataDir + "/storage" +) + +// Server is the server configuration loaded from the config file and its drop-ins. +type Server struct { + // Config is the config file path. + Config string + // DataDir is the data directory. + DataDir string + // WriteKubeconfig is the admin kubeconfig path. + WriteKubeconfig string + // WriteKubeconfigMode is the admin kubeconfig file mode. + WriteKubeconfigMode string + // WriteKubeconfigGroup is the admin kubeconfig group. + WriteKubeconfigGroup string + + // BindAddress is the API bind address. + BindAddress string + // HTTPSListenPort is the API listen port. + HTTPSListenPort int + // AdvertiseAddress is the address advertised to the cluster. + AdvertiseAddress string + // AdvertisePort is the port advertised to the cluster. + AdvertisePort int + // TLSSan is the extra names on the serving certificate. + TLSSan []string + // TLSSanSecurity keeps extra serving names to the node and the SAN list. + TLSSanSecurity bool + + // NodeName is the node name. + NodeName string + // NodeIP is the node IP. + NodeIP string + // NodeExternalIP is the external node IP. + NodeExternalIP string + // NodeLabel is the node labels. + NodeLabel []string + // NodeTaint is the node taints. + NodeTaint []string + // ResolvConf is the resolver file passed to kubelet. + ResolvConf string + + // ClusterCIDR is the pod network. + ClusterCIDR string + // NodePodCIDR is this node's pod range, the first /24 of ClusterCIDR. + NodePodCIDR string + // ServiceCIDR is the service network. + ServiceCIDR string + // ClusterDNS is the cluster DNS address. + ClusterDNS string + // ClusterDomain is the cluster DNS domain. + ClusterDomain string + // ServiceNodePortRange is the NodePort range. + ServiceNodePortRange string + // PauseImage is the pause image kubelet uses. When system-default-registry + // is set and this name is on the pin list, the registry is prefixed. + PauseImage string + + // DatastoreEndpoint is the database endpoint. Empty selects SQLite. + DatastoreEndpoint string + // DatastoreCAFile is the database CA file. + DatastoreCAFile string + // DatastoreCertFile is the database client certificate. + DatastoreCertFile string + // DatastoreKeyFile is the database client key. + DatastoreKeyFile string + // DatastoreNATSCreds is the NATS credentials file. + DatastoreNATSCreds string + + // Disable is the addon names to leave off. + Disable []string + // DisableHelmController leaves the Helm controller off. + DisableHelmController bool + // DefaultLocalStoragePath is the local-path volume directory. + DefaultLocalStoragePath string + // ClusterIssuerEmail is the Let's Encrypt account email. + ClusterIssuerEmail string + + // Debug turns on debug logging. + Debug bool + // V is the log verbosity. + V int + // VModule is the file-filtered log verbosity. + VModule string + // Log is the log file path. + Log string + // AlsoLogToStderr logs to stderr as well as the log file. + AlsoLogToStderr bool + + // KubeAPIServerArg is the extra kube-apiserver arguments. + KubeAPIServerArg []string + // KubeControllerManagerArg is the extra kube-controller-manager arguments. + KubeControllerManagerArg []string + // KubeSchedulerArg is the extra kube-scheduler arguments. + KubeSchedulerArg []string + // KubeletArg is the extra kubelet arguments. + KubeletArg []string + // KubeProxyArg is the extra kube-proxy arguments. + KubeProxyArg []string + // HelmControllerArg is the extra Helm controller arguments. + HelmControllerArg []string + + // Snapshotter is the container snapshot driver. + Snapshotter string + // PreferBundledBin prefers the bundled host binaries. + PreferBundledBin bool + // SELinux enables SELinux. + SELinux bool + // ProtectKernelDefaults leaves kernel sysctls unchanged. + ProtectKernelDefaults bool + // SecretsEncryption encrypts secrets at rest. + SecretsEncryption bool + + // PrivateRegistry is the registries file path. + PrivateRegistry string + // SystemDefaultRegistry is the registry prefix for pinned images. + SystemDefaultRegistry string + // DisableDefaultRegistryEndpoint skips the upstream registry fallback. + DisableDefaultRegistryEndpoint bool + + // present records keys the files set, so a later default does not + // replace an explicit false or empty value. + present map[string]bool +} + +// Defaults returns the built-in server options. +func Defaults() Server { + var srv Server + if err := srv.applyDefaults(DefaultConfigFile); err != nil { + panic(err) + } + return srv +} + +// Load reads the config file selected by args and lookupEnv, then the drop-ins +// beside that file, then EDGELET_KUBE_* variables, then flags. A flag replaces +// the same key from the environment. lookupEnv may be nil. A missing file and +// an empty file use Defaults. Load does not create a config file. +func Load(args []string, lookupEnv func(string) (string, bool)) (Server, error) { + path, err := configPath(args, lookupEnv) + if err != nil { + return Server{}, err + } + srv := Server{present: map[string]bool{}} + if err := mergeFile(&srv, path); err != nil && !errors.Is(err, os.ErrNotExist) { + return Server{}, err + } + drops, err := dropIns(path) + if err != nil { + return Server{}, err + } + for _, drop := range drops { + if err := mergeFile(&srv, drop); err != nil { + return Server{}, err + } + } + if err := applyEnv(&srv, lookupEnv); err != nil { + return Server{}, err + } + if err := applyFlags(&srv, args); err != nil { + return Server{}, err + } + if err := srv.applyDefaults(path); err != nil { + return Server{}, err + } + return srv, nil +} + +func configPath(args []string, lookupEnv func(string) (string, bool)) (string, error) { + path := DefaultConfigFile + if lookupEnv != nil { + if value, ok := lookupEnv(EnvConfigFile); ok && value != "" { + path = value + } + } + for i := 0; i < len(args); i++ { + arg := args[i] + switch { + case arg == "--": + return filepath.Clean(path), nil + case arg == "--config": + if i+1 >= len(args) || args[i+1] == "" || strings.HasPrefix(args[i+1], "-") { + return "", errors.New("config requires a path") + } + i++ + path = args[i] + case strings.HasPrefix(arg, "--config="): + value := strings.TrimPrefix(arg, "--config=") + if value == "" { + return "", errors.New("config requires a path") + } + path = value + } + } + return filepath.Clean(path), nil +} + +func (s *Server) applyDefaults(loadedFrom string) error { + if !s.present["config"] { + s.Config = loadedFrom + } + if !s.present["data-dir"] { + s.DataDir = bundle.DefaultDataDir + } + if !s.present["write-kubeconfig"] { + s.WriteKubeconfig = DefaultKubeconfig + } + if !s.present["write-kubeconfig-mode"] { + s.WriteKubeconfigMode = DefaultKubeconfigMode + } + if !s.present["bind-address"] { + s.BindAddress = DefaultBindAddress + } + if !s.present["https-listen-port"] { + s.HTTPSListenPort = DefaultHTTPSListenPort + } + if !s.present["advertise-port"] { + s.AdvertisePort = s.HTTPSListenPort + } + if !s.present["tls-san-security"] { + s.TLSSanSecurity = true + } + if err := s.applyNetwork(); err != nil { + return err + } + if !s.present["pause-image"] { + s.PauseImage = DefaultPauseImage + } + s.PauseImage = airgap.Resolve(s.SystemDefaultRegistry, s.PauseImage) + if !s.present["default-local-storage-path"] { + s.DefaultLocalStoragePath = DefaultLocalStoragePath + } + if !s.present["snapshotter"] { + s.Snapshotter = DefaultSnapshotter + } + if !s.present["prefer-bundled-bin"] { + s.PreferBundledBin = true + } + if !s.present["private-registry"] { + s.PrivateRegistry = DefaultPrivateRegistry + } + return nil +} + +// KubeletPauseArg is the kubelet flag for the sandbox image. +// The value is PauseImage. A set system-default-registry is already in that name. +func (s Server) KubeletPauseArg() string { + return "--pod-infra-container-image=" + s.PauseImage +} diff --git a/kube/internal/config/config_test.go b/kube/internal/config/config_test.go new file mode 100644 index 0000000..ee62b68 --- /dev/null +++ b/kube/internal/config/config_test.go @@ -0,0 +1,931 @@ +package config + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" +) + +func TestMissingFileUsesDefaults(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + want := Defaults() + want.Config = path + assertServer(t, got, want) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("config file created: %v", err) + } +} + +func TestEmptyFileUsesDefaults(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, nil, 0o644); err != nil { + t.Fatal(err) + } + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + want := Defaults() + want.Config = path + assertServer(t, got, want) + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if len(body) != 0 { + t.Fatalf("empty file was rewritten: %q", body) + } +} + +func TestCommentOnlyFileUsesDefaults(t *testing.T) { + got := loadPath(t, filepath.Join(t.TempDir(), "config.yaml"), "# no keys\n") + want := Defaults() + want.Config = got.Config + assertServer(t, got, want) +} + +func TestDropInLastValueWins(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path, "data-dir: /from-main\ndebug: true\nnode-name: main\n") + drop := path + ".d" + writeFile(t, filepath.Join(drop, "10-a.yaml"), "data-dir: /from-a\nnode-label:\n - a=1\n") + writeFile(t, filepath.Join(drop, "20-b.yaml"), "data-dir: /from-b\ndebug: false\n") + writeFile(t, filepath.Join(drop, "notes.txt"), "not-a-real-key: true\n") + writeFile(t, filepath.Join(drop, "skip.yml"), "not-a-real-key: true\n") + + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.DataDir != "/from-b" { + t.Fatalf("data dir %q", got.DataDir) + } + if got.Debug { + t.Fatal("debug stayed true") + } + if got.NodeName != "main" { + t.Fatalf("node name %q", got.NodeName) + } + if !reflect.DeepEqual(got.NodeLabel, []string{"a=1"}) { + t.Fatalf("labels %#v", got.NodeLabel) + } +} + +func TestDropInWithoutMainFile(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path+".d/10.yaml", "debug: true\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if !got.Debug { + t.Fatal("drop-in was ignored") + } + if got.DataDir != bundle.DefaultDataDir { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestUnknownKeyNamesItself(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "not-a-real-key: true\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "not-a-real-key") || !strings.Contains(err.Error(), "unknown") { + t.Fatalf("error %v", err) + } +} + +func TestRejectedKeysNameThemselves(t *testing.T) { + keys := []string{ + "token", + "token-file", + "agent-token", + "agent-token-file", + "server", + "cluster-init", + "cluster-reset", + "cluster-reset-restore-path", + "lb-server-port", + "etcd-arg", + "etcd-expose-metrics", + "egress-selector-mode", + "vpn-auth", + "vpn-auth-file", + "embedded-registry", + "disable-scheduler", + "disable-kube-proxy", + "disable-cloud-controller", + "disable-network-policy", + "disable-agent", + "docker", + "rootless", + "flannel-backend", + "flannel-iface", + "etcd-snapshot-dir", + "etcd-s3-bucket", + } + for _, key := range keys { + t.Run(key, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, key+": true\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), key) || !strings.Contains(err.Error(), "not accepted") { + t.Fatalf("error %v", err) + } + }) + } +} + +func TestBareFlannelIsUnknown(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "flannel: true\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "unknown") || !strings.Contains(err.Error(), "flannel") { + t.Fatalf("error %v", err) + } +} + +func TestConfigFlagMovesDropInDirectory(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "custom.yaml") + writeFile(t, path, "node-name: file\n") + writeFile(t, path+".d/10.yaml", "node-name: dropin\n") + writeFile(t, filepath.Join(dir, "config.yaml.d", "10.yaml"), "not-a-real-key: true\n") + + envPath := filepath.Join(t.TempDir(), "from-env.yaml") + writeFile(t, envPath, "node-name: env\n") + + got, err := Load([]string{"--config", path}, func(key string) (string, bool) { + if key == EnvConfigFile { + return envPath, true + } + return "", false + }) + if err != nil { + t.Fatal(err) + } + if got.NodeName != "dropin" { + t.Fatalf("node name %q", got.NodeName) + } +} + +func TestEnvSelectsConfigFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "from-env.yaml") + writeFile(t, path, "data-dir: /from-env\n") + got, err := Load(nil, func(key string) (string, bool) { + if key == EnvConfigFile { + return path, true + } + return "", false + }) + if err != nil { + t.Fatal(err) + } + if got.DataDir != "/from-env" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestConfigFlagRequiresPath(t *testing.T) { + _, err := Load([]string{"--config"}, nil) + if err == nil || !strings.Contains(err.Error(), "config") { + t.Fatalf("error %v", err) + } + _, err = Load([]string{"--config="}, nil) + if err == nil { + t.Fatal("expected an error") + } +} + +func TestConfigPathFlagOverridesEnv(t *testing.T) { + path, err := configPath([]string{"--config", "/from-flag", "--config=/from-equals"}, func(string) (string, bool) { + return "/from-env", true + }) + if err != nil { + t.Fatal(err) + } + if path != "/from-equals" { + t.Fatalf("path %q", path) + } +} + +func TestAdvertisePortFollowsListenPort(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "https-listen-port: 7443\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.HTTPSListenPort != 7443 || got.AdvertisePort != 7443 { + t.Fatalf("listen %d advertise %d", got.HTTPSListenPort, got.AdvertisePort) + } +} + +func TestExplicitFalseAndEmpty(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "prefer-bundled-bin: false\ntls-san-security: false\ndata-dir: \"\"\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.PreferBundledBin || got.TLSSanSecurity { + t.Fatalf("prefer %v san %v", got.PreferBundledBin, got.TLSSanSecurity) + } + if got.DataDir != "" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestStringListValue(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "tls-san: site.example.com\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got.TLSSan, []string{"site.example.com"}) { + t.Fatalf("san %#v", got.TLSSan) + } +} + +func TestWrongTypesNameTheKey(t *testing.T) { + cases := map[string]string{ + "debug": "debug: \"true\"\n", + "https-listen-port": "https-listen-port: \"6443\"\n", + "tls-san": "tls-san:\n - 1\n", + } + for key, body := range cases { + t.Run(key, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, body) + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), key) { + t.Fatalf("error %v", err) + } + }) + } +} + +func TestRoundTrip(t *testing.T) { + const body = ` +config: /cfg +data-dir: /data +write-kubeconfig: /kubeconfig +write-kubeconfig-mode: "0644" +write-kubeconfig-group: kube +bind-address: 127.0.0.1 +https-listen-port: 7443 +advertise-address: 10.1.0.8 +advertise-port: 7444 +tls-san: + - a.example + - b.example +tls-san-security: false +node-name: node-a +node-ip: 10.1.0.9 +node-external-ip: 203.0.113.5 +node-label: + - disk=ssd +node-taint: + - "dedicated=lab:NoSchedule" +resolv-conf: /etc/resolv.conf +cluster-cidr: 10.20.0.0/16 +service-cidr: 10.21.0.0/16 +cluster-dns: 10.21.0.10 +cluster-domain: example.local +service-node-port-range: 30000-30010 +pause-image: "pause:test" +datastore-endpoint: "nats://nats.example:4222" +datastore-cafile: /ca.pem +datastore-certfile: /cert.pem +datastore-keyfile: /key.pem +datastore-nats-creds: /nats.creds +disable: + - traefik +disable-helm-controller: true +default-local-storage-path: /storage +cluster-issuer-email: "ops@example.com" +debug: true +v: 4 +vmodule: apiserver=3 +log: /var/log/edgelet-kube.log +alsologtostderr: true +kube-apiserver-arg: + - audit-log-path=/tmp/audit.log +kube-controller-manager-arg: + - node-cidr-mask-size=24 +kube-scheduler-arg: + - v=2 +kubelet-arg: + - config=/etc/kubelet.yaml +kube-proxy-arg: + - proxy-mode=iptables +helm-controller-arg: + - debug=true +snapshotter: native +prefer-bundled-bin: false +selinux: true +protect-kernel-defaults: true +secrets-encryption: true +private-registry: /etc/registries.yaml +system-default-registry: registry.example +disable-default-registry-endpoint: true +` + for key := range setters { + if !yamlHasKey(body, key) { + t.Errorf("sample missing %s", key) + } + } + for key := range rejectedKeys { + if _, ok := setters[key]; ok { + t.Errorf("both accepted and rejected: %s", key) + } + } + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, body) + // The file selector is not the config key, so the file can still set that key. + got, err := Load(nil, func(key string) (string, bool) { + if key == EnvConfigFile { + return path, true + } + return "", false + }) + if err != nil { + t.Fatal(err) + } + want := Server{ + Config: "/cfg", + DataDir: "/data", + WriteKubeconfig: "/kubeconfig", + WriteKubeconfigMode: "0644", + WriteKubeconfigGroup: "kube", + BindAddress: "127.0.0.1", + HTTPSListenPort: 7443, + AdvertiseAddress: "10.1.0.8", + AdvertisePort: 7444, + TLSSan: []string{"a.example", "b.example"}, + TLSSanSecurity: false, + NodeName: "node-a", + NodeIP: "10.1.0.9", + NodeExternalIP: "203.0.113.5", + NodeLabel: []string{"disk=ssd"}, + NodeTaint: []string{"dedicated=lab:NoSchedule"}, + ResolvConf: "/etc/resolv.conf", + ClusterCIDR: "10.20.0.0/16", + NodePodCIDR: "10.20.0.0/24", + ServiceCIDR: "10.21.0.0/16", + ClusterDNS: "10.21.0.10", + ClusterDomain: "example.local", + ServiceNodePortRange: "30000-30010", + PauseImage: "pause:test", + DatastoreEndpoint: "nats://nats.example:4222", + DatastoreCAFile: "/ca.pem", + DatastoreCertFile: "/cert.pem", + DatastoreKeyFile: "/key.pem", + DatastoreNATSCreds: "/nats.creds", + Disable: []string{"traefik"}, + DisableHelmController: true, + DefaultLocalStoragePath: "/storage", + ClusterIssuerEmail: "ops@example.com", + Debug: true, + V: 4, + VModule: "apiserver=3", + Log: "/var/log/edgelet-kube.log", + AlsoLogToStderr: true, + KubeAPIServerArg: []string{"audit-log-path=/tmp/audit.log"}, + KubeControllerManagerArg: []string{"node-cidr-mask-size=24"}, + KubeSchedulerArg: []string{"v=2"}, + KubeletArg: []string{"config=/etc/kubelet.yaml"}, + KubeProxyArg: []string{"proxy-mode=iptables"}, + HelmControllerArg: []string{"debug=true"}, + Snapshotter: "native", + PreferBundledBin: false, + SELinux: true, + ProtectKernelDefaults: true, + SecretsEncryption: true, + PrivateRegistry: "/etc/registries.yaml", + SystemDefaultRegistry: "registry.example", + DisableDefaultRegistryEndpoint: true, + } + assertServer(t, got, want) +} + +func TestDefaultPauseImageMatchesAirgapList(t *testing.T) { + body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "airgap", "image-list.txt")) + if err != nil { + t.Fatal(err) + } + var pause string + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if strings.Contains(line, "/pause:") { + pause = line + break + } + } + name, _, _ := strings.Cut(pause, "@") + if name != DefaultPauseImage { + t.Fatalf("pause image %q, list %q", DefaultPauseImage, name) + } +} + +func TestSystemDefaultRegistryPrefixesPause(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "system-default-registry: registry.example\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.PauseImage != "registry.example/"+DefaultPauseImage { + t.Fatalf("pause %s", got.PauseImage) + } + writeFile(t, path, "system-default-registry: \"\"\npause-image: docker.io/portainer/pause:latest\n") + got, err = Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.PauseImage != DefaultPauseImage { + t.Fatalf("empty registry pause %s", got.PauseImage) + } + writeFile(t, path, "system-default-registry: registry.example\npause-image: docker.io/portainer/pause:latest\n") + got, err = Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.PauseImage != "registry.example/"+DefaultPauseImage { + t.Fatalf("listed pause %s", got.PauseImage) + } +} + +func TestKubeletPauseArg(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + got := loadPath(t, path, "# defaults\n") + pause := DefaultPauseImage + if got.KubeletPauseArg() != "--pod-infra-container-image="+pause { + t.Fatalf("pause flag %s", got.KubeletPauseArg()) + } + if !strings.HasPrefix(airgapPause(t), pause+"@sha256:") { + t.Fatalf("pause %s is not the pin-list name", pause) + } + + got = loadPath(t, path, "system-default-registry: registry.example\n") + flag := got.KubeletPauseArg() + if flag != "--pod-infra-container-image=registry.example/"+pause { + t.Fatalf("prefixed pause flag %s", flag) + } + if !strings.Contains(flag, "registry.example/") { + t.Fatalf("prefix missing from %s", flag) + } + + got = loadPath(t, path, "system-default-registry: \"\"\n") + if got.KubeletPauseArg() != "--pod-infra-container-image="+pause { + t.Fatalf("empty registry flag %s", got.KubeletPauseArg()) + } +} + +func airgapPause(t *testing.T) string { + t.Helper() + body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "airgap", "image-list.txt")) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if strings.Contains(line, "/pause:") { + return line + } + } + t.Fatal("pin list has no pause image") + return "" +} + +func TestDefaults(t *testing.T) { + got := Defaults() + if got.DataDir != bundle.DefaultDataDir { + t.Fatalf("data dir %q", got.DataDir) + } + if got.WriteKubeconfig != DefaultKubeconfig || got.WriteKubeconfigMode != DefaultKubeconfigMode { + t.Fatalf("kubeconfig %q mode %q", got.WriteKubeconfig, got.WriteKubeconfigMode) + } + if got.BindAddress != DefaultBindAddress || got.HTTPSListenPort != DefaultHTTPSListenPort || got.AdvertisePort != DefaultHTTPSListenPort { + t.Fatalf("bind %q port %d advertise %d", got.BindAddress, got.HTTPSListenPort, got.AdvertisePort) + } + if !got.TLSSanSecurity || !got.PreferBundledBin { + t.Fatal("expected security and bundled binaries on") + } + if got.ClusterCIDR != DefaultClusterCIDR || got.NodePodCIDR != DefaultNodePodCIDR { + t.Fatalf("pod %s node %s", got.ClusterCIDR, got.NodePodCIDR) + } + if got.ServiceCIDR != DefaultServiceCIDR || got.ClusterDNS != DefaultClusterDNS { + t.Fatalf("service %s dns %s", got.ServiceCIDR, got.ClusterDNS) + } + if got.ClusterDomain != DefaultClusterDomain || got.ServiceNodePortRange != DefaultServiceNodePortRange { + t.Fatalf("domain %s ports %s", got.ClusterDomain, got.ServiceNodePortRange) + } + if got.PauseImage != DefaultPauseImage || got.Snapshotter != DefaultSnapshotter { + t.Fatalf("pause %s snapshotter %s", got.PauseImage, got.Snapshotter) + } + if got.PrivateRegistry != DefaultPrivateRegistry || got.DefaultLocalStoragePath != DefaultLocalStoragePath { + t.Fatalf("registry %s storage %s", got.PrivateRegistry, got.DefaultLocalStoragePath) + } + if got.Config != DefaultConfigFile { + t.Fatalf("config %q", got.Config) + } +} + +func TestDefaultNetwork(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if got.ClusterCIDR != "10.42.0.0/16" || got.NodePodCIDR != "10.42.0.0/24" { + t.Fatalf("pod %s node %s", got.ClusterCIDR, got.NodePodCIDR) + } + if got.ServiceCIDR != "10.43.0.0/16" || got.ClusterDNS != "10.43.0.10" { + t.Fatalf("service %s dns %s", got.ServiceCIDR, got.ClusterDNS) + } + if got.ClusterDomain != "cluster.local" || got.ServiceNodePortRange != "30000-32767" { + t.Fatalf("domain %s ports %s", got.ClusterDomain, got.ServiceNodePortRange) + } + dns, err := tenthAddress(got.ServiceCIDR) + if err != nil { + t.Fatal(err) + } + if dns != got.ClusterDNS { + t.Fatalf("derived dns %s stored %s", dns, got.ClusterDNS) + } + api, err := FirstServiceAddress(got.ServiceCIDR) + if err != nil { + t.Fatal(err) + } + if api != "10.43.0.1" { + t.Fatalf("service address %s", api) + } + pod, err := nodePodCIDR(got.ClusterCIDR) + if err != nil { + t.Fatal(err) + } + if pod != got.NodePodCIDR { + t.Fatalf("derived pod %s stored %s", pod, got.NodePodCIDR) + } +} + +func TestServiceCIDRDerivesClusterDNS(t *testing.T) { + cases := map[string]string{ + "service-cidr: 192.168.50.0/24\n": "192.168.50.10", + "service-cidr: 10.1.2.128/25\n": "10.1.2.138", + } + for body, want := range cases { + t.Run(want, func(t *testing.T) { + got := loadPath(t, filepath.Join(t.TempDir(), "config.yaml"), body) + if got.ClusterDNS != want { + t.Fatalf("dns %s", got.ClusterDNS) + } + }) + } +} + +func TestClusterDNSOutsideServiceCIDR(t *testing.T) { + cases := map[string][2]string{ + "service-cidr: 10.50.0.0/16\ncluster-dns: 10.60.0.10\n": {"10.60.0.10", "10.50.0.0/16"}, + "cluster-dns: 10.42.0.10\n": {"10.42.0.10", "10.43.0.0/16"}, + } + for body, names := range cases { + t.Run(names[0], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, body) + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), names[0]) || !strings.Contains(err.Error(), names[1]) { + t.Fatalf("error %v", err) + } + }) + } +} + +func TestNodePodCIDR(t *testing.T) { + got := loadPath(t, filepath.Join(t.TempDir(), "config.yaml"), "cluster-cidr: 10.50.9.0/22\n") + if got.ClusterCIDR != "10.50.9.0/22" || got.NodePodCIDR != "10.50.8.0/24" { + t.Fatalf("cluster %s node %s", got.ClusterCIDR, got.NodePodCIDR) + } +} + +func TestBadClusterCIDR(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "cluster-cidr: bananas\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "bananas") || !strings.Contains(err.Error(), "cluster-cidr") { + t.Fatalf("error %v", err) + } +} + +func TestAppendLists(t *testing.T) { + cases := []struct { + base string + extra string + read func(Server) []string + }{ + {base: "tls-san:\n - a.example\n", extra: "tls-san+: b.example\n", read: func(s Server) []string { return s.TLSSan }}, + {base: "kubelet-arg:\n - v=2\n", extra: "kubelet-arg+: v=3\n", read: func(s Server) []string { return s.KubeletArg }}, + {base: "disable:\n - traefik\n", extra: "disable+: coredns\n", read: func(s Server) []string { return s.Disable }}, + {base: "node-label:\n - a=1\n", extra: "node-label+:\n - b=2\n - c=3\n", read: func(s Server) []string { return s.NodeLabel }}, + } + wants := [][]string{ + {"a.example", "b.example"}, + {"v=2", "v=3"}, + {"traefik", "coredns"}, + {"a=1", "b=2", "c=3"}, + } + for i, tc := range cases { + t.Run(tc.extra, func(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path, tc.base) + writeFile(t, path+".d/10.yaml", tc.extra) + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(tc.read(got), wants[i]) { + t.Fatalf("list %#v", tc.read(got)) + } + }) + } +} + +func TestListReplacesWithoutPlus(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path, "tls-san:\n - a.example\n") + writeFile(t, path+".d/10.yaml", "tls-san:\n - b.example\n") + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got.TLSSan, []string{"b.example"}) { + t.Fatalf("san %#v", got.TLSSan) + } +} + +func TestAppendScalarKey(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "data-dir+: /var/extra\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "data-dir+") { + t.Fatalf("error %v", err) + } +} + +func TestPlusOnRejectedKey(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, "etcd-arg+: foo\n") + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "etcd-arg+") || !strings.Contains(err.Error(), "not accepted") { + t.Fatalf("error %v", err) + } +} + +func TestDisableUnknownName(t *testing.T) { + bodies := []string{ + "disable: [flannel]\n", + "disable+: flannel\n", + } + for _, body := range bodies { + t.Run(body, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + writeFile(t, path, body) + _, err := Load([]string{"--config", path}, nil) + if err == nil || !strings.Contains(err.Error(), "flannel") || !strings.Contains(err.Error(), "unknown") { + t.Fatalf("error %v", err) + } + }) + } +} + +func TestDisableNames(t *testing.T) { + got := loadPath(t, filepath.Join(t.TempDir(), "config.yaml"), + "disable: [coredns, servicelb, traefik, gateway-api-crd, local-storage, metrics-server, cert-manager, runtimes]\n") + want := []string{"coredns", "servicelb", "traefik", "gateway-api-crd", "local-storage", "metrics-server", "cert-manager", "runtimes"} + if !reflect.DeepEqual(got.Disable, want) { + t.Fatalf("disable %#v", got.Disable) + } +} + +func TestRepeatableKeys(t *testing.T) { + want := []string{ + "tls-san", + "node-label", + "node-taint", + "disable", + "kube-apiserver-arg", + "kube-controller-manager-arg", + "kube-scheduler-arg", + "kubelet-arg", + "kube-proxy-arg", + "helm-controller-arg", + } + if len(listFields) != len(want) { + t.Fatalf("list keys %#v", listKeys(listFields)) + } + for _, key := range want { + if _, ok := listFields[key]; !ok { + t.Errorf("missing list %s", key) + } + } +} + +func TestEnvNames(t *testing.T) { + cases := map[string]string{ + "datastore-endpoint": "EDGELET_KUBE_DATASTORE_ENDPOINT", + "data-dir": bundle.DataDirEnv, + "https-listen-port": "EDGELET_KUBE_HTTPS_LISTEN_PORT", + "v": "EDGELET_KUBE_V", + "kube-apiserver-arg": "EDGELET_KUBE_KUBE_APISERVER_ARG", + } + for key, want := range cases { + if got := envName(key); got != want { + t.Errorf("%s -> %s, want %s", key, got, want) + } + } +} + +func TestPrecedence(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path, ` +node-name: from-file +data-dir: /from-file +cluster-domain: file.local +tls-san: + - file.example +node-label: + - file=1 +cluster-cidr: 10.20.0.0/16 +`) + writeFile(t, path+".d/10-a.yaml", ` +node-name: from-a +data-dir: /from-a +`) + writeFile(t, path+".d/20-b.yaml", ` +data-dir: /from-b +cluster-domain: drop.local +tls-san+: drop.example +node-label+: drop=1 +`) + + got, err := Load([]string{ + "--config", path, + "--node-name", "from-flag", + "--debug=false", + }, func(key string) (string, bool) { + switch key { + case envName("node-name"): + return "from-env", true + case envName("cluster-domain"): + return "env.local", true + case envName("debug"): + return "true", true + case envName("node-label"): + return "env=1", true + case envName("cluster-cidr"): + return "10.50.0.0/16", true + default: + return "", false + } + }) + if err != nil { + t.Fatal(err) + } + + t.Run("defaults", func(t *testing.T) { + if got.BindAddress != DefaultBindAddress || got.HTTPSListenPort != DefaultHTTPSListenPort { + t.Fatalf("bind %q port %d", got.BindAddress, got.HTTPSListenPort) + } + if got.ServiceNodePortRange != DefaultServiceNodePortRange { + t.Fatalf("ports %s", got.ServiceNodePortRange) + } + }) + t.Run("drop-in over file", func(t *testing.T) { + if got.DataDir != "/from-b" { + t.Fatalf("data dir %q", got.DataDir) + } + }) + t.Run("env over drop-in", func(t *testing.T) { + if got.ClusterDomain != "env.local" { + t.Fatalf("domain %s", got.ClusterDomain) + } + if got.ClusterCIDR != "10.50.0.0/16" || got.NodePodCIDR != "10.50.0.0/24" { + t.Fatalf("cluster %s node %s", got.ClusterCIDR, got.NodePodCIDR) + } + }) + t.Run("flag over env", func(t *testing.T) { + if got.NodeName != "from-flag" { + t.Fatalf("node name %q", got.NodeName) + } + if got.Debug { + t.Fatal("debug stayed true") + } + }) + t.Run("append then env overrides", func(t *testing.T) { + if !reflect.DeepEqual(got.TLSSan, []string{"file.example", "drop.example"}) { + t.Fatalf("san %#v", got.TLSSan) + } + if !reflect.DeepEqual(got.NodeLabel, []string{"env=1"}) { + t.Fatalf("labels %#v", got.NodeLabel) + } + }) +} + +func TestFlagReplacesAppendedList(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeFile(t, path, "tls-san:\n - file.example\n") + writeFile(t, path+".d/10.yaml", "tls-san+: drop.example\n") + got, err := Load([]string{ + "--config", path, + "--tls-san", "flag-a.example", + "--tls-san", "flag-b.example", + }, func(key string) (string, bool) { + if key == envName("tls-san") { + return "env.example", true + } + return "", false + }) + if err != nil { + t.Fatal(err) + } + want := []string{"flag-a.example", "flag-b.example"} + if !reflect.DeepEqual(got.TLSSan, want) { + t.Fatalf("san %#v", got.TLSSan) + } +} + +func listKeys(fields map[string]func(*Server) *[]string) []string { + keys := make([]string, 0, len(fields)) + for key := range fields { + keys = append(keys, key) + } + return keys +} + +func loadPath(t *testing.T, path, body string) Server { + t.Helper() + writeFile(t, path, body) + got, err := Load([]string{"--config", path}, nil) + if err != nil { + t.Fatal(err) + } + return got +} + +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func yamlHasKey(body, key string) bool { + for _, line := range strings.Split(body, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), key+":") { + return true + } + } + return false +} + +func assertServer(t *testing.T, got, want Server) { + t.Helper() + got.present = nil + want.present = nil + if reflect.DeepEqual(got, want) { + return + } + gv := reflect.ValueOf(got) + wv := reflect.ValueOf(want) + typ := gv.Type() + for i := 0; i < typ.NumField(); i++ { + field := typ.Field(i) + if field.PkgPath != "" { + continue + } + gf := gv.Field(i).Interface() + wf := wv.Field(i).Interface() + if !reflect.DeepEqual(gf, wf) { + t.Errorf("%s = %#v, want %#v", field.Name, gf, wf) + } + } +} diff --git a/kube/internal/config/file.go b/kube/internal/config/file.go new file mode 100644 index 0000000..f00bf7d --- /dev/null +++ b/kube/internal/config/file.go @@ -0,0 +1,69 @@ +package config + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + "go.yaml.in/yaml/v3" +) + +func mergeFile(srv *Server, path string) error { + body, err := os.ReadFile(path) // #nosec G304 -- path is the config file or a drop-in + if err != nil { + return fmt.Errorf("read config %s: %w", path, err) + } + if len(bytes.TrimSpace(body)) == 0 { + return nil + } + var doc map[string]any + if err := yaml.Unmarshal(body, &doc); err != nil { + return fmt.Errorf("read config %s: %w", path, err) + } + if doc == nil { + return nil + } + keys := make([]string, 0, len(doc)) + for key := range doc { + keys = append(keys, key) + } + slices.Sort(keys) + for _, key := range keys { + if err := apply(srv, path, key, doc[key]); err != nil { + return err + } + } + return nil +} + +func dropIns(configFile string) ([]string, error) { + dir := configFile + ".d" + entries, err := os.ReadDir(dir) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + return nil, fmt.Errorf("read config directory %s: %w", dir, err) + } + names := make([]string, 0, len(entries)) + for _, entry := range entries { + if entry.IsDir() { + continue + } + name := entry.Name() + if !strings.HasSuffix(name, ".yaml") { + continue + } + names = append(names, name) + } + slices.Sort(names) + paths := make([]string, len(names)) + for i, name := range names { + paths[i] = filepath.Join(dir, name) + } + return paths, nil +} diff --git a/kube/internal/config/keys.go b/kube/internal/config/keys.go new file mode 100644 index 0000000..dc11f88 --- /dev/null +++ b/kube/internal/config/keys.go @@ -0,0 +1,296 @@ +package config + +import ( + "fmt" + "math" + "strings" +) + +// rejectedKeys are server options this process does not accept. +var rejectedKeys = map[string]struct{}{ + "token": {}, + "token-file": {}, + "agent-token": {}, + "agent-token-file": {}, + "server": {}, + "cluster-init": {}, + "cluster-reset": {}, + "cluster-reset-restore-path": {}, + "lb-server-port": {}, + "etcd-arg": {}, + "etcd-expose-metrics": {}, + "egress-selector-mode": {}, + "vpn-auth": {}, + "vpn-auth-file": {}, + "embedded-registry": {}, + "disable-scheduler": {}, + "disable-kube-proxy": {}, + "disable-cloud-controller": {}, + "disable-network-policy": {}, + "disable-agent": {}, + "docker": {}, + "rootless": {}, +} + +var rejectedPrefixes = []string{ + "flannel-", + "etcd-snapshot-", + "etcd-s3-", +} + +type valueKind int + +const ( + kindString valueKind = iota + kindBool + kindInt + kindList +) + +// keyKind is the value shape of each accepted key. +var keyKind = map[string]valueKind{} + +type setter func(*Server, any) error + +func stringField(key string, field func(*Server) *string) setter { + keyKind[key] = kindString + return func(srv *Server, value any) error { + text, err := asString(key, value) + if err != nil { + return err + } + *field(srv) = text + return nil + } +} + +func boolField(key string, field func(*Server) *bool) setter { + keyKind[key] = kindBool + return func(srv *Server, value any) error { + flag, err := asBool(key, value) + if err != nil { + return err + } + *field(srv) = flag + return nil + } +} + +func intField(key string, field func(*Server) *int) setter { + keyKind[key] = kindInt + return func(srv *Server, value any) error { + number, err := asInt(key, value) + if err != nil { + return err + } + *field(srv) = number + return nil + } +} + +func listField(key string, field func(*Server) *[]string) setter { + listFields[key] = field + keyKind[key] = kindList + return func(srv *Server, value any) error { + items, err := asList(key, value) + if err != nil { + return err + } + if err := checkDisable(key, items); err != nil { + return err + } + *field(srv) = items + return nil + } +} + +// listFields are the keys a "+" suffix appends to. +var listFields = map[string]func(*Server) *[]string{} + +// disableNames are the addon names the disable key accepts. +var disableNames = map[string]struct{}{ + "coredns": {}, + "servicelb": {}, + "traefik": {}, + "local-storage": {}, + "metrics-server": {}, + "cert-manager": {}, + "gateway-api-crd": {}, + "runtimes": {}, +} + +var setters = map[string]setter{ + "config": stringField("config", func(srv *Server) *string { return &srv.Config }), + "data-dir": stringField("data-dir", func(srv *Server) *string { return &srv.DataDir }), + "write-kubeconfig": stringField("write-kubeconfig", func(srv *Server) *string { return &srv.WriteKubeconfig }), + "write-kubeconfig-mode": stringField("write-kubeconfig-mode", func(srv *Server) *string { return &srv.WriteKubeconfigMode }), + "write-kubeconfig-group": stringField("write-kubeconfig-group", func(srv *Server) *string { return &srv.WriteKubeconfigGroup }), + "bind-address": stringField("bind-address", func(srv *Server) *string { return &srv.BindAddress }), + "https-listen-port": intField("https-listen-port", func(srv *Server) *int { return &srv.HTTPSListenPort }), + "advertise-address": stringField("advertise-address", func(srv *Server) *string { return &srv.AdvertiseAddress }), + "advertise-port": intField("advertise-port", func(srv *Server) *int { return &srv.AdvertisePort }), + "tls-san": listField("tls-san", func(srv *Server) *[]string { return &srv.TLSSan }), + "tls-san-security": boolField("tls-san-security", func(srv *Server) *bool { return &srv.TLSSanSecurity }), + "node-name": stringField("node-name", func(srv *Server) *string { return &srv.NodeName }), + "node-ip": stringField("node-ip", func(srv *Server) *string { return &srv.NodeIP }), + "node-external-ip": stringField("node-external-ip", func(srv *Server) *string { return &srv.NodeExternalIP }), + "node-label": listField("node-label", func(srv *Server) *[]string { return &srv.NodeLabel }), + "node-taint": listField("node-taint", func(srv *Server) *[]string { return &srv.NodeTaint }), + "resolv-conf": stringField("resolv-conf", func(srv *Server) *string { return &srv.ResolvConf }), + "cluster-cidr": stringField("cluster-cidr", func(srv *Server) *string { return &srv.ClusterCIDR }), + "service-cidr": stringField("service-cidr", func(srv *Server) *string { return &srv.ServiceCIDR }), + "cluster-dns": stringField("cluster-dns", func(srv *Server) *string { return &srv.ClusterDNS }), + "cluster-domain": stringField("cluster-domain", func(srv *Server) *string { return &srv.ClusterDomain }), + "service-node-port-range": stringField("service-node-port-range", func(srv *Server) *string { return &srv.ServiceNodePortRange }), + "pause-image": stringField("pause-image", func(srv *Server) *string { return &srv.PauseImage }), + "datastore-endpoint": stringField("datastore-endpoint", func(srv *Server) *string { return &srv.DatastoreEndpoint }), + "datastore-cafile": stringField("datastore-cafile", func(srv *Server) *string { return &srv.DatastoreCAFile }), + "datastore-certfile": stringField("datastore-certfile", func(srv *Server) *string { return &srv.DatastoreCertFile }), + "datastore-keyfile": stringField("datastore-keyfile", func(srv *Server) *string { return &srv.DatastoreKeyFile }), + "datastore-nats-creds": stringField("datastore-nats-creds", func(srv *Server) *string { return &srv.DatastoreNATSCreds }), + "disable": listField("disable", func(srv *Server) *[]string { return &srv.Disable }), + "disable-helm-controller": boolField("disable-helm-controller", func(srv *Server) *bool { return &srv.DisableHelmController }), + "default-local-storage-path": stringField("default-local-storage-path", func(srv *Server) *string { return &srv.DefaultLocalStoragePath }), + "cluster-issuer-email": stringField("cluster-issuer-email", func(srv *Server) *string { return &srv.ClusterIssuerEmail }), + "debug": boolField("debug", func(srv *Server) *bool { return &srv.Debug }), + "v": intField("v", func(srv *Server) *int { return &srv.V }), + "vmodule": stringField("vmodule", func(srv *Server) *string { return &srv.VModule }), + "log": stringField("log", func(srv *Server) *string { return &srv.Log }), + "alsologtostderr": boolField("alsologtostderr", func(srv *Server) *bool { return &srv.AlsoLogToStderr }), + "kube-apiserver-arg": listField("kube-apiserver-arg", func(srv *Server) *[]string { return &srv.KubeAPIServerArg }), + "kube-controller-manager-arg": listField("kube-controller-manager-arg", func(srv *Server) *[]string { return &srv.KubeControllerManagerArg }), + "kube-scheduler-arg": listField("kube-scheduler-arg", func(srv *Server) *[]string { return &srv.KubeSchedulerArg }), + "kubelet-arg": listField("kubelet-arg", func(srv *Server) *[]string { return &srv.KubeletArg }), + "kube-proxy-arg": listField("kube-proxy-arg", func(srv *Server) *[]string { return &srv.KubeProxyArg }), + "helm-controller-arg": listField("helm-controller-arg", func(srv *Server) *[]string { return &srv.HelmControllerArg }), + "snapshotter": stringField("snapshotter", func(srv *Server) *string { return &srv.Snapshotter }), + "prefer-bundled-bin": boolField("prefer-bundled-bin", func(srv *Server) *bool { return &srv.PreferBundledBin }), + "selinux": boolField("selinux", func(srv *Server) *bool { return &srv.SELinux }), + "protect-kernel-defaults": boolField("protect-kernel-defaults", func(srv *Server) *bool { return &srv.ProtectKernelDefaults }), + "secrets-encryption": boolField("secrets-encryption", func(srv *Server) *bool { return &srv.SecretsEncryption }), + "private-registry": stringField("private-registry", func(srv *Server) *string { return &srv.PrivateRegistry }), + "system-default-registry": stringField("system-default-registry", func(srv *Server) *string { return &srv.SystemDefaultRegistry }), + "disable-default-registry-endpoint": boolField("disable-default-registry-endpoint", func(srv *Server) *bool { return &srv.DisableDefaultRegistryEndpoint }), +} + +func rejected(key string) bool { + if _, ok := rejectedKeys[key]; ok { + return true + } + for _, prefix := range rejectedPrefixes { + if strings.HasPrefix(key, prefix) { + return true + } + } + return false +} + +func apply(srv *Server, path, key string, value any) error { + name := key + appendList := false + if strings.HasSuffix(key, "+") { + appendList = true + name = strings.TrimSuffix(key, "+") + } + if rejected(name) { + return fmt.Errorf("%s: config key %q is not accepted", path, key) + } + set, ok := setters[name] + if !ok { + return fmt.Errorf("%s: unknown config key %q", path, key) + } + // Null leaves the key unset so a default, or an earlier file, still applies. + if value == nil { + return nil + } + if appendList { + field, ok := listFields[name] + if !ok { + return fmt.Errorf("%s: config key %q is not a list", path, key) + } + items, err := asList(key, value) + if err != nil { + return fmt.Errorf("%s: %w", path, err) + } + if err := checkDisable(name, items); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + dst := field(srv) + *dst = append(*dst, items...) + srv.present[name] = true + return nil + } + if err := set(srv, value); err != nil { + return fmt.Errorf("%s: %w", path, err) + } + srv.present[name] = true + return nil +} + +func checkDisable(key string, items []string) error { + if key != "disable" { + return nil + } + for _, name := range items { + if _, ok := disableNames[name]; !ok { + return fmt.Errorf("unknown disable name %q", name) + } + } + return nil +} + +func asString(key string, value any) (string, error) { + text, ok := value.(string) + if !ok { + return "", fmt.Errorf("config key %q must be a string", key) + } + return text, nil +} + +func asBool(key string, value any) (bool, error) { + flag, ok := value.(bool) + if !ok { + return false, fmt.Errorf("config key %q must be true or false", key) + } + return flag, nil +} + +func asInt(key string, value any) (int, error) { + var number int64 + switch typed := value.(type) { + case int: + number = int64(typed) + case int64: + number = typed + case uint64: + if typed > uint64(math.MaxInt64) { + return 0, fmt.Errorf("config key %q must be an integer", key) + } + number = int64(typed) + default: + return 0, fmt.Errorf("config key %q must be an integer", key) + } + if int64(int(number)) != number { + return 0, fmt.Errorf("config key %q must be an integer", key) + } + return int(number), nil +} + +func asList(key string, value any) ([]string, error) { + switch typed := value.(type) { + case string: + return []string{typed}, nil + case []any: + items := make([]string, 0, len(typed)) + for _, item := range typed { + text, ok := item.(string) + if !ok { + return nil, fmt.Errorf("config key %q must be a list of strings", key) + } + items = append(items, text) + } + return items, nil + default: + return nil, fmt.Errorf("config key %q must be a list of strings", key) + } +} diff --git a/kube/internal/config/network.go b/kube/internal/config/network.go new file mode 100644 index 0000000..4e603b8 --- /dev/null +++ b/kube/internal/config/network.go @@ -0,0 +1,119 @@ +package config + +import ( + "fmt" + "net" +) + +// applyNetwork fills cluster addresses the files left unset and checks that +// cluster DNS lies in the service network. The node pod range and the derived +// DNS address are stored on the server for later callers. +func (s *Server) applyNetwork() error { + if !s.present["cluster-cidr"] { + s.ClusterCIDR = DefaultClusterCIDR + } + if !s.present["service-cidr"] { + s.ServiceCIDR = DefaultServiceCIDR + } + if !s.present["cluster-domain"] { + s.ClusterDomain = DefaultClusterDomain + } + if !s.present["service-node-port-range"] { + s.ServiceNodePortRange = DefaultServiceNodePortRange + } + pod, err := nodePodCIDR(s.ClusterCIDR) + if err != nil { + return err + } + s.NodePodCIDR = pod + if !s.present["cluster-dns"] { + dns, err := tenthAddress(s.ServiceCIDR) + if err != nil { + return err + } + s.ClusterDNS = dns + } + return clusterDNSInService(s.ClusterDNS, s.ServiceCIDR) +} + +// nodePodCIDR is the first /24 of cluster. The mask stays /24. +func nodePodCIDR(cluster string) (string, error) { + _, network, err := net.ParseCIDR(cluster) + if err != nil { + return "", fmt.Errorf("cluster-cidr %q is not a network", cluster) + } + ip := network.IP.To4() + if ip == nil { + return "", fmt.Errorf("cluster-cidr %q is not an IPv4 network", cluster) + } + mask := net.CIDRMask(24, 32) + pod := ip.Mask(mask) + if pod == nil { + return "", fmt.Errorf("cluster-cidr %q is not an IPv4 network", cluster) + } + return (&net.IPNet{IP: pod, Mask: mask}).String(), nil +} + +// FirstServiceAddress is the first host address of cidr. +// Kubernetes assigns that address to the kubernetes API service. +// The default service network 10.43.0.0/16 yields 10.43.0.1. +func FirstServiceAddress(cidr string) (string, error) { + ip, network, err := offsetAddress(cidr, 1) + if err != nil { + return "", err + } + if !network.Contains(ip) { + return "", fmt.Errorf("service-cidr %q has no service address", cidr) + } + return ip.String(), nil +} + +// tenthAddress is the address ten steps from the start of cidr. +// The default service network 10.43.0.0/16 yields 10.43.0.10. +func tenthAddress(cidr string) (string, error) { + ip, network, err := offsetAddress(cidr, 10) + if err != nil { + return "", err + } + if !network.Contains(ip) { + return "", fmt.Errorf("service-cidr %q has no 10th address", cidr) + } + return ip.String(), nil +} + +func offsetAddress(cidr string, steps int) (net.IP, *net.IPNet, error) { + _, network, err := net.ParseCIDR(cidr) + if err != nil { + return nil, nil, fmt.Errorf("service-cidr %q is not a network", cidr) + } + ip := make(net.IP, len(network.IP)) + copy(ip, network.IP) + for i := 0; i < steps; i++ { + if !incIP(ip) { + return nil, nil, fmt.Errorf("service-cidr %q has no service address", cidr) + } + } + return ip, network, nil +} + +func clusterDNSInService(dns, cidr string) error { + _, network, err := net.ParseCIDR(cidr) + if err != nil { + return fmt.Errorf("service-cidr %q is not a network", cidr) + } + ip := net.ParseIP(dns) + if ip == nil || !network.Contains(ip) { + return fmt.Errorf("cluster-dns %q is outside service-cidr %q", dns, cidr) + } + return nil +} + +func incIP(ip net.IP) bool { + for i := len(ip) - 1; i >= 0; i-- { + ip[i]++ + if ip[i] != 0 { + return true + } + } + return false +} diff --git a/kube/internal/config/overlay.go b/kube/internal/config/overlay.go new file mode 100644 index 0000000..93b0e63 --- /dev/null +++ b/kube/internal/config/overlay.go @@ -0,0 +1,166 @@ +package config + +import ( + "fmt" + "path/filepath" + "slices" + "strconv" + "strings" +) + +// applyEnv overlays EDGELET_KUBE_* values. A set variable replaces the key. +// List append from the files has already run. +func applyEnv(srv *Server, lookupEnv func(string) (string, bool)) error { + if lookupEnv == nil { + return nil + } + for _, key := range knownKeys() { + name := envName(key) + raw, ok := lookupEnv(name) + if !ok || raw == "" { + continue + } + if err := assign(srv, name, key, raw); err != nil { + return err + } + } + return nil +} + +// applyFlags overlays command-line flags. The flag replaces the key, including +// a value that came from the environment. Repeated list flags collect one +// element each and then replace the key. +func applyFlags(srv *Server, args []string) error { + lists := map[string][]string{} + scalars := map[string]string{} + var order []string + seen := map[string]bool{} + + for i := 0; i < len(args); i++ { + arg := args[i] + if arg == "--" { + break + } + if !strings.HasPrefix(arg, "--") { + continue + } + key, raw, hasValue := strings.Cut(strings.TrimPrefix(arg, "--"), "=") + if key == "" { + return fmt.Errorf("unknown config key %q", arg) + } + if rejected(key) { + return fmt.Errorf("config key %q is not accepted", key) + } + kind, ok := keyKind[key] + if !ok { + return fmt.Errorf("unknown config key %q", key) + } + if !hasValue { + next, err := flagValue(args, i, key, kind) + if err != nil { + return err + } + if next.consumed { + i++ + } + raw = next.raw + } + if !seen[key] { + seen[key] = true + order = append(order, key) + } + if kind == kindList { + lists[key] = append(lists[key], raw) + continue + } + scalars[key] = raw + } + + for _, key := range order { + if items, ok := lists[key]; ok { + if err := assignList(srv, "--"+key, key, items); err != nil { + return err + } + continue + } + if err := assign(srv, "--"+key, key, scalars[key]); err != nil { + return err + } + } + return nil +} + +type takenFlag struct { + raw string + consumed bool +} + +func flagValue(args []string, i int, key string, kind valueKind) (takenFlag, error) { + if kind == kindBool { + if i+1 < len(args) && (args[i+1] == "true" || args[i+1] == "false") { + return takenFlag{raw: args[i+1], consumed: true}, nil + } + return takenFlag{raw: "true"}, nil + } + if i+1 >= len(args) || args[i+1] == "--" || strings.HasPrefix(args[i+1], "-") { + return takenFlag{}, fmt.Errorf("config key %q requires a value", key) + } + return takenFlag{raw: args[i+1], consumed: true}, nil +} + +func assign(srv *Server, source, key, raw string) error { + if key == "config" { + raw = filepath.Clean(raw) + } + if keyKind[key] == kindList { + return assignList(srv, source, key, []string{raw}) + } + value, err := parseScalar(key, raw) + if err != nil { + return fmt.Errorf("%s: %w", source, err) + } + return apply(srv, source, key, value) +} + +func assignList(srv *Server, source, key string, items []string) error { + values := make([]any, len(items)) + for i, item := range items { + values[i] = item + } + return apply(srv, source, key, values) +} + +func parseScalar(key, raw string) (any, error) { + switch keyKind[key] { + case kindBool: + switch raw { + case "true": + return true, nil + case "false": + return false, nil + default: + return nil, fmt.Errorf("config key %q must be true or false", key) + } + case kindInt: + number, err := strconv.Atoi(raw) + if err != nil { + return nil, fmt.Errorf("config key %q must be an integer", key) + } + return number, nil + default: + return raw, nil + } +} + +func envName(key string) string { + return "EDGELET_KUBE_" + strings.ToUpper(strings.ReplaceAll(key, "-", "_")) +} + +func knownKeys() []string { + keys := make([]string, 0, len(setters)) + for key := range setters { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} diff --git a/kube/internal/conformance/doc.go b/kube/internal/conformance/doc.go new file mode 100644 index 0000000..0c79a92 --- /dev/null +++ b/kube/internal/conformance/doc.go @@ -0,0 +1,2 @@ +// Package conformance checks the conformance job definition. +package conformance diff --git a/kube/internal/conformance/job_test.go b/kube/internal/conformance/job_test.go new file mode 100644 index 0000000..4719aee --- /dev/null +++ b/kube/internal/conformance/job_test.go @@ -0,0 +1,51 @@ +package conformance + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestConformanceJob(t *testing.T) { + root := filepath.Join("..", "..", "..") + workflow, err := os.ReadFile(filepath.Join(root, ".github", "workflows", "conformance-kube.yml")) + if err != nil { + t.Fatal(err) + } + script, err := os.ReadFile(filepath.Join(root, "kube", "scripts", "conformance.sh")) + if err != nil { + t.Fatal(err) + } + text := string(workflow) + for _, want := range []string{ + "certified-conformance", + "edgelet-kube-linux-amd64", + "edgelet-kube-airgap-images-amd64.tar.zst", + "runs-on: ubuntu-latest", + "timeout-minutes: 240", + `CONFORMANCE_TIMEOUT_MINUTES: "240"`, + } { + if !strings.Contains(text, want) { + t.Fatalf("job definition missing %s", want) + } + } + if strings.Contains(text, "--disable") || strings.Contains(text, "\ndisable:") { + t.Fatal("job definition turns an addon off") + } + body := string(script) + for _, want := range []string{ + "--mode=certified-conformance", + "edgelet-kube-linux-amd64", + "edgelet-kube-airgap-images-amd64.tar.zst", + "CONFORMANCE_TIMEOUT_MINUTES:-240", + "reserve_minutes=45", + } { + if !strings.Contains(body, want) { + t.Fatalf("conformance script missing %s", want) + } + } + if strings.Contains(body, "--disable") { + t.Fatal("conformance script turns an addon off") + } +} diff --git a/kube/internal/containerd/child.go b/kube/internal/containerd/child.go new file mode 100644 index 0000000..5d6b44f --- /dev/null +++ b/kube/internal/containerd/child.go @@ -0,0 +1,13 @@ +package containerd + +// MaybeRunChild serves containerd when args carry ChildArg. +// The process returns when containerd exits. It does not start the API server. +func MaybeRunChild(args []string) (bool, error) { + if len(args) < 2 || args[1] != ChildArg { + return false, nil + } + if err := serveChild(args); err != nil { + return true, err + } + return true, nil +} diff --git a/kube/internal/containerd/child_linux_test.go b/kube/internal/containerd/child_linux_test.go new file mode 100644 index 0000000..13b6fd6 --- /dev/null +++ b/kube/internal/containerd/child_linux_test.go @@ -0,0 +1,254 @@ +//go:build linux && cgo + +package containerd + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "golang.org/x/sys/unix" +) + +func TestMain(m *testing.M) { + handled, err := MaybeRunChild(os.Args) + if handled { + if err != nil { + fmt.Fprintf(os.Stderr, "containerd child: %v\n", err) + unix.Exit(1) + } + unix.Exit(0) + } + m.Run() +} + +func TestChildServesCRI(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-child-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + sock := filepath.Join(dir, "containerd.sock") + logFile, err := os.Create(filepath.Join(dir, "child.log")) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = logFile.Close() + }() + + cmd := exec.Command(os.Args[0], + ChildArg, + "--address", sock, + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + "--crun", filepath.Join(dir, "crun"), + "--shim", filepath.Join(dir, "containerd-shim-runc-v2"), + "--cni-bin-dir", filepath.Join(dir, "bin"), + "--cni-conf-dir", filepath.Join(dir, "net.d"), + ) + cmd.Stdout = logFile + cmd.Stderr = logFile + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + stopChild(cmd) + }) + + deadline := time.Now().Add(45 * time.Second) + var version RuntimeInfo + for { + version, err = RuntimeVersion(t.Context(), sock) + if err == nil { + break + } + if time.Now().After(deadline) { + logText, _ := os.ReadFile(logFile.Name()) + t.Fatalf("cri version: %v\n%s", err, logText) + } + time.Sleep(200 * time.Millisecond) + } + if version.RuntimeName == "" && version.RuntimeVersion == "" { + t.Fatalf("empty cri version %+v", version) + } + + cmdline, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", cmd.Process.Pid)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(cmdline), ChildArg) { + t.Fatalf("cmdline %q", cmdline) + } + listening, err := processListens(cmd.Process.Pid, 6443) + if err != nil { + t.Fatal(err) + } + if listening { + t.Fatal("child listens on 6443") + } + + t.Setenv(SocketEnv, sock) + if err := RunCtr([]string{"version"}); err != nil { + logText, _ := os.ReadFile(logFile.Name()) + t.Fatalf("ctr: %v\n%s", err, logText) + } + if err := RunCrictl([]string{"version"}); err != nil { + t.Fatalf("crictl: %v", err) + } + + body, err := os.ReadFile(filepath.Join(dir, "root", "config.toml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "SystemdCgroup = true") || !strings.Contains(string(body), `default_runtime_name = "crun"`) { + t.Fatalf("config:\n%s", body) + } +} + +func TestChildUsesRuntimePaths(t *testing.T) { + for _, path := range []string{paths.ContainerdSocket, paths.ContainerdRoot, paths.ContainerdState, paths.CNIConfDir} { + if _, err := os.Lstat(path); err == nil { + t.Fatalf("%s already exists", path) + } else if !os.IsNotExist(err) { + t.Fatal(err) + } + } + logFile, err := os.CreateTemp("", "edgelet-kube-child-*.log") + if err != nil { + t.Fatal(err) + } + defer func() { + _ = logFile.Close() + _ = os.Remove(logFile.Name()) + }() + + cmd := exec.Command(os.Args[0], ChildArg) + cmd.Stdout = logFile + cmd.Stderr = logFile + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + stopChild(cmd) + _ = os.RemoveAll(paths.ContainerdState) + _ = os.RemoveAll(paths.ContainerdRoot) + _ = os.RemoveAll(paths.CNIConfDir) + removeEmpty(filepath.Dir(paths.CNIConfDir)) + removeEmpty(filepath.Dir(filepath.Dir(paths.CNIConfDir))) + removeEmpty(filepath.Dir(paths.ContainerdRoot)) + removeEmpty(filepath.Dir(filepath.Dir(paths.ContainerdRoot))) + }) + + deadline := time.Now().Add(20 * time.Second) + for { + if _, err := os.Stat(paths.ContainerdSocket); err == nil { + break + } + if time.Now().After(deadline) { + logText, _ := os.ReadFile(logFile.Name()) + t.Fatalf("socket %s missing\n%s", paths.ContainerdSocket, logText) + } + time.Sleep(200 * time.Millisecond) + } + body, err := os.ReadFile(filepath.Join(paths.ContainerdRoot, "config.toml")) + if err != nil { + t.Fatal(err) + } + text := string(body) + for _, want := range []string{paths.ContainerdRoot, paths.ContainerdSocket, paths.CNIConfDir, `snapshotter = "overlayfs"`} { + if !strings.Contains(text, want) { + t.Fatalf("config missing %q\n%s", want, text) + } + } + for _, blocked := range []string{"/opt/cni/bin", "/run/containerd/containerd.sock"} { + if strings.Contains(text, blocked) { + t.Fatalf("config contains %s\n%s", blocked, text) + } + } +} + +func removeEmpty(path string) { + _ = os.Remove(path) +} + +func stopChild(cmd *exec.Cmd) { + if cmd.Process == nil { + return + } + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + done := make(chan struct{}) + go func() { + _, _ = cmd.Process.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + <-done + } +} + +func processListens(pid, port int) (bool, error) { + inodes, err := listenInodes(port) + if err != nil || len(inodes) == 0 { + return false, err + } + entries, err := os.ReadDir(fmt.Sprintf("/proc/%d/fd", pid)) + if err != nil { + return false, err + } + for _, entry := range entries { + target, err := os.Readlink(filepath.Join(fmt.Sprintf("/proc/%d/fd", pid), entry.Name())) + if err != nil || !strings.HasPrefix(target, "socket:[") || !strings.HasSuffix(target, "]") { + continue + } + inode := strings.TrimSuffix(strings.TrimPrefix(target, "socket:["), "]") + if _, ok := inodes[inode]; ok { + return true, nil + } + } + return false, nil +} + +func listenInodes(port int) (map[string]struct{}, error) { + inodes := map[string]struct{}{} + for _, name := range []string{"/proc/net/tcp", "/proc/net/tcp6"} { + body, err := os.ReadFile(name) + if err != nil { + if os.IsNotExist(err) { + continue + } + return nil, err + } + lines := strings.Split(string(body), "\n") + for _, line := range lines[1:] { + fields := strings.Fields(line) + if len(fields) < 10 || fields[3] != "0A" { + continue + } + local := fields[1] + colon := strings.LastIndex(local, ":") + if colon < 0 { + continue + } + var got int + if _, err := fmt.Sscanf(local[colon+1:], "%x", &got); err != nil || got != port { + continue + } + inodes[fields[9]] = struct{}{} + } + } + return inodes, nil +} diff --git a/kube/internal/containerd/client_linux.go b/kube/internal/containerd/client_linux.go new file mode 100644 index 0000000..b8af85c --- /dev/null +++ b/kube/internal/containerd/client_linux.go @@ -0,0 +1,104 @@ +//go:build linux && cgo + +package containerd + +import ( + "context" + "errors" + "fmt" + "net" + "time" + + "github.com/containerd/containerd/v2/cmd/ctr/app" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + runtimev1 "k8s.io/cri-api/pkg/apis/runtime/v1" +) + +// RunCtr runs ctr against the containerd socket. +func RunCtr(args []string) error { + socket, rest, err := clientSocket(args) + if err != nil { + return err + } + argv := append([]string{"ctr", "--address", socket}, rest...) + if err := app.New().Run(argv); err != nil { + return fmt.Errorf("ctr: %w", err) + } + return nil +} + +// RunCrictl runs crictl against the containerd CRI socket. +func RunCrictl(args []string) error { + socket, rest, err := clientSocket(args) + if err != nil { + return err + } + if len(rest) == 0 || rest[0] != "version" { + command := "" + if len(rest) > 0 { + command = rest[0] + } + return fmt.Errorf("crictl command %q is unavailable", command) + } + version, err := RuntimeVersion(context.Background(), socket) + if err != nil { + return err + } + fmt.Printf("RuntimeName: %s\nRuntimeVersion: %s\nRuntimeApiVersion: %s\n", version.RuntimeName, version.RuntimeVersion, version.RuntimeAPIVersion) + return nil +} + +// RuntimeInfo is the CRI runtime version. +type RuntimeInfo struct { + // RuntimeName is the runtime that answered the version call. + RuntimeName string + // RuntimeVersion is the runtime version. + RuntimeVersion string + // RuntimeAPIVersion is the CRI API version. + RuntimeAPIVersion string +} + +// Dial opens a gRPC connection to the containerd socket. +func Dial(socket string) (*grpc.ClientConn, error) { + if err := checkSocket(socket); err != nil { + return nil, err + } + conn, err := grpc.NewClient("passthrough:///containerd", + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + var dialer net.Dialer + return dialer.DialContext(ctx, "unix", socket) + }), + ) + if err != nil { + return nil, fmt.Errorf("dial cri: %w", err) + } + return conn, nil +} + +// RuntimeVersion calls the CRI version method on socket. +func RuntimeVersion(ctx context.Context, socket string) (RuntimeInfo, error) { + dialCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + conn, err := Dial(socket) + if err != nil { + return RuntimeInfo{}, err + } + defer func() { + _ = conn.Close() + }() + resp, err := runtimev1.NewRuntimeServiceClient(conn).Version(dialCtx, &runtimev1.VersionRequest{}) + if err != nil { + return RuntimeInfo{}, fmt.Errorf("cri version: %w", err) + } + info := RuntimeInfo{ + RuntimeName: resp.GetRuntimeName(), + RuntimeVersion: resp.GetRuntimeVersion(), + RuntimeAPIVersion: resp.GetRuntimeApiVersion(), + } + if info.RuntimeName == "" && info.RuntimeVersion == "" { + return RuntimeInfo{}, errors.New("cri version response was empty") + } + return info, nil +} diff --git a/kube/internal/containerd/config.go b/kube/internal/containerd/config.go new file mode 100644 index 0000000..5d274ce --- /dev/null +++ b/kube/internal/containerd/config.go @@ -0,0 +1,422 @@ +package containerd + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "github.com/eclipse-iofog/edgelet-kube/internal/registries" + "github.com/pelletier/go-toml" +) + +// RuntimeName is the CRI runtime handler backed by crun. +const RuntimeName = "crun" + +// Settings is the containerd child configuration. +type Settings struct { + // Socket is the containerd gRPC socket. + Socket string + // Root is the containerd persistent directory. + Root string + // State is the containerd transient directory. + State string + // ConfigFile is the containerd config file to write. + ConfigFile string + // CrunBinary is the crun executable. + CrunBinary string + // ShimBinary is the containerd-shim-runc-v2 executable. + ShimBinary string + // CNIBinDir is the directory of CNI plugin binaries. + CNIBinDir string + // CNIConfDir is the directory of CNI configuration. + CNIConfDir string + // Snapshotter is the container snapshot driver. + Snapshotter string + // LogLevel is the containerd log level. + LogLevel string + // RegistryFile is the registries file. A missing file leaves containerd on upstream endpoints. + RegistryFile string + // RegistryDir is the containerd hosts directory. + RegistryDir string + // DisableDefaultEndpoint omits the upstream registry for names listed in RegistryFile. + DisableDefaultEndpoint bool + // PauseImage is the sandbox image. + PauseImage string +} + +// ParseChildArgs reads the containerd child command line. +// args[0] is the executable and args[1] is ChildArg. +func ParseChildArgs(args []string) (Settings, error) { + if len(args) < 2 || args[1] != ChildArg { + return Settings{}, fmt.Errorf("containerd child requires %s", ChildArg) + } + var settings Settings + for i := 2; i < len(args); i++ { + name, value, next, err := childFlag(args, i) + if err != nil { + return Settings{}, err + } + i = next + switch name { + case "address": + settings.Socket = value + case "root": + settings.Root = value + case "state": + settings.State = value + case "config": + settings.ConfigFile = value + case "crun": + settings.CrunBinary = value + case "shim": + settings.ShimBinary = value + case "cni-bin-dir": + settings.CNIBinDir = value + case "cni-conf-dir": + settings.CNIConfDir = value + case "snapshotter": + settings.Snapshotter = value + case "log-level": + settings.LogLevel = value + case "private-registry": + settings.RegistryFile = value + case "pause-image": + settings.PauseImage = value + case "disable-default-registry-endpoint": + flag, err := strconv.ParseBool(value) + if err != nil { + return Settings{}, errors.New("disable-default-registry-endpoint requires true or false") + } + settings.DisableDefaultEndpoint = flag + default: + return Settings{}, fmt.Errorf("unknown containerd child flag %q", name) + } + } + if err := settings.applyDefaults(); err != nil { + return Settings{}, err + } + if err := settings.validate(); err != nil { + return Settings{}, err + } + return settings, nil +} + +func childFlag(args []string, i int) (string, string, int, error) { + arg := args[i] + if arg == "--" || !strings.HasPrefix(arg, "--") { + return "", "", i, fmt.Errorf("unknown containerd child argument %q", arg) + } + body := strings.TrimPrefix(arg, "--") + name, value, ok := strings.Cut(body, "=") + if !ok { + if i+1 >= len(args) || args[i+1] == "" || strings.HasPrefix(args[i+1], "-") { + return "", "", i, fmt.Errorf("%s requires a value", name) + } + value = args[i+1] + i++ + } + if name == "" || value == "" { + return "", "", i, fmt.Errorf("%s requires a value", name) + } + return name, value, i, nil +} + +func (s *Settings) applyDefaults() error { + exe, err := os.Executable() + if err != nil { + return fmt.Errorf("resolve executable: %w", err) + } + bin := filepath.Dir(exe) + if s.Socket == "" { + s.Socket = paths.ContainerdSocket + } + if s.Root == "" { + s.Root = paths.ContainerdRoot + } + if s.State == "" { + s.State = paths.ContainerdState + } + if s.CrunBinary == "" { + s.CrunBinary = filepath.Join(bin, "crun") + } + if s.ShimBinary == "" { + s.ShimBinary = filepath.Join(bin, "containerd-shim-runc-v2") + } + if s.CNIBinDir == "" { + s.CNIBinDir = bin + } + if s.CNIConfDir == "" { + s.CNIConfDir = paths.CNIConfDir + } + if s.ConfigFile == "" { + s.ConfigFile = filepath.Join(s.Root, "config.toml") + } + if s.Snapshotter == "" { + s.Snapshotter = config.DefaultSnapshotter + } + if s.LogLevel == "" { + s.LogLevel = "warn" + } + if s.PauseImage == "" { + s.PauseImage = config.DefaultPauseImage + } + if s.RegistryDir == "" { + s.RegistryDir = filepath.Join(s.Root, "certs.d") + } + var errAbs error + s.Socket, errAbs = absPath(s.Socket) + if errAbs != nil { + return errAbs + } + s.Root, errAbs = absPath(s.Root) + if errAbs != nil { + return errAbs + } + s.State, errAbs = absPath(s.State) + if errAbs != nil { + return errAbs + } + s.ConfigFile, errAbs = absPath(s.ConfigFile) + if errAbs != nil { + return errAbs + } + s.CrunBinary, errAbs = absPath(s.CrunBinary) + if errAbs != nil { + return errAbs + } + s.ShimBinary, errAbs = absPath(s.ShimBinary) + if errAbs != nil { + return errAbs + } + s.CNIBinDir, errAbs = absPath(s.CNIBinDir) + if errAbs != nil { + return errAbs + } + s.CNIConfDir, errAbs = absPath(s.CNIConfDir) + if errAbs != nil { + return errAbs + } + s.RegistryDir, errAbs = absPath(s.RegistryDir) + if errAbs != nil { + return errAbs + } + s.RegistryFile, errAbs = absPath(s.RegistryFile) + return errAbs +} + +func absPath(path string) (string, error) { + if path == "" { + return "", nil + } + abs, err := filepath.Abs(path) + if err != nil { + return "", fmt.Errorf("absolute path %s: %w", path, err) + } + return abs, nil +} + +func (s Settings) validate() error { + if s.Socket == "" { + return errors.New("containerd socket is required") + } + if err := checkSocket(s.Socket); err != nil { + return err + } + if s.Root == "" { + return errors.New("containerd root is required") + } + if s.State == "" { + return errors.New("containerd state is required") + } + if s.ConfigFile == "" { + return errors.New("containerd config is required") + } + if s.CrunBinary == "" { + return errors.New("crun binary is required") + } + if s.ShimBinary == "" { + return errors.New("containerd shim is required") + } + if s.CNIBinDir == "" { + return errors.New("cni binary directory is required") + } + if err := checkCNIBin(s.CNIBinDir); err != nil { + return err + } + if s.CNIConfDir == "" { + return errors.New("cni config directory is required") + } + if s.Snapshotter == "" { + return errors.New("snapshotter is required") + } + return nil +} + +// WriteConfig writes the containerd config for these settings. +// crun is the CRI runtime and SystemdCgroup is enabled. +// A missing registries file leaves the hosts directory empty so containerd uses upstream endpoints. +func WriteConfig(s Settings) error { + if err := s.validate(); err != nil { + return err + } + if s.PauseImage == "" { + s.PauseImage = config.DefaultPauseImage + } + if s.RegistryDir == "" { + return errors.New("registry config directory is required") + } + auths, err := registries.Prepare(s.RegistryDir, s.RegistryFile, s.DisableDefaultEndpoint) + if err != nil { + return err + } + tree, err := toml.TreeFromMap(configMap(s, auths)) + if err != nil { + return fmt.Errorf("containerd config: %w", err) + } + var buf bytes.Buffer + if _, err := tree.WriteTo(&buf); err != nil { + return fmt.Errorf("render containerd config: %w", err) + } + if err := os.MkdirAll(filepath.Dir(s.ConfigFile), 0o755); err != nil { // #nosec G301 -- containerd root must be traversable + return fmt.Errorf("create containerd config directory: %w", err) + } + // The file can hold registry credentials. + if err := os.WriteFile(s.ConfigFile, buf.Bytes(), 0o600); err != nil { + return fmt.Errorf("write containerd config: %w", err) + } + return nil +} + +func configMap(s Settings, auths map[string]registries.Auth) map[string]any { + runtimes := map[string]any{ + RuntimeName: crunRuntime(s), + } + appendDiscoveredRuntimes(runtimes, s.ShimBinary) + return map[string]any{ + "version": 4, + "root": s.Root, + "state": s.State, + "disabled_plugins": []string{}, + "required_plugins": []string{}, + "plugins": map[string]any{ + "io.containerd.server.v1.grpc": map[string]any{ + "address": s.Socket, + "uid": os.Getuid(), + "gid": os.Getgid(), + }, + "io.containerd.server.v1.ttrpc": map[string]any{ + "address": s.Socket + ".ttrpc", + "uid": os.Getuid(), + "gid": os.Getgid(), + }, + "io.containerd.nri.v1.nri": map[string]any{ + "disable": true, + }, + "io.containerd.cri.v1.images": imagePlugin(s, auths), + "io.containerd.cri.v1.runtime": map[string]any{ + "enable_selinux": false, + "containerd": map[string]any{ + "default_runtime_name": RuntimeName, + "runtimes": runtimes, + }, + "cni": map[string]any{ + "bin_dirs": []string{s.CNIBinDir}, + "conf_dir": s.CNIConfDir, + }, + }, + "io.containerd.grpc.v1.cri": map[string]any{ + "disable_tcp_service": true, + "stream_server_address": "127.0.0.1", + "stream_server_port": "0", + }, + "io.containerd.snapshotter.v1.overlayfs": map[string]any{ + "slow_chown": false, + }, + }, + } +} + +func imagePlugin(s Settings, auths map[string]registries.Auth) map[string]any { + registry := map[string]any{ + "config_path": s.RegistryDir, + } + if len(auths) > 0 { + configs := map[string]any{} + for host, auth := range auths { + if host == "" { + continue + } + entry := map[string]any{} + if auth.Username != "" { + entry["username"] = auth.Username + } + if auth.Password != "" { + entry["password"] = auth.Password + } + if auth.Token != "" { + entry["auth"] = auth.Token + } + if len(entry) == 0 { + continue + } + configs[host] = map[string]any{"auth": entry} + } + if len(configs) > 0 { + registry["configs"] = configs + } + } + return map[string]any{ + "snapshotter": s.Snapshotter, + "disable_snapshot_annotations": true, + "pinned_images": map[string]any{ + "sandbox": s.PauseImage, + }, + "registry": registry, + } +} + +func crunRuntime(s Settings) map[string]any { + return map[string]any{ + "runtime_type": "io.containerd.runc.v2", + "runtime_path": s.ShimBinary, + "options": map[string]any{ + "BinaryName": s.CrunBinary, + "SystemdCgroup": true, + }, + } +} + +func appendDiscoveredRuntimes(runtimes map[string]any, shimBinary string) { + for _, entry := range BuildRuntimeCatalog() { + if entry.Handler == "" || entry.Path == "" || entry.Handler == RuntimeName { + continue + } + if _, exists := runtimes[entry.Handler]; exists { + continue + } + runtimes[entry.Handler] = discoveredRuntime(entry, shimBinary) + } +} + +func discoveredRuntime(entry RuntimeCatalogEntry, shimBinary string) map[string]any { + if entry.Family == RuntimeFamilyRunc { + return map[string]any{ + "runtime_type": entry.RuntimeType, + "runtime_path": shimBinary, + "options": map[string]any{ + "BinaryName": entry.Path, + "SystemdCgroup": true, + }, + } + } + return map[string]any{ + "runtime_type": entry.RuntimeType, + "runtime_path": entry.Path, + } +} diff --git a/kube/internal/containerd/config_test.go b/kube/internal/containerd/config_test.go new file mode 100644 index 0000000..6aceca4 --- /dev/null +++ b/kube/internal/containerd/config_test.go @@ -0,0 +1,418 @@ +package containerd + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "github.com/pelletier/go-toml" +) + +func TestMaybeRunChildLeavesServerAlone(t *testing.T) { + handled, err := MaybeRunChild([]string{"edgelet-kube", "server"}) + if err != nil { + t.Fatal(err) + } + if handled { + t.Fatal("server was handled as the containerd child") + } +} + +func TestWantsClient(t *testing.T) { + if WantsClient("crictl", []string{"crictl", "--data-dir", "/data"}) { + t.Fatal("data-dir alone is the recognition path") + } + if WantsClient("kubectl", []string{"kubectl", "get", "nodes"}) { + t.Fatal("kubectl is not a containerd client") + } + if !WantsClient("ctr", []string{"ctr", "version"}) { + t.Fatal("ctr version should run the client") + } + if !WantsClient("crictl", []string{"crictl", "--runtime-endpoint", "/tmp/c.sock", "version"}) { + t.Fatal("crictl version should run the client") + } +} + +func TestClientsUseSocket(t *testing.T) { + sock := filepath.Join(t.TempDir(), "containerd.sock") + got, rest, err := clientSocket([]string{"--data-dir", "/data", "--address", sock, "version"}) + if err != nil { + t.Fatal(err) + } + if got != sock { + t.Fatalf("socket %q", got) + } + if len(rest) != 1 || rest[0] != "version" { + t.Fatalf("args %#v", rest) + } + got, _, err = clientSocket([]string{"--runtime-endpoint", "unix://" + sock, "info"}) + if err != nil { + t.Fatal(err) + } + if got != sock { + t.Fatalf("socket %q", got) + } + for _, blocked := range []string{ + "/run/containerd/containerd.sock", + "/var/run/containerd/containerd.sock", + "unix:///run/containerd/containerd.sock", + } { + if _, _, err := clientSocket([]string{"--address", blocked, "version"}); err == nil { + t.Fatalf("accepted %s", blocked) + } + } +} + +func TestDefaultRuntimePaths(t *testing.T) { + settings, err := ParseChildArgs([]string{"edgelet-kube", ChildArg}) + if err != nil { + t.Fatal(err) + } + if settings.Socket != paths.ContainerdSocket { + t.Fatalf("socket %s", settings.Socket) + } + if settings.Root != paths.ContainerdRoot { + t.Fatalf("root %s", settings.Root) + } + if settings.State != paths.ContainerdState { + t.Fatalf("state %s", settings.State) + } + if settings.CNIConfDir != paths.CNIConfDir { + t.Fatalf("cni conf %s", settings.CNIConfDir) + } + if settings.Snapshotter != "overlayfs" { + t.Fatalf("snapshotter %s", settings.Snapshotter) + } + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + wantBin, err := filepath.Abs(filepath.Dir(exe)) + if err != nil { + t.Fatal(err) + } + if settings.CNIBinDir != wantBin { + t.Fatalf("cni bin %s", settings.CNIBinDir) + } + if settings.CNIBinDir == "/opt/cni/bin" || settings.Socket == "/run/containerd/containerd.sock" { + t.Fatalf("host path in %+v", settings) + } + got, rest, err := clientSocket([]string{"version"}) + if err != nil { + t.Fatal(err) + } + if got != paths.ContainerdSocket { + t.Fatalf("client socket %s", got) + } + if len(rest) != 1 || rest[0] != "version" { + t.Fatalf("args %#v", rest) + } +} + +func TestWriteConfigUsesCrun(t *testing.T) { + hideDiscoveredRuntimes(t) + dir := t.TempDir() + settings, err := ParseChildArgs([]string{ + "edgelet-kube", + ChildArg, + "--address", filepath.Join(dir, "containerd.sock"), + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + "--crun", filepath.Join(dir, "crun"), + "--shim", filepath.Join(dir, "containerd-shim-runc-v2"), + "--cni-bin-dir", filepath.Join(dir, "bin"), + "--cni-conf-dir", filepath.Join(dir, "net.d"), + }) + if err != nil { + t.Fatal(err) + } + if settings.Snapshotter != config.DefaultSnapshotter { + t.Fatalf("snapshotter %q", settings.Snapshotter) + } + if err := WriteConfig(settings); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(settings.ConfigFile) + if err != nil { + t.Fatal(err) + } + text := string(body) + for _, want := range []string{ + `default_runtime_name = "crun"`, + `runtime_type = "io.containerd.runc.v2"`, + "SystemdCgroup = true", + `snapshotter = "overlayfs"`, + settings.CrunBinary, + settings.ShimBinary, + settings.Socket, + settings.CNIBinDir, + } { + if !strings.Contains(text, want) { + t.Fatalf("config missing %q\n%s", want, text) + } + } + for _, blocked := range []string{"/opt/cni/bin", "/run/containerd/containerd.sock"} { + if strings.Contains(text, blocked) { + t.Fatalf("config contains %s\n%s", blocked, text) + } + } +} + +func TestMissingRegistriesFileUsesUpstream(t *testing.T) { + dir := t.TempDir() + settings := childSettings(t, dir) + settings.RegistryFile = filepath.Join(dir, "missing.yaml") + if err := WriteConfig(settings); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(settings.ConfigFile) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), settings.RegistryDir) { + t.Fatalf("config path missing\n%s", body) + } + entries, err := os.ReadDir(settings.RegistryDir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("hosts written for a missing file: %d", len(entries)) + } + if !strings.Contains(string(body), config.DefaultPauseImage) { + t.Fatalf("pause image missing\n%s", body) + } +} + +func TestRegistriesAndPauseImageReachContainerd(t *testing.T) { + dir := t.TempDir() + registriesFile := filepath.Join(dir, "registries.yaml") + if err := os.WriteFile(registriesFile, []byte(` +mirrors: + docker.io: + endpoint: + - https://mirror.example.com +configs: + mirror.example.com: + auth: + username: user + password: secret + auth: dXNlcjpwYXNz +`), 0o644); err != nil { + t.Fatal(err) + } + settings := childSettings(t, dir) + settings.RegistryFile = registriesFile + settings.DisableDefaultEndpoint = true + settings.PauseImage = "registry.example/docker.io/portainer/pause:latest" + if err := WriteConfig(settings); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(settings.ConfigFile) + if err != nil { + t.Fatal(err) + } + tree, err := toml.LoadBytes(body) + if err != nil { + t.Fatal(err) + } + images := tree.GetPath([]string{"plugins", "io.containerd.cri.v1.images"}) + plugin, ok := images.(*toml.Tree) + if !ok { + t.Fatalf("images plugin %#v", images) + } + if got := plugin.GetPath([]string{"registry", "config_path"}); got != settings.RegistryDir { + t.Fatalf("config_path %v", got) + } + if got := plugin.GetPath([]string{"pinned_images", "sandbox"}); got != settings.PauseImage { + t.Fatalf("sandbox %v", got) + } + auth := plugin.GetPath([]string{"registry", "configs", "mirror.example.com", "auth"}) + authTree, ok := auth.(*toml.Tree) + if !ok { + t.Fatalf("auth %#v\n%s", auth, body) + } + if authTree.Get("username") != "user" || authTree.Get("password") != "secret" || authTree.Get("auth") != "dXNlcjpwYXNz" { + t.Fatalf("auth %#v", authTree.ToMap()) + } + mirror := filepath.Join(settings.RegistryDir, "docker.io", "hosts.toml") + hosts, err := os.ReadFile(mirror) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(hosts), "registry-1.docker.io") { + t.Fatalf("upstream fallback still present\n%s", hosts) + } + if !strings.Contains(string(hosts), "https://mirror.example.com/v2") { + t.Fatalf("mirror missing\n%s", hosts) + } +} + +func childSettings(t *testing.T, dir string) Settings { + t.Helper() + hideDiscoveredRuntimes(t) + settings, err := ParseChildArgs([]string{ + "edgelet-kube", + ChildArg, + "--address", filepath.Join(dir, "containerd.sock"), + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + "--crun", filepath.Join(dir, "crun"), + "--shim", filepath.Join(dir, "containerd-shim-runc-v2"), + "--cni-bin-dir", filepath.Join(dir, "bin"), + "--cni-conf-dir", filepath.Join(dir, "net.d"), + }) + if err != nil { + t.Fatal(err) + } + return settings +} + +func TestParseChildRejectsHostPaths(t *testing.T) { + dir := t.TempDir() + _, err := ParseChildArgs([]string{ + "edgelet-kube", + ChildArg, + "--address", "/run/containerd/containerd.sock", + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + }) + if err == nil { + t.Fatal("accepted the host containerd socket") + } + _, err = ParseChildArgs([]string{ + "edgelet-kube", + ChildArg, + "--address", filepath.Join(dir, "containerd.sock"), + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + "--cni-bin-dir", "/opt/cni/bin", + }) + if err == nil { + t.Fatal("accepted the host cni directory") + } +} + +func TestWriteConfigRegistersDiscoveredRuntimes(t *testing.T) { + prev := lookPathForRuntimeCatalog + t.Cleanup(func() { lookPathForRuntimeCatalog = prev }) + lookPathForRuntimeCatalog = func(file string) (string, error) { + switch file { + case "nvidia-container-runtime": + return "/usr/bin/nvidia-container-runtime", nil + case "containerd-shim-spin-v2": + return "/usr/local/bin/containerd-shim-spin-v2", nil + default: + return "", errors.New("not found") + } + } + + dir := t.TempDir() + settings, err := ParseChildArgs([]string{ + "edgelet-kube", + ChildArg, + "--address", filepath.Join(dir, "containerd.sock"), + "--root", filepath.Join(dir, "root"), + "--state", filepath.Join(dir, "state"), + "--crun", filepath.Join(dir, "crun"), + "--shim", filepath.Join(dir, "containerd-shim-runc-v2"), + "--cni-bin-dir", filepath.Join(dir, "bin"), + "--cni-conf-dir", filepath.Join(dir, "net.d"), + }) + if err != nil { + t.Fatal(err) + } + if err := WriteConfig(settings); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(settings.ConfigFile) + if err != nil { + t.Fatal(err) + } + tree, err := toml.LoadBytes(body) + if err != nil { + t.Fatal(err) + } + plugins, ok := tree.GetPath([]string{"plugins"}).(*toml.Tree) + if !ok { + t.Fatalf("plugins %#v", tree.Get("plugins")) + } + runtimePlugin, ok := plugins.GetPath([]string{"io.containerd.cri.v1.runtime"}).(*toml.Tree) + if !ok { + t.Fatalf("runtime plugin %#v", plugins.GetPath([]string{"io.containerd.cri.v1.runtime"})) + } + containerdTree, ok := runtimePlugin.Get("containerd").(*toml.Tree) + if !ok { + t.Fatal("containerd runtime table missing") + } + if got := containerdTree.Get("default_runtime_name"); got != RuntimeName { + t.Fatalf("default runtime %v", got) + } + runtimes, ok := containerdTree.Get("runtimes").(*toml.Tree) + if !ok { + t.Fatal("runtimes table missing") + } + crunOpts := runtimeOptions(t, runtimes, "crun") + if got := crunOpts.Get("BinaryName"); got != settings.CrunBinary { + t.Fatalf("crun binary %v", got) + } + if got, ok := crunOpts.Get("SystemdCgroup").(bool); !ok || !got { + t.Fatalf("crun SystemdCgroup %v", crunOpts.Get("SystemdCgroup")) + } + nvidia, ok := runtimes.Get("nvidia").(*toml.Tree) + if !ok { + t.Fatal("nvidia runtime missing") + } + if got := nvidia.Get("runtime_path"); got != settings.ShimBinary { + t.Fatalf("nvidia shim %v", got) + } + nvidiaOpts := runtimeOptions(t, runtimes, "nvidia") + if got := nvidiaOpts.Get("BinaryName"); got != "/usr/bin/nvidia-container-runtime" { + t.Fatalf("nvidia binary %v", got) + } + if got, ok := nvidiaOpts.Get("SystemdCgroup").(bool); !ok || !got { + t.Fatalf("nvidia SystemdCgroup %v", nvidiaOpts.Get("SystemdCgroup")) + } + spin, ok := runtimes.Get("spin").(*toml.Tree) + if !ok { + t.Fatal("spin runtime missing") + } + if got := spin.Get("runtime_type"); got != "io.containerd.spin.v2" { + t.Fatalf("spin runtime type %v", got) + } + if got := spin.Get("runtime_path"); got != "/usr/local/bin/containerd-shim-spin-v2" { + t.Fatalf("spin path %v", got) + } + if spin.Get("options") != nil { + t.Fatal("spin shim should not carry runc options") + } + if runtimes.Get("wasmer") != nil { + t.Fatal("missing wasmer binary was registered") + } +} + +func runtimeOptions(t *testing.T, runtimes *toml.Tree, name string) *toml.Tree { + t.Helper() + runtime, ok := runtimes.Get(name).(*toml.Tree) + if !ok { + t.Fatalf("runtime %s missing", name) + } + options, ok := runtime.Get("options").(*toml.Tree) + if !ok { + t.Fatalf("runtime %s options missing", name) + } + return options +} + +func hideDiscoveredRuntimes(t *testing.T) { + t.Helper() + prev := lookPathForRuntimeCatalog + t.Cleanup(func() { lookPathForRuntimeCatalog = prev }) + lookPathForRuntimeCatalog = func(string) (string, error) { + return "", errors.New("not found") + } +} diff --git a/kube/internal/containerd/plugins_linux.go b/kube/internal/containerd/plugins_linux.go new file mode 100644 index 0000000..8136c35 --- /dev/null +++ b/kube/internal/containerd/plugins_linux.go @@ -0,0 +1,48 @@ +//go:build linux && cgo + +package containerd + +import ( + // Register the in-process containerd plugins: CRI, the overlay snapshotter, + // and the gRPC server. There is no standalone containerd executable. + _ "github.com/containerd/containerd/v2/core/runtime/v2" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/content/local/plugin" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/cri" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/cri/images" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/cri/runtime" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/diff/walking/plugin" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/events" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/gc" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/imageverifier" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/leases" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/metadata" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/mount" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/nri" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/restart" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/sandbox" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/server/debug" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/server/grpc" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/server/metrics" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/server/ttrpc" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/containers" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/content" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/diff" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/events" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/healthcheck" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/images" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/introspection" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/leases" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/mounts" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/namespaces" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/opt" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/sandbox" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/snapshots" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/streaming" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/tasks" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/transfer" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/version" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/services/warning" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/snapshots/overlay/plugin" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/streaming" // containerd plugin + _ "github.com/containerd/containerd/v2/plugins/transfer" // containerd plugin +) diff --git a/kube/internal/containerd/proc_linux.go b/kube/internal/containerd/proc_linux.go new file mode 100644 index 0000000..094a1bf --- /dev/null +++ b/kube/internal/containerd/proc_linux.go @@ -0,0 +1,54 @@ +//go:build linux && cgo + +package containerd + +import ( + "fmt" + "io" + "os" + "os/exec" + "syscall" + "time" +) + +// StartChild re-execs this process as the containerd child. +// args are the flags after the child switch. The caller stops the process. +func StartChild(args []string, stdout, stderr io.Writer) (*exec.Cmd, error) { + exe, err := os.Executable() + if err != nil { + return nil, fmt.Errorf("resolve executable: %w", err) + } + cmd := exec.Command(exe, append([]string{ChildArg}, args...)...) // #nosec G204 -- re-exec this binary as the containerd child + if stdout == nil { + stdout = os.Stdout + } + if stderr == nil { + stderr = os.Stderr + } + cmd.Stdout = stdout + cmd.Stderr = stderr + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start containerd: %w", err) + } + return cmd, nil +} + +// StopChild stops a process started by StartChild, including its group. +func StopChild(cmd *exec.Cmd) { + if cmd == nil || cmd.Process == nil { + return + } + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + done := make(chan struct{}) + go func() { + _, _ = cmd.Process.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + <-done + } +} diff --git a/kube/internal/containerd/runtime_catalog.go b/kube/internal/containerd/runtime_catalog.go new file mode 100644 index 0000000..463a965 --- /dev/null +++ b/kube/internal/containerd/runtime_catalog.go @@ -0,0 +1,275 @@ +package containerd + +import ( + "cmp" + "errors" + "fmt" + "os/exec" + "slices" + "strings" +) + +var lookPathForRuntimeCatalog = exec.LookPath + +var errRuntimeHandlerUnavailable = errors.New("runtime handler unavailable") + +// RuntimeFamily is how a discovered runtime is registered with CRI. +type RuntimeFamily string + +const ( + // RuntimeFamilyRunc uses the bundled shim and a BinaryName option. + RuntimeFamilyRunc RuntimeFamily = "runc" + // RuntimeFamilyShim is a runtime whose executable is the shim itself. + RuntimeFamilyShim RuntimeFamily = "shim" +) + +type runtimeSpec struct { + Handler string + RuntimeType string + Family RuntimeFamily + Candidates []string +} + +var runtimeSpecs = map[string]runtimeSpec{ + "runc": { + Handler: "runc", + RuntimeType: "io.containerd.runc.v2", + Family: RuntimeFamilyRunc, + Candidates: []string{"runc"}, + }, + "nvidia": { + Handler: "nvidia", + RuntimeType: "io.containerd.runc.v2", + Family: RuntimeFamilyRunc, + Candidates: []string{"nvidia-container-runtime"}, + }, + "nvidia-experimental": { + Handler: "nvidia-experimental", + RuntimeType: "io.containerd.runc.v2", + Family: RuntimeFamilyRunc, + Candidates: []string{"nvidia-container-runtime-experimental", "nvidia-container-runtime"}, + }, + "nvidia-cdi": { + Handler: "nvidia-cdi", + RuntimeType: "io.containerd.runc.v2", + Family: RuntimeFamilyRunc, + Candidates: []string{"nvidia-container-runtime.cdi", "nvidia-container-runtime"}, + }, + "lunatic": { + Handler: "lunatic", + RuntimeType: "io.containerd.lunatic.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-lunatic-v1", "containerd-shim-lunatic-v2", "lunatic"}, + }, + "slight": { + Handler: "slight", + RuntimeType: "io.containerd.slight.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-slight-v1", "containerd-shim-slight-v2", "slight"}, + }, + "spin": { + Handler: "spin", + RuntimeType: "io.containerd.spin.v2", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-spin-v2", "containerd-shim-spin-v1", "spin"}, + }, + "wws": { + Handler: "wws", + RuntimeType: "io.containerd.wws.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-wws-v1", "containerd-shim-wws-v2", "wws"}, + }, + "wasmedge": { + Handler: "wasmedge", + RuntimeType: "io.containerd.wasmedge.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-wasmedge-v1", "containerd-shim-wasmedge-v2", "wasmedge"}, + }, + "wasmer": { + Handler: "wasmer", + RuntimeType: "io.containerd.wasmer.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-wasmer-v1", "containerd-shim-wasmer-v2", "wasmer"}, + }, + "wasmtime": { + Handler: "wasmtime", + RuntimeType: "io.containerd.wasmtime.v1", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-wasmtime-v1", "containerd-shim-wasmtime-v2", "wasmtime"}, + }, + "edgelet-wasmtime": { + Handler: "edgelet-wasmtime", + RuntimeType: "io.containerd.edgelet.v2", + Family: RuntimeFamilyShim, + Candidates: []string{"containerd-shim-edgelet-v2", "containerd-shim-edgelet-wasm-v2", "containerd-shim-edgelet", "edgelet-wasm"}, + }, +} + +// RuntimeCatalogEntry is one runtime handler found on PATH. +type RuntimeCatalogEntry struct { + // Handler is the CRI runtime name. + Handler string + // Binary is the candidate name that resolved. + Binary string + // Path is the absolute executable path. + Path string + // RuntimeType is the containerd runtime type. + RuntimeType string + // Family selects how the handler is written into the containerd config. + Family RuntimeFamily +} + +// ErrRuntimeHandlerUnavailable indicates a requested handler is missing or not eligible. +type ErrRuntimeHandlerUnavailable struct { + Handler string + Candidates []string +} + +func (e *ErrRuntimeHandlerUnavailable) Error() string { + handler := strings.TrimSpace(strings.ToLower(e.Handler)) + candidates := append([]string{}, e.Candidates...) + if len(candidates) == 0 { + return fmt.Sprintf("%v: handler %q is not supported", errRuntimeHandlerUnavailable, handler) + } + return fmt.Sprintf("%v: handler %q is not available in PATH (tried: %s)", errRuntimeHandlerUnavailable, handler, strings.Join(candidates, ", ")) +} + +func (e *ErrRuntimeHandlerUnavailable) Unwrap() error { + return errRuntimeHandlerUnavailable +} + +// RegisteredRuntimeHandlers returns the CRI handlers written into the +// containerd config. crun is always included because it is the default +// runtime. Every other name is a catalog runtime whose binary was found. +func RegisteredRuntimeHandlers() []string { + handlers := map[string]struct{}{RuntimeName: {}} + for _, entry := range BuildRuntimeCatalog() { + if entry.Handler == "" || entry.Handler == RuntimeName { + continue + } + handlers[entry.Handler] = struct{}{} + } + return sortedHandlers(handlers) +} + +// KnownRuntimeHandlers returns every handler the catalog can register, plus crun. +// A name in this list that is not registered is removed from the API. +func KnownRuntimeHandlers() []string { + handlers := map[string]struct{}{RuntimeName: {}} + for name := range runtimeSpecs { + handlers[name] = struct{}{} + } + return sortedHandlers(handlers) +} + +func sortedHandlers(handlers map[string]struct{}) []string { + out := make([]string, 0, len(handlers)) + for name := range handlers { + out = append(out, name) + } + slices.Sort(out) + return out +} + +// BuildRuntimeCatalog discovers supported runtimes from PATH. +// Only discovered handlers are returned. +func BuildRuntimeCatalog() []RuntimeCatalogEntry { + entries := make([]RuntimeCatalogEntry, 0, len(runtimeSpecs)) + entries = findRunCContainerRuntime(entries) + entries = findNvidiaContainerRuntimes(entries) + entries = findWasiRuntimes(entries) + slices.SortFunc(entries, func(a, b RuntimeCatalogEntry) int { + return cmp.Compare(a.Handler, b.Handler) + }) + return entries +} + +// ValidateRuntimeHandlerEligibility returns a runtime entry only when handler +// exists in the catalog and was discovered. +func ValidateRuntimeHandlerEligibility(handler string, catalog []RuntimeCatalogEntry) (RuntimeCatalogEntry, error) { + normalized := strings.TrimSpace(strings.ToLower(handler)) + if _, ok := runtimeSpecs[normalized]; !ok { + return RuntimeCatalogEntry{}, &ErrRuntimeHandlerUnavailable{ + Handler: normalized, + Candidates: runtimeHandlerLookupCandidates(normalized), + } + } + entry, ok := runtimeEntryByHandler(normalized, catalog) + if !ok { + return RuntimeCatalogEntry{}, &ErrRuntimeHandlerUnavailable{ + Handler: normalized, + Candidates: runtimeHandlerLookupCandidates(normalized), + } + } + return entry, nil +} + +func runtimeEntryByHandler(handler string, catalog []RuntimeCatalogEntry) (RuntimeCatalogEntry, bool) { + for _, item := range catalog { + if item.Handler == handler { + return item, true + } + } + return RuntimeCatalogEntry{}, false +} + +func runtimeHandlerLookupCandidates(handler string) []string { + spec, ok := runtimeSpecs[handler] + if !ok { + return nil + } + return append([]string{}, spec.Candidates...) +} + +func findRunCContainerRuntime(entries []RuntimeCatalogEntry) []RuntimeCatalogEntry { + return searchForRuntimes(map[string]runtimeSpec{ + "runc": runtimeSpecs["runc"], + }, entries) +} + +func findNvidiaContainerRuntimes(entries []RuntimeCatalogEntry) []RuntimeCatalogEntry { + return searchForRuntimes(map[string]runtimeSpec{ + "nvidia": runtimeSpecs["nvidia"], + "nvidia-cdi": runtimeSpecs["nvidia-cdi"], + "nvidia-experimental": runtimeSpecs["nvidia-experimental"], + }, entries) +} + +func findWasiRuntimes(entries []RuntimeCatalogEntry) []RuntimeCatalogEntry { + return searchForRuntimes(map[string]runtimeSpec{ + "edgelet-wasmtime": runtimeSpecs["edgelet-wasmtime"], + "lunatic": runtimeSpecs["lunatic"], + "slight": runtimeSpecs["slight"], + "spin": runtimeSpecs["spin"], + "wasmedge": runtimeSpecs["wasmedge"], + "wasmer": runtimeSpecs["wasmer"], + "wasmtime": runtimeSpecs["wasmtime"], + "wws": runtimeSpecs["wws"], + }, entries) +} + +func searchForRuntimes(potential map[string]runtimeSpec, entries []RuntimeCatalogEntry) []RuntimeCatalogEntry { + handlers := make([]string, 0, len(potential)) + for runtimeName := range potential { + handlers = append(handlers, runtimeName) + } + slices.Sort(handlers) + for _, runtimeName := range handlers { + spec := potential[runtimeName] + for _, candidate := range spec.Candidates { + path, err := lookPathForRuntimeCatalog(candidate) + if err != nil { + continue + } + entries = append(entries, RuntimeCatalogEntry{ + Handler: spec.Handler, + Binary: candidate, + Path: path, + RuntimeType: spec.RuntimeType, + Family: spec.Family, + }) + break + } + } + return entries +} diff --git a/kube/internal/containerd/runtime_catalog_test.go b/kube/internal/containerd/runtime_catalog_test.go new file mode 100644 index 0000000..5b592bc --- /dev/null +++ b/kube/internal/containerd/runtime_catalog_test.go @@ -0,0 +1,136 @@ +package containerd + +import ( + "errors" + "fmt" + "slices" + "strings" + "testing" +) + +func TestBuildRuntimeCatalogOrderAndEligibility(t *testing.T) { + prev := lookPathForRuntimeCatalog + t.Cleanup(func() { lookPathForRuntimeCatalog = prev }) + + lookPathForRuntimeCatalog = func(file string) (string, error) { + switch file { + case "runc": + return "/usr/bin/runc", nil + case "containerd-shim-spin-v2": + return "/usr/local/bin/containerd-shim-spin-v2", nil + case "containerd-shim-edgelet-v2": + return "/opt/edgelet/containerd-shim-edgelet-v2", nil + default: + return "", fmt.Errorf("not found: %s", file) + } + } + + catalog := BuildRuntimeCatalog() + if len(catalog) != 3 { + t.Fatalf("expected found-only catalog entries, got %d", len(catalog)) + } + for i := 1; i < len(catalog); i++ { + if catalog[i-1].Handler > catalog[i].Handler { + t.Fatalf("catalog must be sorted by handler: %q > %q", catalog[i-1].Handler, catalog[i].Handler) + } + } + + runc, ok := runtimeEntryByHandler("runc", catalog) + if !ok || runc.Path != "/usr/bin/runc" || runc.Family != RuntimeFamilyRunc { + t.Fatalf("expected discovered runc entry, got %+v", runc) + } + if _, ok := runtimeEntryByHandler("wasmer", catalog); ok { + t.Fatal("wasmer should be absent when its binary is missing") + } + wasm, ok := runtimeEntryByHandler("edgelet-wasmtime", catalog) + if !ok || wasm.Family != RuntimeFamilyShim || wasm.RuntimeType != "io.containerd.edgelet.v2" { + t.Fatalf("expected discovered edgelet-wasmtime shim, got %+v", wasm) + } +} + +func TestBuildRuntimeCatalogUsesNvidiaExperimentalBinary(t *testing.T) { + prev := lookPathForRuntimeCatalog + t.Cleanup(func() { lookPathForRuntimeCatalog = prev }) + + lookPathForRuntimeCatalog = func(file string) (string, error) { + if file == "nvidia-container-runtime-experimental" { + return "/usr/bin/nvidia-container-runtime-experimental", nil + } + return "", errors.New("not found") + } + + catalog := BuildRuntimeCatalog() + got, ok := runtimeEntryByHandler("nvidia-experimental", catalog) + if !ok { + t.Fatal("expected nvidia-experimental entry") + } + if got.Binary != "nvidia-container-runtime-experimental" { + t.Fatalf("binary %q", got.Binary) + } +} + +func TestRegisteredRuntimeHandlersAlwaysIncludeCrun(t *testing.T) { + prev := lookPathForRuntimeCatalog + t.Cleanup(func() { lookPathForRuntimeCatalog = prev }) + lookPathForRuntimeCatalog = func(file string) (string, error) { + switch file { + case "nvidia-container-runtime.cdi": + return "/usr/bin/nvidia-container-runtime.cdi", nil + case "containerd-shim-edgelet-v2": + return "/opt/edgelet/containerd-shim-edgelet-v2", nil + default: + return "", errors.New("not found") + } + } + + got := RegisteredRuntimeHandlers() + want := []string{"crun", "edgelet-wasmtime", "nvidia-cdi"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("handlers %v", got) + } + for _, name := range []string{"wasmer", "runc", "nvidia"} { + for _, gotName := range got { + if gotName == name { + t.Fatalf("unregistered handler %s was listed", name) + } + } + } + known := KnownRuntimeHandlers() + for _, name := range []string{"crun", "runc", "nvidia-cdi", "edgelet-wasmtime", "wasmer"} { + if !slices.Contains(known, name) { + t.Fatalf("known handlers %v missing %s", known, name) + } + } +} + +func TestValidateRuntimeHandlerEligibility(t *testing.T) { + catalog := []RuntimeCatalogEntry{ + { + Handler: "spin", + Binary: "containerd-shim-spin-v2", + Path: "/usr/local/bin/containerd-shim-spin-v2", + RuntimeType: "io.containerd.spin.v2", + Family: RuntimeFamilyShim, + }, + } + if _, err := ValidateRuntimeHandlerEligibility("spin", catalog); err != nil { + t.Fatal(err) + } + + _, err := ValidateRuntimeHandlerEligibility("wasmer", catalog) + if err == nil { + t.Fatal("expected an error for wasmer") + } + var unavailable *ErrRuntimeHandlerUnavailable + if !errors.As(err, &unavailable) { + t.Fatalf("error type %T", err) + } + if !strings.Contains(err.Error(), "handler \"wasmer\" is not available in PATH") { + t.Fatalf("error %q", err) + } + + _, err = ValidateRuntimeHandlerEligibility("unknown", catalog) + if err == nil || !strings.Contains(err.Error(), "handler \"unknown\" is not supported") { + t.Fatalf("error %v", err) + } +} diff --git a/kube/internal/containerd/serve_linux.go b/kube/internal/containerd/serve_linux.go new file mode 100644 index 0000000..4e9f6af --- /dev/null +++ b/kube/internal/containerd/serve_linux.go @@ -0,0 +1,39 @@ +//go:build linux && cgo + +package containerd + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/containerd/containerd/v2/cmd/containerd/command" +) + +func serveChild(args []string) error { + settings, err := ParseChildArgs(args) + if err != nil { + return err + } + for _, dir := range []string{settings.Root, settings.State, settings.CNIConfDir, filepath.Dir(settings.Socket)} { + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- containerd and CNI traverse these directories + return fmt.Errorf("create containerd directory: %w", err) + } + } + if err := WriteConfig(settings); err != nil { + return err + } + app := command.App() + argv := []string{ + "containerd", + "--config", settings.ConfigFile, + "--address", settings.Socket, + "--root", settings.Root, + "--state", settings.State, + "--log-level", settings.LogLevel, + } + if err := app.Run(argv); err != nil { + return fmt.Errorf("containerd: %w", err) + } + return nil +} diff --git a/kube/internal/containerd/serve_stub.go b/kube/internal/containerd/serve_stub.go new file mode 100644 index 0000000..2364269 --- /dev/null +++ b/kube/internal/containerd/serve_stub.go @@ -0,0 +1,9 @@ +//go:build !linux || !cgo + +package containerd + +import "errors" + +func serveChild(_ []string) error { + return errors.New("containerd child requires linux") +} diff --git a/kube/internal/containerd/socket.go b/kube/internal/containerd/socket.go new file mode 100644 index 0000000..7e66c77 --- /dev/null +++ b/kube/internal/containerd/socket.go @@ -0,0 +1,137 @@ +// Package containerd runs containerd as a child of the fat runtime. +// crun is the CRI runtime, with SystemdCgroup enabled. +package containerd + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" +) + +const ( + // ChildArg is the re-exec switch for the process that serves containerd. + ChildArg = "--edgelet-kube-containerd-child" + + // SocketEnv is the containerd socket for ctr and crictl when the command + // line does not name one. + SocketEnv = "EDGELET_KUBE_CONTAINERD_SOCKET" +) + +// installedSocket is the containerd socket ctr and crictl use when the +// command line and SocketEnv are empty. +var installedSocket = paths.ContainerdSocket + +// WantsClient reports whether args invoke ctr or crictl with a client command. +// A data-dir flag on its own leaves the process on the recognition path. +func WantsClient(name string, args []string) bool { + if name != "ctr" && name != "crictl" { + return false + } + return hasClientArgs(args) +} + +func hasClientArgs(args []string) bool { + flag := "--" + bundle.DataDirFlag + for i := 1; i < len(args); i++ { + switch { + case args[i] == flag: + i++ + case strings.HasPrefix(args[i], flag+"="): + default: + return true + } + } + return false +} + +// clientSocket resolves the containerd socket and the arguments left for the client. +func clientSocket(args []string) (string, []string, error) { + explicit, rest, err := splitClientArgs(args) + if err != nil { + return "", nil, err + } + socket := explicit + if socket == "" { + socket = os.Getenv(SocketEnv) + } + if socket == "" { + socket = installedSocket + } + socket = socketPath(socket) + if socket == "" { + return "", nil, errors.New("containerd socket is required") + } + if err := checkSocket(socket); err != nil { + return "", nil, err + } + return socket, rest, nil +} + +func splitClientArgs(args []string) (string, []string, error) { + var explicit string + var rest []string + dataFlag := "--" + bundle.DataDirFlag + for i := 0; i < len(args); i++ { + arg := args[i] + switch { + case arg == dataFlag: + if i+1 >= len(args) || args[i+1] == "" { + return "", nil, fmt.Errorf("%s requires a path", bundle.DataDirFlag) + } + i++ + case strings.HasPrefix(arg, dataFlag+"="): + if strings.TrimPrefix(arg, dataFlag+"=") == "" { + return "", nil, fmt.Errorf("%s requires a path", bundle.DataDirFlag) + } + case arg == "--address" || arg == "--runtime-endpoint" || arg == "--image-endpoint": + if i+1 >= len(args) || args[i+1] == "" { + return "", nil, fmt.Errorf("%s requires a value", strings.TrimPrefix(arg, "--")) + } + i++ + explicit = args[i] + case strings.HasPrefix(arg, "--address="): + explicit = strings.TrimPrefix(arg, "--address=") + case strings.HasPrefix(arg, "--runtime-endpoint="): + explicit = strings.TrimPrefix(arg, "--runtime-endpoint=") + case strings.HasPrefix(arg, "--image-endpoint="): + explicit = strings.TrimPrefix(arg, "--image-endpoint=") + default: + rest = append(rest, arg) + } + } + if explicit == "" { + return "", rest, nil + } + if socketPath(explicit) == "" { + return "", nil, errors.New("containerd socket is required") + } + return explicit, rest, nil +} + +func socketPath(value string) string { + value = strings.TrimSpace(value) + value = strings.TrimPrefix(value, "unix://") + return value +} + +func checkSocket(socket string) error { + cleaned := filepath.Clean(socket) + switch cleaned { + case "/run/containerd/containerd.sock", "/var/run/containerd/containerd.sock": + return fmt.Errorf("unsupported containerd socket %s", socket) + default: + return nil + } +} + +func checkCNIBin(dir string) error { + if filepath.Clean(dir) == "/opt/cni/bin" { + return fmt.Errorf("unsupported cni binary directory %s", dir) + } + return nil +} diff --git a/kube/internal/control/addons_test.go b/kube/internal/control/addons_test.go new file mode 100644 index 0000000..2ea7182 --- /dev/null +++ b/kube/internal/control/addons_test.go @@ -0,0 +1,343 @@ +package control + +import ( + "bytes" + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strconv" + "strings" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/kubectl" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + corev1 "k8s.io/api/core/v1" + discoveryv1 "k8s.io/api/discovery/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kruntime "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/serializer" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + aggregator "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset" + metricsv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1" +) + +type clusterClients struct { + kube kubernetes.Interface + reg aggregator.Interface +} + +func assertAddons(t *testing.T, client clusterClients, srv config.Server, coredns, storage, metrics bool) { + t.Helper() + ctx := t.Context() + if coredns { + dep, err := client.kube.AppsV1().Deployments("kube-system").Get(ctx, "coredns", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if len(dep.Spec.Template.Spec.Containers) != 1 || !pinnedImage(dep.Spec.Template.Spec.Containers[0].Image, "coredns/coredns") { + t.Fatalf("coredns image %v", dep.Spec.Template.Spec.Containers) + } + cm, err := client.kube.CoreV1().ConfigMaps("kube-system").Get(ctx, "coredns", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(cm.Data["Corefile"], srv.ClusterDomain) { + t.Fatalf("corefile %s", cm.Data["Corefile"]) + } + svc, err := client.kube.CoreV1().Services("kube-system").Get(ctx, "kube-dns", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if svc.Spec.ClusterIP != srv.ClusterDNS { + t.Fatalf("cluster dns %s", svc.Spec.ClusterIP) + } + } else { + waitGone(t, func(ctx context.Context) error { + _, err := client.kube.AppsV1().Deployments("kube-system").Get(ctx, "coredns", metav1.GetOptions{}) + return err + }) + } + + if storage { + class, err := client.kube.StorageV1().StorageClasses().Get(ctx, "local-path", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if class.Provisioner != "rancher.io/local-path" || class.Annotations["storageclass.kubernetes.io/is-default-class"] != "true" { + t.Fatalf("storage class %#v", class) + } + cm, err := client.kube.CoreV1().ConfigMaps("kube-system").Get(ctx, "local-path-config", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(cm.Data["config.json"], srv.DefaultLocalStoragePath) { + t.Fatalf("storage path %s", cm.Data["config.json"]) + } + } else { + waitGone(t, func(ctx context.Context) error { + _, err := client.kube.StorageV1().StorageClasses().Get(ctx, "local-path", metav1.GetOptions{}) + return err + }) + } + + if metrics { + api, err := client.reg.ApiregistrationV1().APIServices().Get(ctx, "v1beta1.metrics.k8s.io", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if api.Spec.Group != "metrics.k8s.io" || api.Spec.Version != "v1beta1" { + t.Fatalf("metrics api %#v", api.Spec) + } + } else { + waitGone(t, func(ctx context.Context) error { + _, err := client.reg.ApiregistrationV1().APIServices().Get(ctx, "v1beta1.metrics.k8s.io", metav1.GetOptions{}) + return err + }) + } +} + +func waitGone(t *testing.T, get func(context.Context) error) { + t.Helper() + ctx := t.Context() + deadline := time.NewTimer(20 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + last = get(ctx) + if apierrors.IsNotFound(last) { + return + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + t.Fatalf("object still present: %v", last) + case <-ticker.C: + } + } +} + +func pinnedImage(got, repo string) bool { + for _, ref := range airgap.Names("") { + name, _, _ := strings.Cut(ref, "@") + image, _, _ := strings.Cut(name, ":") + if strings.HasSuffix(image, "/"+repo) && got == ref { + return true + } + } + return false +} + +func assertMetricsTop(t *testing.T, client clusterClients, kubeconfig string) { + t.Helper() + ctx := t.Context() + const node = "edge-a" + if _, err := client.kube.CoreV1().Nodes().Create(ctx, &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: node}}, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + server, address := metricsServer(t, node) + t.Cleanup(server.Close) + parsed, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(parsed.Port()) + if err != nil { + t.Fatal(err) + } + ready := true + number := int32(port) + name := "https" + protocol := corev1.ProtocolTCP + if _, err := client.kube.DiscoveryV1().EndpointSlices("kube-system").Create(ctx, &discoveryv1.EndpointSlice{ + ObjectMeta: metav1.ObjectMeta{ + Name: "metrics-server-local", + Namespace: "kube-system", + Labels: map[string]string{discoveryv1.LabelServiceName: "metrics-server"}, + }, + AddressType: discoveryv1.AddressTypeIPv4, + Endpoints: []discoveryv1.Endpoint{{ + Addresses: []string{address}, + Conditions: discoveryv1.EndpointConditions{Ready: &ready}, + }}, + Ports: []discoveryv1.EndpointPort{{ + Name: &name, + Port: &number, + Protocol: &protocol, + }}, + }, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + waitMetricsAvailable(t, client) + + t.Setenv("KUBECONFIG", kubeconfig) + stdout := os.Stdout + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stdout = writer + err = kubectl.Run([]string{"top", "nodes"}) + _ = writer.Close() + os.Stdout = stdout + var buf bytes.Buffer + _, _ = io.Copy(&buf, reader) + _ = reader.Close() + if err != nil { + t.Fatalf("kubectl top: %v\n%s", err, buf.String()) + } + if !strings.Contains(buf.String(), node) { + t.Fatalf("kubectl top output %s", buf.String()) + } +} + +func waitMetricsAvailable(t *testing.T, client clusterClients) { + t.Helper() + ctx := t.Context() + deadline := time.NewTimer(90 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + var last string + for { + api, err := client.reg.ApiregistrationV1().APIServices().Get(ctx, "v1beta1.metrics.k8s.io", metav1.GetOptions{}) + if err != nil { + last = err.Error() + } else { + last = "waiting" + for _, cond := range api.Status.Conditions { + if cond.Type == "Available" { + last = string(cond.Reason) + ": " + cond.Message + if cond.Status == "True" { + return + } + } + } + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + t.Fatalf("metrics api: %s", last) + case <-ticker.C: + } + } +} + +func metricsServer(t *testing.T, node string) (*httptest.Server, string) { + t.Helper() + scheme := kruntime.NewScheme() + if err := metricsv1beta1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + codecs := serializer.NewCodecFactory(scheme) + list := &metricsv1beta1.NodeMetricsList{ + Items: []metricsv1beta1.NodeMetrics{{ + ObjectMeta: metav1.ObjectMeta{Name: node}, + Timestamp: metav1.Now(), + Window: metav1.Duration{Duration: 15 * time.Second}, + Usage: corev1.ResourceList{ + corev1.ResourceCPU: resource.MustParse("10m"), + corev1.ResourceMemory: resource.MustParse("10Mi"), + }, + }}, + } + address := outboundIPv4(t) + listener, err := net.Listen("tcp", net.JoinHostPort(address, "0")) + if err != nil { + t.Fatal(err) + } + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimSuffix(r.URL.Path, "/") + if path != "/apis/metrics.k8s.io/v1beta1/nodes" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"kind":"APIResourceList","apiVersion":"v1","groupVersion":"metrics.k8s.io/v1beta1","resources":[{"name":"nodes","singularName":"","namespaced":false,"kind":"NodeMetrics","verbs":["get","list"]}]}`)) + return + } + info := serializerFor(r.Header.Get("Accept"), codecs.SupportedMediaTypes()) + w.Header().Set("Content-Type", info.MediaType) + encoded := info.Serializer + if encoded == nil && info.StreamSerializer != nil { + encoded = info.StreamSerializer.Serializer + } + if encoded == nil { + http.Error(w, "no serializer", http.StatusNotAcceptable) + return + } + if err := codecs.EncoderForVersion(encoded, metricsv1beta1.SchemeGroupVersion).Encode(list, w); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + })) + previous := server.Listener + server.Listener = listener + _ = previous.Close() + server.StartTLS() + return server, address +} + +func outboundIPv4(t *testing.T) string { + t.Helper() + conn, err := net.Dial("udp", "8.8.8.8:80") + if err != nil { + t.Fatal(err) + } + defer conn.Close() + host, _, err := net.SplitHostPort(conn.LocalAddr().String()) + if err != nil { + t.Fatal(err) + } + if host == "" || host == "127.0.0.1" { + t.Fatal("no routable address for the metrics service") + } + return host +} + +func serializerFor(accept string, types []kruntime.SerializerInfo) kruntime.SerializerInfo { + for _, part := range strings.Split(accept, ",") { + media := strings.TrimSpace(part) + if cut, _, ok := strings.Cut(media, ";"); ok { + media = strings.TrimSpace(cut) + } + if media == "" || media == "*/*" { + continue + } + if info, ok := kruntime.SerializerInfoForMediaType(types, media); ok { + return info + } + } + for _, info := range types { + if info.MediaType == "application/json" { + return info + } + } + return types[0] +} + +func kubeClient(t *testing.T, kubeconfig string) clusterClients { + t.Helper() + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + t.Fatal(err) + } + kube, err := kubernetes.NewForConfig(cfg) + if err != nil { + t.Fatal(err) + } + reg, err := aggregator.NewForConfig(cfg) + if err != nil { + t.Fatal(err) + } + return clusterClients{kube: kube, reg: reg} +} diff --git a/kube/internal/control/args.go b/kube/internal/control/args.go new file mode 100644 index 0000000..51cf6da --- /dev/null +++ b/kube/internal/control/args.go @@ -0,0 +1,353 @@ +package control + +import ( + "errors" + "fmt" + "net" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "github.com/eclipse-iofog/edgelet-kube/internal/version" +) + +func init() { + version.Pin() +} + +func apiServerArgs(srv config.Server, endpoint, advertise, encryptionFile string, paths certPaths) []string { + issuer := "https://kubernetes.default.svc." + srv.ClusterDomain + values := map[string]string{ + "etcd-servers": endpoint, + "storage-backend": "etcd3", + "allow-privileged": "true", + "authorization-mode": "Node,RBAC", + "anonymous-auth": "false", + "service-account-signing-key-file": paths.ServiceAccountKey, + "service-account-key-file": paths.ServiceAccountCert, + "service-account-issuer": issuer, + "api-audiences": issuer, + "service-cluster-ip-range": srv.ServiceCIDR, + "service-node-port-range": srv.ServiceNodePortRange, + "secure-port": strconv.Itoa(srv.HTTPSListenPort), + "bind-address": srv.BindAddress, + "tls-cert-file": paths.ServingCert, + "tls-private-key-file": paths.ServingKey, + "client-ca-file": paths.CACert, + "kubelet-certificate-authority": paths.CACert, + "requestheader-client-ca-file": paths.FrontProxyCA, + "requestheader-allowed-names": "front-proxy-client", + "proxy-client-cert-file": paths.FrontProxyCert, + "proxy-client-key-file": paths.FrontProxyKey, + "requestheader-extra-headers-prefix": "X-Remote-Extra-", + "requestheader-group-headers": "X-Remote-Group", + "requestheader-username-headers": "X-Remote-User", + "enable-aggregator-routing": "true", + "enable-admission-plugins": "NodeRestriction", + "profiling": "false", + "cert-dir": paths.Dir, + } + if paths.APIServerCert != "" && paths.APIServerKey != "" { + values["kubelet-client-certificate"] = paths.APIServerCert + values["kubelet-client-key"] = paths.APIServerKey + } + if advertise != "" { + values["advertise-address"] = advertise + } + if encryptionFile != "" { + values["encryption-provider-config"] = encryptionFile + } + if srv.DatastoreCAFile != "" { + values["etcd-cafile"] = srv.DatastoreCAFile + } + if srv.DatastoreCertFile != "" { + values["etcd-certfile"] = srv.DatastoreCertFile + } + if srv.DatastoreKeyFile != "" { + values["etcd-keyfile"] = srv.DatastoreKeyFile + } + if srv.V != 0 { + values["v"] = strconv.Itoa(srv.V) + } + if srv.VModule != "" { + values["vmodule"] = srv.VModule + } + return flagArgs(values, srv.KubeAPIServerArg) +} + +func controllerManagerArgs(srv config.Server, leader bool, port int, paths certPaths) ([]string, error) { + mask, err := prefixSize(srv.NodePodCIDR) + if err != nil { + return nil, err + } + values := map[string]string{ + "kubeconfig": paths.ControllerKubeconfig, + "authorization-kubeconfig": paths.ControllerKubeconfig, + "authentication-kubeconfig": paths.ControllerKubeconfig, + "service-account-private-key-file": paths.ServiceAccountKey, + "allocate-node-cidrs": "true", + "cluster-cidr": srv.ClusterCIDR, + "node-cidr-mask-size": mask, + "service-cluster-ip-range": srv.ServiceCIDR, + "root-ca-file": paths.CACert, + "cluster-signing-cert-file": paths.CACert, + "cluster-signing-key-file": paths.CAKey, + "use-service-account-credentials": "true", + "leader-elect": strconv.FormatBool(leader), + "bind-address": "127.0.0.1", + "secure-port": strconv.Itoa(port), + "tls-cert-file": paths.ServingCert, + "tls-private-key-file": paths.ServingKey, + "cert-dir": paths.Dir, + "profiling": "false", + "controllers": "*,tokencleaner", + } + if srv.V != 0 { + values["v"] = strconv.Itoa(srv.V) + } + if srv.VModule != "" { + values["vmodule"] = srv.VModule + } + return flagArgs(values, srv.KubeControllerManagerArg), nil +} + +func schedulerArgs(srv config.Server, leader bool, port int, paths certPaths) []string { + values := map[string]string{ + "kubeconfig": paths.SchedulerKubeconfig, + "authorization-kubeconfig": paths.SchedulerKubeconfig, + "authentication-kubeconfig": paths.SchedulerKubeconfig, + "leader-elect": strconv.FormatBool(leader), + "bind-address": "127.0.0.1", + "secure-port": strconv.Itoa(port), + "tls-cert-file": paths.ServingCert, + "tls-private-key-file": paths.ServingKey, + "cert-dir": paths.Dir, + "profiling": "false", + } + if srv.V != 0 { + values["v"] = strconv.Itoa(srv.V) + } + if srv.VModule != "" { + values["vmodule"] = srv.VModule + } + return flagArgs(values, srv.KubeSchedulerArg) +} + +func kubeletArgs(srv config.Server, nodeIP string, certs certPaths, cniConfDir, cniBinDir string) ([]string, error) { + confDir, binDir, err := cniDirs(cniConfDir, cniBinDir) + if err != nil { + return nil, err + } + name, err := nodeName(srv) + if err != nil { + return nil, err + } + dataDir := srv.DataDir + if dataDir == "" { + dataDir = bundle.DefaultDataDir + } + root := filepath.Join(dataDir, "agent", "kubelet") + values := map[string]string{ + "kubeconfig": certs.KubeletKubeconfig, + "container-runtime-endpoint": runtimeEndpoint(), + "hostname-override": name, + "node-ip": nodeIP, + "cluster-dns": srv.ClusterDNS, + "cluster-domain": srv.ClusterDomain, + "root-dir": root, + "cert-dir": filepath.Join(root, "pki"), + "read-only-port": "0", + "register-node": "true", + } + resolv := srv.ResolvConf + if resolv == "" { + resolv = hostResolvConf("") + } + if resolv != "" { + values["resolv-conf"] = resolv + } + if certs.KubeletServingCert != "" && certs.KubeletServingKey != "" { + values["tls-cert-file"] = certs.KubeletServingCert + values["tls-private-key-file"] = certs.KubeletServingKey + } + if certs.CACert != "" { + values["client-ca-file"] = certs.CACert + } + if len(srv.NodeLabel) > 0 { + values["node-labels"] = strings.Join(srv.NodeLabel, ",") + } + if len(srv.NodeTaint) > 0 { + values["register-with-taints"] = strings.Join(srv.NodeTaint, ",") + } + if srv.V != 0 { + values["v"] = strconv.Itoa(srv.V) + } + if srv.VModule != "" { + values["vmodule"] = srv.VModule + } + for _, arg := range (paths.Layout{CNIConfDir: confDir, CNIBinDir: binDir}).KubeletCNIArgs() { + key, value := splitArg(arg) + values[key] = value + } + pauseKey, pauseValue := splitArg(srv.KubeletPauseArg()) + values[pauseKey] = pauseValue + // The cgroup driver is systemd, matching crun. + // protect-kernel-defaults is passed when that setting is enabled. + extra, err := kubeletExtra(srv.KubeletArg) + if err != nil { + return nil, err + } + values["cgroup-driver"] = "systemd" + if srv.ProtectKernelDefaults { + values["protect-kernel-defaults"] = "true" + } + return flagArgs(values, extra), nil +} + +// kubeletExtra drops arguments that would select another cgroup driver or +// override protect-kernel-defaults. The server setting decides that flag. +func kubeletExtra(extra []string) ([]string, error) { + if len(extra) == 0 { + return nil, nil + } + kept := make([]string, 0, len(extra)) + for _, raw := range extra { + key, value := splitArg(raw) + switch key { + case "cgroup-driver": + if value != "systemd" { + return nil, errors.New("kubelet cgroup driver is systemd") + } + case "protect-kernel-defaults": + default: + kept = append(kept, raw) + } + } + return kept, nil +} + +func kubeProxyArgs(srv config.Server, nodeIP string, certs certPaths) ([]string, error) { + name, err := nodeName(srv) + if err != nil { + return nil, err + } + values := map[string]string{ + "proxy-mode": "iptables", + "kubeconfig": certs.KubeProxyKubeconfig, + "cluster-cidr": srv.ClusterCIDR, + "hostname-override": name, + "bind-address": nodeIP, + "healthz-bind-address": "127.0.0.1:10256", + "profiling": "false", + } + if srv.V != 0 { + values["v"] = strconv.Itoa(srv.V) + } + if srv.VModule != "" { + values["vmodule"] = srv.VModule + } + return flagArgs(values, srv.KubeProxyArg), nil +} + +func cniDirs(confDir, binDir string) (string, string, error) { + if confDir == "" { + confDir = paths.CNIConfDir + } + if binDir == "" { + exe, err := os.Executable() + if err != nil { + return "", "", fmt.Errorf("resolve executable: %w", err) + } + binDir = filepath.Dir(exe) + } + if filepath.Clean(binDir) == "/opt/cni/bin" { + return "", "", fmt.Errorf("unsupported cni binary directory %s", binDir) + } + return confDir, binDir, nil +} + +func runtimeEndpoint() string { + socket := paths.ContainerdSocket + if strings.HasPrefix(socket, "unix://") { + return socket + } + return "unix://" + socket +} + +func flagValue(args []string, name string) string { + prefix := "--" + name + "=" + for _, arg := range args { + if value, ok := strings.CutPrefix(arg, prefix); ok { + return value + } + } + return "" +} + +func prefixSize(cidr string) (string, error) { + _, network, err := net.ParseCIDR(cidr) + if err != nil { + return "", fmt.Errorf("node pod network %q is not a network", cidr) + } + ones, _ := network.Mask.Size() + return strconv.Itoa(ones), nil +} + +func flagArgs(values map[string]string, extra []string) []string { + merged := make(map[string]string, len(values)+len(extra)) + for key, value := range values { + merged[key] = value + } + for _, raw := range extra { + key, value := splitArg(raw) + if key == "" { + continue + } + merged[key] = value + } + keys := make([]string, 0, len(merged)) + for key := range merged { + keys = append(keys, key) + } + slices.Sort(keys) + args := make([]string, 0, len(keys)) + for _, key := range keys { + args = append(args, "--"+key+"="+merged[key]) + } + return args +} + +func splitArg(raw string) (string, string) { + raw = strings.TrimLeft(raw, "-") + key, value, ok := strings.Cut(raw, "=") + if key == "" { + return "", "" + } + if !ok { + return key, "true" + } + return key, value +} + +func componentPorts(api, controller, scheduler int) (int, int) { + if controller == 0 { + if api == config.DefaultHTTPSListenPort { + controller = 10257 + } else { + controller = api + 1 + } + } + if scheduler == 0 { + if api == config.DefaultHTTPSListenPort { + scheduler = 10259 + } else { + scheduler = api + 2 + } + } + return controller, scheduler +} diff --git a/kube/internal/control/certs.go b/kube/internal/control/certs.go new file mode 100644 index 0000000..1445b48 --- /dev/null +++ b/kube/internal/control/certs.go @@ -0,0 +1,455 @@ +package control + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/pem" + "fmt" + "math/big" + "net" + "os" + "path/filepath" + "strconv" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/config" +) + +// certPaths are the TLS files the API processes read. +// The directory is kept across restarts. +type certPaths struct { + Dir string + CACert string + CAKey string + ServingCert string + ServingKey string + ServiceAccountCert string + ServiceAccountKey string + FrontProxyCA string + FrontProxyCAKey string + FrontProxyCert string + FrontProxyKey string + AdminCert string + AdminKey string + AdminKubeconfig string + ControllerCert string + ControllerKey string + ControllerKubeconfig string + SchedulerCert string + SchedulerKey string + SchedulerKubeconfig string + KubeletCert string + KubeletKey string + KubeletServingCert string + KubeletServingKey string + KubeletKubeconfig string + APIServerCert string + APIServerKey string + KubeProxyCert string + KubeProxyKey string + KubeProxyKubeconfig string +} + +// tlsDir is the directory that holds the CA, the serving certificate, +// and the client certificates. +func tlsDir(dataDir string) string { + if dataDir == "" { + dataDir = bundle.DefaultDataDir + } + return filepath.Join(dataDir, "server", "tls") +} + +func ensureCerts(srv config.Server) (certPaths, error) { + dir := tlsDir(srv.DataDir) + if err := os.MkdirAll(dir, 0o700); err != nil { + return certPaths{}, fmt.Errorf("create certificate directory: %w", err) + } + if err := os.Chmod(dir, 0o700); err != nil { // #nosec G302 -- directory must be owner-traversable + return certPaths{}, fmt.Errorf("create certificate directory: %w", err) + } + admin := srv.WriteKubeconfig + if admin == "" { + admin = config.DefaultKubeconfig + } + paths := certPathsFor(dir, admin) + mode, err := fileMode(srv.WriteKubeconfigMode) + if err != nil { + return certPaths{}, err + } + + caCert, caKey, err := ensurePair(paths.CACert, paths.CAKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return newCA("edgelet-kube-ca") + }) + if err != nil { + return certPaths{}, err + } + if !caCert.IsCA { + return certPaths{}, fmt.Errorf("certificate %s is not a CA", paths.CACert) + } + if _, _, err := ensurePair(paths.ServingCert, paths.ServingKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + tmpl, err := servingCertificate(srv) + if err != nil { + return nil, nil, err + } + return sign(caCert, caKey, tmpl) + }); err != nil { + return certPaths{}, err + } + if _, _, err := ensurePair(paths.KubeletServingCert, paths.KubeletServingKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + tmpl, err := kubeletServingCertificate(srv) + if err != nil { + return nil, nil, err + } + return sign(caCert, caKey, tmpl) + }); err != nil { + return certPaths{}, err + } + if _, _, err := ensurePair(paths.APIServerCert, paths.APIServerKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return sign(caCert, caKey, clientTemplate("system:apiserver", []string{"system:masters"})) + }); err != nil { + return certPaths{}, err + } + if _, _, err := ensurePair(paths.ServiceAccountCert, paths.ServiceAccountKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return sign(caCert, caKey, &x509.Certificate{ + Subject: pkix.Name{CommonName: "edgelet-kube-service-account"}, + KeyUsage: x509.KeyUsageDigitalSignature, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + }) + }); err != nil { + return certPaths{}, err + } + + proxyCA, proxyKey, err := ensurePair(paths.FrontProxyCA, paths.FrontProxyCAKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return newCA("front-proxy-ca") + }) + if err != nil { + return certPaths{}, err + } + if !proxyCA.IsCA { + return certPaths{}, fmt.Errorf("certificate %s is not a CA", paths.FrontProxyCA) + } + if _, _, err := ensurePair(paths.FrontProxyCert, paths.FrontProxyKey, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return sign(proxyCA, proxyKey, clientTemplate("front-proxy-client", nil)) + }); err != nil { + return certPaths{}, err + } + + server := serverURL(srv) + name, err := nodeName(srv) + if err != nil { + return certPaths{}, err + } + clients := []struct { + cert, key, kubeconfig, cn string + org []string + mode os.FileMode + }{ + {paths.AdminCert, paths.AdminKey, paths.AdminKubeconfig, "system:admin", []string{"system:masters"}, mode}, + {paths.ControllerCert, paths.ControllerKey, paths.ControllerKubeconfig, "system:kube-controller-manager", []string{"system:kube-controller-manager"}, 0o600}, + {paths.SchedulerCert, paths.SchedulerKey, paths.SchedulerKubeconfig, "system:kube-scheduler", []string{"system:kube-scheduler"}, 0o600}, + {paths.KubeletCert, paths.KubeletKey, paths.KubeletKubeconfig, fmt.Sprintf("system:node:%s", name), []string{"system:nodes"}, 0o600}, + {paths.KubeProxyCert, paths.KubeProxyKey, paths.KubeProxyKubeconfig, "system:kube-proxy", []string{"system:node-proxier"}, 0o600}, + } + for _, client := range clients { + if err := ensureClient(caCert, caKey, client.cert, client.key, client.kubeconfig, server, client.cn, client.org, client.mode); err != nil { + return certPaths{}, err + } + } + return paths, nil +} + +func certPathsFor(dir, admin string) certPaths { + return certPaths{ + Dir: dir, + CACert: filepath.Join(dir, "ca.crt"), + CAKey: filepath.Join(dir, "ca.key"), + ServingCert: filepath.Join(dir, "serving.crt"), + ServingKey: filepath.Join(dir, "serving.key"), + ServiceAccountCert: filepath.Join(dir, "service-account.crt"), + ServiceAccountKey: filepath.Join(dir, "service-account.key"), + FrontProxyCA: filepath.Join(dir, "front-proxy-ca.crt"), + FrontProxyCAKey: filepath.Join(dir, "front-proxy-ca.key"), + FrontProxyCert: filepath.Join(dir, "front-proxy-client.crt"), + FrontProxyKey: filepath.Join(dir, "front-proxy-client.key"), + AdminCert: filepath.Join(dir, "client-admin.crt"), + AdminKey: filepath.Join(dir, "client-admin.key"), + AdminKubeconfig: admin, + ControllerCert: filepath.Join(dir, "client-controller-manager.crt"), + ControllerKey: filepath.Join(dir, "client-controller-manager.key"), + ControllerKubeconfig: filepath.Join(dir, "controller-manager.kubeconfig"), + SchedulerCert: filepath.Join(dir, "client-scheduler.crt"), + SchedulerKey: filepath.Join(dir, "client-scheduler.key"), + SchedulerKubeconfig: filepath.Join(dir, "scheduler.kubeconfig"), + KubeletCert: filepath.Join(dir, "client-kubelet.crt"), + KubeletKey: filepath.Join(dir, "client-kubelet.key"), + KubeletServingCert: filepath.Join(dir, "kubelet-serving.crt"), + KubeletServingKey: filepath.Join(dir, "kubelet-serving.key"), + KubeletKubeconfig: filepath.Join(dir, "kubelet.kubeconfig"), + APIServerCert: filepath.Join(dir, "client-kube-apiserver.crt"), + APIServerKey: filepath.Join(dir, "client-kube-apiserver.key"), + KubeProxyCert: filepath.Join(dir, "client-kube-proxy.crt"), + KubeProxyKey: filepath.Join(dir, "client-kube-proxy.key"), + KubeProxyKubeconfig: filepath.Join(dir, "kube-proxy.kubeconfig"), + } +} + +func ensureClient(ca *x509.Certificate, caKey *ecdsa.PrivateKey, certPath, keyPath, kubeconfig, server, cn string, org []string, mode os.FileMode) error { + cert, key, err := ensurePair(certPath, keyPath, func() (*x509.Certificate, *ecdsa.PrivateKey, error) { + return sign(ca, caKey, clientTemplate(cn, org)) + }) + if err != nil { + return err + } + return writeKubeconfig(kubeconfig, ca, cert, key, server, mode) +} + +func ensurePair(certPath, keyPath string, issue func() (*x509.Certificate, *ecdsa.PrivateKey, error)) (*x509.Certificate, *ecdsa.PrivateKey, error) { + certThere, err := fileThere(certPath) + if err != nil { + return nil, nil, err + } + keyThere, err := fileThere(keyPath) + if err != nil { + return nil, nil, err + } + if certThere && keyThere { + return loadPair(certPath, keyPath) + } + if certThere || keyThere { + return nil, nil, fmt.Errorf("incomplete certificate pair %s", certPath) + } + cert, key, err := issue() + if err != nil { + return nil, nil, err + } + if err := writePair(certPath, keyPath, cert, key); err != nil { + _ = os.Remove(certPath) + _ = os.Remove(keyPath) + return nil, nil, err + } + return cert, key, nil +} + +func fileThere(path string) (bool, error) { + info, err := os.Stat(path) + if err == nil { + if info.IsDir() { + return false, fmt.Errorf("%s is a directory", path) + } + return true, nil + } + if os.IsNotExist(err) { + return false, nil + } + return false, err +} + +// serverURL is the address stored in kubeconfigs. Clients on this node use +// the listen address. +func serverURL(srv config.Server) string { + port := srv.HTTPSListenPort + if port == 0 { + port = config.DefaultHTTPSListenPort + } + return "https://" + net.JoinHostPort(apiHost(srv.BindAddress), strconv.Itoa(port)) +} + +func fileMode(raw string) (os.FileMode, error) { + if raw == "" { + raw = config.DefaultKubeconfigMode + } + parsed, err := strconv.ParseUint(raw, 8, 32) + if err != nil || parsed > 0o777 { + return 0, fmt.Errorf("write-kubeconfig-mode %q is not a file mode", raw) + } + return os.FileMode(parsed), nil +} + +func writeKubeconfig(path string, ca, cert *x509.Certificate, key *ecdsa.PrivateKey, server string, mode os.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { // #nosec G301 -- kubeconfig parent must be traversable + return fmt.Errorf("create kubeconfig directory: %w", err) + } + caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.Raw}) + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + return err + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) + body := fmt.Sprintf(`apiVersion: v1 +kind: Config +clusters: +- cluster: + certificate-authority-data: %s + server: %s + name: default +contexts: +- context: + cluster: default + user: default + name: default +current-context: default +users: +- name: default + user: + client-certificate-data: %s + client-key-data: %s +`, base64.StdEncoding.EncodeToString(caPEM), server, base64.StdEncoding.EncodeToString(certPEM), base64.StdEncoding.EncodeToString(keyPEM)) + if err := os.WriteFile(path, []byte(body), mode); err != nil { + return fmt.Errorf("write kubeconfig %s: %w", path, err) + } + if err := os.Chmod(path, mode); err != nil { + return fmt.Errorf("write kubeconfig %s: %w", path, err) + } + return nil +} + +func apiHost(bind string) string { + switch bind { + case "", "0.0.0.0", "::": + return "127.0.0.1" + default: + return bind + } +} + +func clientTemplate(cn string, org []string) *x509.Certificate { + return &x509.Certificate{ + Subject: pkix.Name{CommonName: cn, Organization: org}, + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + } +} + +func newCA(cn string) (*x509.Certificate, *ecdsa.PrivateKey, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + return nil, nil, err + } + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + IsCA: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, key.Public(), key) + if err != nil { + return nil, nil, err + } + cert, err := x509.ParseCertificate(der) + if err != nil { + return nil, nil, err + } + return cert, key, nil +} + +func sign(ca *x509.Certificate, caKey *ecdsa.PrivateKey, tmpl *x509.Certificate) (*x509.Certificate, *ecdsa.PrivateKey, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + if err != nil { + return nil, nil, err + } + tmpl.SerialNumber = serial + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, key.Public(), caKey) + if err != nil { + return nil, nil, err + } + cert, err := x509.ParseCertificate(der) + if err != nil { + return nil, nil, err + } + return cert, key, nil +} + +func loadPair(certPath, keyPath string) (*x509.Certificate, *ecdsa.PrivateKey, error) { + cert, err := loadCert(certPath) + if err != nil { + return nil, nil, err + } + key, err := loadKey(keyPath) + if err != nil { + return nil, nil, err + } + pub, ok := cert.PublicKey.(*ecdsa.PublicKey) + if !ok || !pub.Equal(&key.PublicKey) { + return nil, nil, fmt.Errorf("certificate %s does not match %s", certPath, keyPath) + } + return cert, key, nil +} + +func loadCert(path string) (*x509.Certificate, error) { + body, err := os.ReadFile(path) // #nosec G304 -- path is a certificate under the server tls directory + if err != nil { + return nil, fmt.Errorf("read certificate %s: %w", path, err) + } + block, _ := pem.Decode(body) + if block == nil || block.Type != "CERTIFICATE" { + return nil, fmt.Errorf("certificate %s is not PEM", path) + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return nil, fmt.Errorf("parse certificate %s: %w", path, err) + } + return cert, nil +} + +func loadKey(path string) (*ecdsa.PrivateKey, error) { + body, err := os.ReadFile(path) // #nosec G304 -- path is a key under the server tls directory + if err != nil { + return nil, fmt.Errorf("read key %s: %w", path, err) + } + block, _ := pem.Decode(body) + if block == nil { + return nil, fmt.Errorf("key %s is not PEM", path) + } + key, err := x509.ParseECPrivateKey(block.Bytes) + if err != nil { + return nil, fmt.Errorf("parse key %s: %w", path, err) + } + return key, nil +} + +func writePair(certPath, keyPath string, cert *x509.Certificate, key *ecdsa.PrivateKey) error { + if err := writeCert(certPath, cert); err != nil { + return err + } + return writeKey(keyPath, key) +} + +func writeCert(path string, cert *x509.Certificate) error { + body := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) + if err := os.WriteFile(path, body, 0o644); err != nil { // #nosec G306 -- certificate PEM is not a private key + return fmt.Errorf("write certificate %s: %w", path, err) + } + return nil +} + +func writeKey(path string, key *ecdsa.PrivateKey) error { + der, err := x509.MarshalECPrivateKey(key) + if err != nil { + return err + } + body := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: der}) + if err := os.WriteFile(path, body, 0o600); err != nil { + return fmt.Errorf("write key %s: %w", path, err) + } + return nil +} diff --git a/kube/internal/control/certs_test.go b/kube/internal/control/certs_test.go new file mode 100644 index 0000000..5935c48 --- /dev/null +++ b/kube/internal/control/certs_test.go @@ -0,0 +1,357 @@ +package control + +import ( + "bytes" + "crypto/x509" + "encoding/pem" + "net" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + "k8s.io/client-go/tools/clientcmd" +) + +func TestDefaultTLSDirectory(t *testing.T) { + if got := tlsDir(""); got != "/var/lib/edgelet-kube/server/tls" { + t.Fatalf("%s", got) + } +} + +func TestRestartReusesCertificates(t *testing.T) { + srv := testServer(t) + srv.TLSSan = []string{"san.example.test"} + srv.TLSSanSecurity = true + first, err := ensureCerts(srv) + if err != nil { + t.Fatal(err) + } + info, err := os.Stat(first.Dir) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o700 { + t.Fatalf("directory mode %o", info.Mode().Perm()) + } + marker := filepath.Join(first.Dir, "keep") + if err := os.WriteFile(marker, []byte("keep"), 0o600); err != nil { + t.Fatal(err) + } + ca := mustRead(t, first.CACert) + serving := mustRead(t, first.ServingCert) + adminCert := mustRead(t, first.AdminCert) + front := mustRead(t, first.FrontProxyCert) + kubelet := mustRead(t, first.KubeletCert) + kubeletServing := mustRead(t, first.KubeletServingCert) + apiServer := mustRead(t, first.APIServerCert) + proxy := mustRead(t, first.KubeProxyCert) + + srv.TLSSan = []string{"other.example.test"} + srv.TLSSanSecurity = false + second, err := ensureCerts(srv) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(marker); err != nil { + t.Fatal(err) + } + for _, pair := range []struct { + name string + path string + want []byte + }{ + {"ca", second.CACert, ca}, + {"serving", second.ServingCert, serving}, + {"admin", second.AdminCert, adminCert}, + {"front-proxy", second.FrontProxyCert, front}, + {"kubelet", second.KubeletCert, kubelet}, + {"kubelet-serving", second.KubeletServingCert, kubeletServing}, + {"apiserver", second.APIServerCert, apiServer}, + {"kube-proxy", second.KubeProxyCert, proxy}, + } { + if got := mustRead(t, pair.path); !bytes.Equal(got, pair.want) { + t.Fatalf("%s changed", pair.name) + } + } + assertAdmin(t, second.AdminKubeconfig) + if masters := mastersCount(t, second.Dir); masters != 2 { + t.Fatalf("privileged principals %d", masters) + } + kubeletCert := mustCert(t, second.KubeletCert) + if kubeletCert.Subject.CommonName != "system:node:node-a" { + t.Fatalf("kubelet %s", kubeletCert.Subject.CommonName) + } + if !sameOrg(kubeletCert, "system:nodes") { + t.Fatalf("kubelet org %v", kubeletCert.Subject.Organization) + } + proxyCert := mustCert(t, second.KubeProxyCert) + if proxyCert.Subject.CommonName != "system:kube-proxy" || !sameOrg(proxyCert, "system:node-proxier") { + t.Fatalf("kube-proxy %s %v", proxyCert.Subject.CommonName, proxyCert.Subject.Organization) + } + if got := mustCert(t, second.FrontProxyCert); got.Subject.CommonName != "front-proxy-client" { + t.Fatalf("front-proxy %s", got.Subject.CommonName) + } +} + +func TestServingNames(t *testing.T) { + node := net.ParseIP("10.1.0.9") + other := net.ParseIP("10.9.9.9") + orig := hostIPs + t.Cleanup(func() { hostIPs = orig }) + hostIPs = func() ([]net.IP, error) { + return []net.IP{node, other}, nil + } + + secure := testServer(t) + secure.TLSSan = []string{"san.example.test"} + secure.TLSSanSecurity = true + securePaths, err := ensureCerts(secure) + if err != nil { + t.Fatal(err) + } + secureCert := mustCert(t, securePaths.ServingCert) + if hasIP(secureCert, other) { + t.Fatal("host address is present") + } + if !hasIP(secureCert, node) || !hasIP(secureCert, net.ParseIP("127.0.0.1")) || !hasIP(secureCert, net.ParseIP("10.43.0.1")) { + t.Fatal("node, loopback, or service address is absent") + } + if !hasDNS(secureCert, "san.example.test") || !hasDNS(secureCert, "localhost") || !hasDNS(secureCert, "node-a") { + t.Fatalf("dns %v", secureCert.DNSNames) + } + if !hasDNS(secureCert, "kubernetes.default.svc.cluster.local") { + t.Fatalf("dns %v", secureCert.DNSNames) + } + + open := testServer(t) + open.TLSSan = []string{"san.example.test"} + open.TLSSanSecurity = false + openPaths, err := ensureCerts(open) + if err != nil { + t.Fatal(err) + } + openCert := mustCert(t, openPaths.ServingCert) + if !hasIP(openCert, other) || !hasIP(openCert, net.ParseIP("10.43.0.1")) { + t.Fatal("host or service address is absent") + } + if !hasDNS(openCert, "san.example.test") { + t.Fatal("tls-san is absent") + } + assertAdmin(t, openPaths.AdminKubeconfig) +} + +func TestKubeletServingCert(t *testing.T) { + srv := testServer(t) + paths, err := ensureCerts(srv) + if err != nil { + t.Fatal(err) + } + ca := mustCert(t, paths.CACert) + cert := mustCert(t, paths.KubeletServingCert) + if err := cert.CheckSignatureFrom(ca); err != nil { + t.Fatal(err) + } + if !hasDNS(cert, "node-a") || !hasIP(cert, net.ParseIP("10.1.0.9")) { + t.Fatalf("names %v %v", cert.DNSNames, cert.IPAddresses) + } + if cert.Subject.CommonName != "node-a" { + t.Fatalf("common name %s", cert.Subject.CommonName) + } + client := mustCert(t, paths.APIServerCert) + if err := client.CheckSignatureFrom(ca); err != nil { + t.Fatal(err) + } + if client.Subject.CommonName != "system:apiserver" || !sameOrg(client, "system:masters") { + t.Fatalf("apiserver client %s %v", client.Subject.CommonName, client.Subject.Organization) + } +} + +func TestAdvertiseAddressUnset(t *testing.T) { + srv := config.Defaults() + srv.AdvertiseAddress = "192.0.2.9" + srv.NodeIP = "192.0.2.8" + got, err := advertiseAddress(srv) + if err != nil { + t.Fatal(err) + } + if got != "192.0.2.9" { + t.Fatalf("address %s", got) + } + srv.AdvertiseAddress = "" + got, err = advertiseAddress(srv) + if err != nil { + t.Fatal(err) + } + if got != "192.0.2.8" { + t.Fatalf("address %s", got) + } + srv.NodeIP = "" + orig := nodeIPForKubelet + t.Cleanup(func() { nodeIPForKubelet = orig }) + nodeIPForKubelet = func(string) (net.IP, error) { + return net.ParseIP("192.0.2.7"), nil + } + got, err = advertiseAddress(srv) + if err != nil { + t.Fatal(err) + } + if got != "192.0.2.7" { + t.Fatalf("address %s", got) + } + if srv.AdvertisePort != srv.HTTPSListenPort { + t.Fatalf("advertise port %d listen %d", srv.AdvertisePort, srv.HTTPSListenPort) + } +} + +func TestEncryptionFilePassedOnlyWhenAllowed(t *testing.T) { + dir := t.TempDir() + srv := config.Defaults() + srv.DataDir = dir + + got, err := encryptionConfig(srv) + if err != nil || got != "" { + t.Fatalf("config %q err %v", got, err) + } + args := apiServerArgs(srv, "unix:///tmp/kine.sock", "192.0.2.10", got, certPaths{}) + if strings.Contains(strings.Join(args, "\n"), "encryption-provider-config") { + t.Fatal(args) + } + + srv.SecretsEncryption = true + got, err = encryptionConfig(srv) + if err != nil { + t.Fatal(err) + } + want := datastore.EncryptionConfigPath(dir) + if got != want { + t.Fatalf("path %s", got) + } + args = apiServerArgs(srv, "unix:///tmp/kine.sock", "192.0.2.10", got, certPaths{}) + if !containsArg(args, "--encryption-provider-config="+want) { + t.Fatal(args) + } + + srv.SecretsEncryption = false + if _, err := encryptionConfig(srv); err == nil { + t.Fatal("expected a startup error") + } + + srv.SecretsEncryption = true + if err := os.Remove(want); err != nil { + t.Fatal(err) + } + db := datastore.StateDB(dir) + if err := os.MkdirAll(filepath.Dir(db), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(db, []byte("db"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := encryptionConfig(srv); err == nil { + t.Fatal("expected a startup error") + } +} + +func testServer(t *testing.T) config.Server { + t.Helper() + dir := t.TempDir() + srv := config.Defaults() + srv.DataDir = dir + srv.WriteKubeconfig = filepath.Join(dir, "edgelet-kube.yaml") + srv.NodeName = "node-a" + srv.NodeIP = "10.1.0.9" + return srv +} + +func assertAdmin(t *testing.T, path string) { + t.Helper() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("kubeconfig mode %o", info.Mode().Perm()) + } + cfg, err := clientcmd.BuildConfigFromFlags("", path) + if err != nil { + t.Fatal(err) + } + block, _ := pem.Decode(cfg.CertData) + if block == nil { + t.Fatal("client certificate is missing") + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + t.Fatal(err) + } + if cert.Subject.CommonName != "system:admin" || !sameOrg(cert, "system:masters") || len(cert.Subject.Organization) != 1 { + t.Fatalf("subject %s %v", cert.Subject.CommonName, cert.Subject.Organization) + } +} + +func mastersCount(t *testing.T, dir string) int { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var count int + for _, entry := range entries { + if !strings.HasSuffix(entry.Name(), ".crt") { + continue + } + cert := mustCert(t, filepath.Join(dir, entry.Name())) + if sameOrg(cert, "system:masters") { + count++ + } + } + return count +} + +func sameOrg(cert *x509.Certificate, org string) bool { + for _, got := range cert.Subject.Organization { + if got == org { + return true + } + } + return false +} + +func hasIP(cert *x509.Certificate, ip net.IP) bool { + for _, got := range cert.IPAddresses { + if got.Equal(ip) { + return true + } + } + return false +} + +func hasDNS(cert *x509.Certificate, name string) bool { + for _, got := range cert.DNSNames { + if strings.EqualFold(got, name) { + return true + } + } + return false +} + +func mustRead(t *testing.T, path string) []byte { + t.Helper() + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return body +} + +func mustCert(t *testing.T, path string) *x509.Certificate { + t.Helper() + cert, err := loadCert(path) + if err != nil { + t.Fatal(err) + } + return cert +} diff --git a/kube/internal/control/control_test.go b/kube/internal/control/control_test.go new file mode 100644 index 0000000..10ff30d --- /dev/null +++ b/kube/internal/control/control_test.go @@ -0,0 +1,775 @@ +package control + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "io" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/charts" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + "github.com/eclipse-iofog/edgelet-kube/internal/helm" + "github.com/eclipse-iofog/edgelet-kube/internal/network" + "github.com/eclipse-iofog/edgelet-kube/internal/stage" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "github.com/sirupsen/logrus" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/klog/v2" +) + +func TestMain(m *testing.M) { + logrus.SetOutput(io.Discard) + klog.SetOutput(io.Discard) + startKubelet = func(ctx context.Context, _ []string) error { + <-ctx.Done() + return nil + } + startKubeProxy = func(ctx context.Context, _ []string) error { + <-ctx.Done() + return nil + } + m.Run() +} + +func TestSELinuxRejectedWithoutHostSupport(t *testing.T) { + orig := hostSELinux + t.Cleanup(func() { hostSELinux = orig }) + + hostSELinux = func() bool { return false } + if err := CheckSELinux(false); err != nil { + t.Fatal(err) + } + if err := CheckSELinux(true); err == nil { + t.Fatal("expected a startup error") + } + hostSELinux = func() bool { return true } + if err := CheckSELinux(true); err != nil { + t.Fatal(err) + } +} + +func TestArgumentsUseConfiguredNetworks(t *testing.T) { + srv := config.Defaults() + srv.ClusterCIDR = "10.20.0.0/16" + srv.ServiceCIDR = "10.50.0.0/16" + srv.ClusterDNS = "10.50.0.25" + srv.ClusterDomain = "example.test" + srv.NodePodCIDR = "10.20.0.0/24" + srv.Disable = []string{"metrics-server"} + paths := certPaths{ + Dir: "/tmp/certs", + CACert: "/tmp/certs/ca.crt", + CAKey: "/tmp/certs/ca.key", + ServingCert: "/tmp/certs/serving.crt", + ServingKey: "/tmp/certs/serving.key", + ServiceAccountCert: "/tmp/certs/sa.crt", + ServiceAccountKey: "/tmp/certs/sa.key", + FrontProxyCA: "/tmp/certs/front-proxy-ca.crt", + FrontProxyCert: "/tmp/certs/front-proxy-client.crt", + FrontProxyKey: "/tmp/certs/front-proxy-client.key", + AdminKubeconfig: "/tmp/certs/admin.kubeconfig", + ControllerKubeconfig: "/tmp/certs/controller-manager.kubeconfig", + SchedulerKubeconfig: "/tmp/certs/scheduler.kubeconfig", + APIServerCert: "/tmp/certs/client-kube-apiserver.crt", + APIServerKey: "/tmp/certs/client-kube-apiserver.key", + } + api := strings.Join(apiServerArgs(srv, "unix:///tmp/kine.sock", "10.20.0.8", "", paths), "\n") + controller, err := controllerManagerArgs(srv, false, 10257, paths) + if err != nil { + t.Fatal(err) + } + joined := api + "\n" + strings.Join(controller, "\n") + "\n" + strings.Join(schedulerArgs(srv, false, 10259, paths), "\n") + for _, want := range []string{ + "--service-cluster-ip-range=10.50.0.0/16", + "--cluster-cidr=10.20.0.0/16", + "--node-cidr-mask-size=24", + "--service-account-issuer=https://kubernetes.default.svc.example.test", + "--etcd-servers=unix:///tmp/kine.sock", + "--bind-address=0.0.0.0", + "--secure-port=6443", + "--leader-elect=false", + "--proxy-client-cert-file=/tmp/certs/front-proxy-client.crt", + "--requestheader-client-ca-file=/tmp/certs/front-proxy-ca.crt", + "--enable-aggregator-routing=true", + "--advertise-address=10.20.0.8", + "--kubelet-client-certificate=/tmp/certs/client-kube-apiserver.crt", + "--kubelet-client-key=/tmp/certs/client-kube-apiserver.key", + } { + if !strings.Contains(joined, want) { + t.Fatalf("missing %s\n%s", want, joined) + } + } + for _, absent := range []string{ + "10.50.0.10", + "10.43.0.10", + "10.42.0.0/16", + "encryption-provider-config", + } { + if strings.Contains(joined, absent) { + t.Fatalf("argument list contains %s", absent) + } + } +} + +func TestLeaderElectionFollowsDatastore(t *testing.T) { + srv := config.Defaults() + paths := certPaths{ControllerKubeconfig: "c", SchedulerKubeconfig: "s"} + off, err := controllerManagerArgs(srv, false, 10257, paths) + if err != nil { + t.Fatal(err) + } + if !containsArg(off, "--leader-elect=false") { + t.Fatalf("controller args %v", off) + } + on := schedulerArgs(srv, true, 10259, paths) + if !containsArg(on, "--leader-elect=true") { + t.Fatalf("scheduler args %v", on) + } +} + +func TestReadyz(t *testing.T) { + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip(runtime.GOOS) + } + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + store, err := datastore.Open(ctx, datastore.Config{DataDir: dir}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + + srv := config.Defaults() + srv.DataDir = dir + srv.WriteKubeconfig = filepath.Join(dir, "edgelet-kube.yaml") + srv.BindAddress = "127.0.0.1" + srv.HTTPSListenPort = freePort(t) + srv.NodeIP = "192.0.2.10" + srv.ClusterCIDR = "10.20.0.0/16" + srv.ServiceCIDR = "10.50.0.0/16" + srv.ClusterDNS = "10.50.0.25" + srv.ClusterDomain = "example.test" + srv.NodePodCIDR = "10.20.0.0/24" + srv.DefaultLocalStoragePath = filepath.Join(dir, "volumes") + chartNames, err := charts.Names() + if err != nil { + t.Fatal(err) + } + extra := []byte("apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: caller-addon\n namespace: kube-system\ndata:\n ok: \"true\"\n---\napiVersion: helm.cattle.io/v1\nkind: HelmChart\nmetadata:\n name: chart-order\n namespace: kube-system\n annotations:\n helmcharts.helm.cattle.io/unmanaged: \"true\"\nspec:\n chart: https://kubernetes.default.svc" + charts.Prefix + chartNames[0] + "\n") + cniConf := filepath.Join(dir, "net.d") + cniBin := filepath.Join(dir, "bin") + origKubelet := startKubelet + origProxy := startKubeProxy + origHelm := startHelm + helmErr := make(chan error, 1) + t.Cleanup(func() { + startKubelet = origKubelet + startKubeProxy = origProxy + startHelm = origHelm + }) + startHelm = func(ctx context.Context, kubeconfig string, srv config.Server) error { + err := origHelm(ctx, kubeconfig, srv) + if err != nil && ctx.Err() == nil { + select { + case helmErr <- err: + default: + } + } + return err + } + kubeletStarted := make(chan struct{}) + proxyStarted := make(chan struct{}) + var kubeletArgsSeen []string + var proxyArgsSeen []string + startKubelet = func(ctx context.Context, args []string) error { + if _, err := os.Stat(filepath.Join(cniConf, network.FileName)); err != nil { + t.Errorf("conflist missing when kubelet started: %v", err) + } + kubeletArgsSeen = append([]string(nil), args...) + close(kubeletStarted) + <-ctx.Done() + return nil + } + startKubeProxy = func(ctx context.Context, args []string) error { + proxyArgsSeen = append([]string(nil), args...) + close(proxyStarted) + <-ctx.Done() + return nil + } + rt, err := Start(ctx, Config{ + Server: srv, + Store: store, + CNIConfDir: cniConf, + CNIBinDir: cniBin, + Manifests: extra, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(rt.Stop) + select { + case <-kubeletStarted: + case <-ctx.Done(): + t.Fatal("kubelet was not started") + } + select { + case <-proxyStarted: + case <-ctx.Done(): + t.Fatal("kube-proxy was not started") + } + body, err := os.ReadFile(filepath.Join(cniConf, network.FileName)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), `"hairpinMode":true`) { + t.Fatalf("conflist %s", body) + } + entries, err := os.ReadDir(cniConf) + if err != nil { + t.Fatal(err) + } + var conflists int + for _, entry := range entries { + name := entry.Name() + if strings.HasSuffix(name, ".conflist") || strings.HasSuffix(name, ".conf") { + conflists++ + } + } + if conflists != 1 { + t.Fatalf("conflists %d", conflists) + } + seen := strings.Join(kubeletArgsSeen, "\n") + "\n" + strings.Join(proxyArgsSeen, "\n") + for _, want := range []string{ + "--cni-conf-dir=" + cniConf, + "--cni-bin-dir=" + cniBin, + "--pod-infra-container-image=" + config.DefaultPauseImage, + "--proxy-mode=iptables", + "--cluster-cidr=" + srv.ClusterCIDR, + "--cgroup-driver=systemd", + } { + if !strings.Contains(seen, want) { + t.Fatalf("missing %s\n%s", want, seen) + } + } + if strings.Contains(seen, "/opt/cni/bin") || strings.Contains(seen, "register-with-taints") || strings.Contains(seen, "cgroupfs") || strings.Contains(seen, "protect-kernel-defaults") { + t.Fatalf("args %s", seen) + } + if kubeletRunning() { + t.Fatal("kubelet is running") + } + if _, err := os.Stat(filepath.Join(dir, "server", "tls", "ca.crt")); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "server", "temporary")); !os.IsNotExist(err) { + t.Fatal("temporary certificate directory was created") + } + if _, err := os.Stat(filepath.Join(dir, "db", "etcd")); !os.IsNotExist(err) { + t.Fatal("etcd directory was created") + } + info, err := os.Stat(rt.Kubeconfig) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("kubeconfig mode %o", info.Mode().Perm()) + } + + cfg, err := clientcmd.BuildConfigFromFlags("", rt.Kubeconfig) + if err != nil { + t.Fatal(err) + } + client, err := kubernetes.NewForConfig(cfg) + if err != nil { + t.Fatal(err) + } + readyBody, err := client.Discovery().RESTClient().Get().AbsPath("/readyz").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(readyBody), "ok") { + t.Fatalf("readyz %q", readyBody) + } + versionBody, err := client.Discovery().RESTClient().Get().AbsPath("/version").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(versionBody), airgap.KubernetesVersion()) { + t.Fatalf("version %s", versionBody) + } + group, err := client.Discovery().RESTClient().Get().AbsPath("/apis/apiregistration.k8s.io/v1").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(group), "APIService") { + t.Fatalf("aggregation API %s", group) + } + if kubeletRunning() { + t.Fatal("kubelet is running") + } + + addons := kubeClient(t, rt.Kubeconfig) + if _, err := addons.kube.CoreV1().ConfigMaps("kube-system").Get(ctx, "caller-addon", metav1.GetOptions{}); err != nil { + t.Fatal(err) + } + chart, err := client.Discovery().RESTClient().Get().AbsPath("/apis/helm.cattle.io/v1/namespaces/kube-system/helmcharts/chart-order").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(chart), "chart-order") { + t.Fatalf("helm chart %s", chart) + } + assertCharts(t, rt.Kubeconfig, chartNames) + assertStagedCharts(t, client) + waitHelmLease(t, client) + waitHelmJob(t, client, "helm-install-traefik") + waitHelmJob(t, client, "helm-install-cert-manager") + select { + case err := <-helmErr: + t.Fatal(err) + case <-time.After(10 * time.Second): + } + assertAddons(t, addons, srv, true, true, true) + assertMetricsTop(t, addons, rt.Kubeconfig) + for _, name := range []string{"coredns", "local-storage", "metrics-server"} { + disabled := srv + disabled.Disable = []string{name} + if err := stage.Apply(ctx, rt.Kubeconfig, disabled, extra); err != nil { + t.Fatal(err) + } + assertAddons(t, addons, srv, name != "coredns", name != "local-storage", name != "metrics-server") + if _, err := addons.kube.CoreV1().ConfigMaps("kube-system").Get(ctx, "caller-addon", metav1.GetOptions{}); err != nil { + t.Fatal(err) + } + if name == "metrics-server" { + still, err := addons.kube.Discovery().RESTClient().Get().AbsPath("/apis/apiregistration.k8s.io/v1").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(still), "APIService") { + t.Fatalf("aggregation API %s", still) + } + } + if err := stage.Apply(ctx, rt.Kubeconfig, srv, extra); err != nil { + t.Fatal(err) + } + assertAddons(t, addons, srv, true, true, true) + } + assertIssuerRetries(ctx, t, rt.Kubeconfig, srv) +} + +func TestKubeletAndProxyUseNodeNetwork(t *testing.T) { + srv := config.Defaults() + srv.NodeName = "node-a" + srv.NodeIP = "192.0.2.10" + srv.DataDir = t.TempDir() + srv.ClusterCIDR = "10.20.0.0/16" + srv.ServiceCIDR = "10.50.0.0/16" + srv.ClusterDNS = "10.50.0.10" + srv.ClusterDomain = "example.test" + srv.NodePodCIDR = "10.20.0.0/24" + srv.PauseImage = "registry.example/pause:test" + srv.NodeLabel = []string{"disk=ssd"} + srv.ResolvConf = "/etc/resolv.conf" + srv.WriteKubeconfig = filepath.Join(srv.DataDir, "edgelet-kube.yaml") + certs, err := ensureCerts(srv) + if err != nil { + t.Fatal(err) + } + cniConf := filepath.Join(srv.DataDir, "net.d") + cniBin := filepath.Join(srv.DataDir, "bin") + kubelet, err := kubeletArgs(srv, srv.NodeIP, certs, cniConf, cniBin) + if err != nil { + t.Fatal(err) + } + proxy, err := kubeProxyArgs(srv, srv.NodeIP, certs) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(kubelet, "\n") + "\n" + strings.Join(proxy, "\n") + for _, want := range []string{ + "--cni-conf-dir=" + cniConf, + "--cni-bin-dir=" + cniBin, + "--pod-infra-container-image=registry.example/pause:test", + "--container-runtime-endpoint=unix:///run/edgelet-kube/containerd.sock", + "--cluster-dns=10.50.0.10", + "--cluster-domain=example.test", + "--node-ip=192.0.2.10", + "--hostname-override=node-a", + "--node-labels=disk=ssd", + "--resolv-conf=/etc/resolv.conf", + "--tls-cert-file=" + certs.KubeletServingCert, + "--tls-private-key-file=" + certs.KubeletServingKey, + "--client-ca-file=" + certs.CACert, + "--proxy-mode=iptables", + "--cluster-cidr=10.20.0.0/16", + "--cgroup-driver=systemd", + } { + if !strings.Contains(joined, want) { + t.Fatalf("missing %s\n%s", want, joined) + } + } + for _, absent := range []string{ + "/opt/cni/bin", + "register-with-taints", + "control-plane", + "cgroupfs", + "protect-kernel-defaults", + "disable-kube-proxy", + "--token", + "flannel", + } { + if strings.Contains(joined, absent) { + t.Fatalf("argument list contains %s\n%s", absent, joined) + } + } + loaded, err := loadKubelet(kubelet) + if err != nil { + t.Fatal(err) + } + if loaded.CgroupDriver != "systemd" || loaded.ProtectKernelDefaults { + t.Fatalf("driver %s protect %v", loaded.CgroupDriver, loaded.ProtectKernelDefaults) + } + if _, err := loadKubeProxy(proxy); err != nil { + t.Fatal(err) + } + + srv.NodeTaint = []string{"dedicated=lab:NoSchedule"} + withTaint, err := kubeletArgs(srv, srv.NodeIP, certs, cniConf, cniBin) + if err != nil { + t.Fatal(err) + } + taintArgs := strings.Join(withTaint, "\n") + if !strings.Contains(taintArgs, "--register-with-taints=dedicated=lab:NoSchedule") { + t.Fatalf("taint args %s", taintArgs) + } + if strings.Contains(taintArgs, "control-plane") { + t.Fatalf("taint args %s", taintArgs) + } + if _, err := kubeletArgs(srv, srv.NodeIP, certs, cniConf, "/opt/cni/bin"); err == nil { + t.Fatal("accepted the host cni directory") + } +} + +func TestKubeletProtectsKernelDefaults(t *testing.T) { + srv := config.Defaults() + srv.NodeName = "node-a" + srv.NodeIP = "192.0.2.10" + srv.DataDir = t.TempDir() + srv.ProtectKernelDefaults = true + srv.KubeletArg = []string{"protect-kernel-defaults=false", "v=2"} + certs := certPaths{KubeletKubeconfig: filepath.Join(srv.DataDir, "kubelet.kubeconfig")} + args, err := kubeletArgs(srv, srv.NodeIP, certs, filepath.Join(srv.DataDir, "net.d"), filepath.Join(srv.DataDir, "bin")) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(args, "\n") + if !strings.Contains(joined, "--cgroup-driver=systemd") || !strings.Contains(joined, "--protect-kernel-defaults=true") { + t.Fatalf("args %s", joined) + } + if strings.Contains(joined, "cgroupfs") || strings.Contains(joined, "--protect-kernel-defaults=false") { + t.Fatalf("args %s", joined) + } + if !strings.Contains(joined, "--v=2") { + t.Fatalf("args %s", joined) + } + loaded, err := loadKubelet(args) + if err != nil { + t.Fatal(err) + } + if loaded.CgroupDriver != "systemd" || !loaded.ProtectKernelDefaults { + t.Fatalf("driver %s protect %v", loaded.CgroupDriver, loaded.ProtectKernelDefaults) + } + + srv.ProtectKernelDefaults = false + srv.KubeletArg = []string{"cgroup-driver=cgroupfs"} + if _, err := kubeletArgs(srv, srv.NodeIP, certs, filepath.Join(srv.DataDir, "net.d"), filepath.Join(srv.DataDir, "bin")); err == nil { + t.Fatal("accepted a cgroupfs driver") + } +} + +func TestPreferBundledIptables(t *testing.T) { + root := t.TempDir() + bin := filepath.Join(root, "bin") + aux := filepath.Join(bin, "aux") + host := filepath.Join(root, "host") + if err := os.MkdirAll(aux, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(host, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(aux, "xtables-nft-multi"), []byte("iptables"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("xtables-nft-multi", filepath.Join(aux, "iptables")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(host, "iptables"), []byte("host"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", host) + + srv := config.Defaults() + if !srv.PreferBundledBin { + t.Fatal("prefer-bundled-bin default") + } + if err := applyBundledPath(srv.PreferBundledBin, bin); err != nil { + t.Fatal(err) + } + got, err := exec.LookPath("iptables") + if err != nil { + t.Fatal(err) + } + if got != filepath.Join(aux, "iptables") { + t.Fatalf("iptables %s", got) + } + target, err := os.Readlink(got) + if err != nil { + t.Fatal(err) + } + if target != "xtables-nft-multi" { + t.Fatalf("iptables -> %s", target) + } + if !strings.HasPrefix(os.Getenv("PATH"), aux+string(os.PathListSeparator)) { + t.Fatalf("PATH %s", os.Getenv("PATH")) + } + + if err := applyBundledPath(false, bin); err != nil { + t.Fatal(err) + } + got, err = exec.LookPath("iptables") + if err != nil { + t.Fatal(err) + } + if got != filepath.Join(host, "iptables") { + t.Fatalf("host iptables %s", got) + } +} + +func assertCharts(t *testing.T, kubeconfig string, names []string) { + t.Helper() + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + t.Fatal(err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(cfg.CAData) { + t.Fatal("cluster CA was not in the client config") + } + client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} + base := strings.TrimRight(cfg.Host, "/") + for _, name := range names { + resp, err := client.Get(base + charts.Prefix + name) + if err != nil { + t.Fatal(err) + } + body, err := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("%s status %d", name, resp.StatusCode) + } + want, err := charts.Read(name) + if err != nil { + t.Fatal(err) + } + if string(body) != string(want) { + t.Fatalf("%s returned %d bytes", name, len(body)) + } + } + resp, err := client.Get(base + "/api/v1") + if err != nil { + t.Fatal(err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("unauthenticated api status %d", resp.StatusCode) + } +} + +type helmChartSpec struct { + Chart string `json:"chart"` + ValuesContent string `json:"valuesContent"` + TargetNamespace string `json:"targetNamespace"` +} + +type helmChartObject struct { + Spec helmChartSpec `json:"spec"` +} + +func assertStagedCharts(t *testing.T, client kubernetes.Interface) { + t.Helper() + ctx := t.Context() + names, err := charts.Names() + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"traefik-crd", "traefik", "gateway-api-crd", "cert-manager"} { + raw, err := client.Discovery().RESTClient().Get().AbsPath("/apis/helm.cattle.io/v1/namespaces/kube-system/helmcharts/" + name).DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + var obj helmChartObject + if err := json.Unmarshal(raw, &obj); err != nil { + t.Fatal(err) + } + var file string + for _, candidate := range names { + if strings.HasPrefix(candidate, name+"-") && strings.HasSuffix(candidate, ".tgz") { + if name == "traefik" && strings.HasPrefix(candidate, "traefik-crd-") { + continue + } + file = candidate + } + } + want := "https://kubernetes.default.svc" + charts.Prefix + file + if obj.Spec.Chart != want { + t.Fatalf("%s chart %s", name, obj.Spec.Chart) + } + if name == "traefik" { + if !strings.Contains(obj.Spec.ValuesContent, "type: LoadBalancer") { + t.Fatalf("traefik values %s", obj.Spec.ValuesContent) + } + if !strings.Contains(obj.Spec.ValuesContent, "exposedPort: 80") || !strings.Contains(obj.Spec.ValuesContent, "exposedPort: 443") { + t.Fatalf("traefik ports %s", obj.Spec.ValuesContent) + } + } + if name == "cert-manager" { + if obj.Spec.TargetNamespace != "cert-manager" || !strings.Contains(obj.Spec.ValuesContent, "enabled: true") { + t.Fatalf("cert-manager %#v", obj.Spec) + } + } + } + err = client.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/letsencrypt-prod").Do(ctx).Error() + if err == nil { + t.Fatal("letsencrypt cluster issuer was written without an email") + } +} + +func waitHelmJob(t *testing.T, client kubernetes.Interface, name string) { + t.Helper() + ctx := t.Context() + deadline := time.NewTimer(60 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + _, last = client.BatchV1().Jobs("kube-system").Get(ctx, name, metav1.GetOptions{}) + if last == nil { + return + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + t.Fatalf("helm job %s: %v", name, last) + case <-ticker.C: + } + } +} + +func waitHelmLease(t *testing.T, client kubernetes.Interface) { + t.Helper() + ctx := t.Context() + deadline := time.NewTimer(60 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + _, last = client.CoordinationV1().Leases("kube-system").Get(ctx, helm.LeaseName, metav1.GetOptions{}) + if last == nil { + return + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + t.Fatalf("helm controller lease: %v", last) + case <-ticker.C: + } + } +} + +func containsArg(args []string, want string) bool { + for _, arg := range args { + if arg == want { + return true + } + } + return false +} + +func freePort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + port := ln.Addr().(*net.TCPAddr).Port + _ = ln.Close() + return port +} + +func kubeletRunning() bool { + if _, err := os.Stat("/proc"); err == nil { + entries, err := os.ReadDir("/proc") + if err != nil { + return false + } + for _, entry := range entries { + body, err := os.ReadFile("/proc/" + entry.Name() + "/cmdline") + if err != nil || len(body) == 0 { + continue + } + argv0 := string(body) + if i := strings.IndexByte(argv0, 0); i >= 0 { + argv0 = argv0[:i] + } + if filepath.Base(argv0) == "kubelet" { + return true + } + } + return false + } + out, err := exec.Command("ps", "-ax", "-o", "comm=").Output() + if err != nil { + return false + } + for _, line := range strings.Split(string(out), "\n") { + if filepath.Base(strings.TrimSpace(line)) == "kubelet" { + return true + } + } + return false +} + +func TestPodNetworkRunsBeforeControllers(t *testing.T) { + // The ordering test above starts the controllers. This checks the port + // helper used when the API port is not the default. + controller, scheduler := componentPorts(20000, 0, 0) + if controller != 20001 || scheduler != 20002 { + t.Fatalf("ports %d %d", controller, scheduler) + } + controller, scheduler = componentPorts(config.DefaultHTTPSListenPort, 0, 0) + if controller != 10257 || scheduler != 10259 { + t.Fatalf("default ports %d %d", controller, scheduler) + } +} diff --git a/kube/internal/control/issuer_test.go b/kube/internal/control/issuer_test.go new file mode 100644 index 0000000..1fe09e5 --- /dev/null +++ b/kube/internal/control/issuer_test.go @@ -0,0 +1,176 @@ +package control + +import ( + "context" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + "github.com/eclipse-iofog/edgelet-kube/internal/stage" + "k8s.io/client-go/kubernetes" +) + +func TestHelmControllerDisabledKeepsManifestAddons(t *testing.T) { + if os.Getenv("EDGELET_KUBE_HELM_OFF") != "1" { + cmd := exec.Command(os.Args[0], "-test.run=^TestHelmControllerDisabledKeepsManifestAddons$", "-test.count=1", "-test.timeout=4m") + cmd.Env = append(os.Environ(), "EDGELET_KUBE_HELM_OFF=1") + out, err := cmd.CombinedOutput() + if err != nil || !strings.Contains(string(out), helmOffChecked) { + t.Fatalf("%v\n%s", err, out) + } + return + } + srv := config.Defaults() + srv.DisableHelmController = true + srv.ClusterIssuerEmail = "ops@example.com" + rt := bootServer(t, &srv) + ctx := t.Context() + client := kubeClient(t, rt.Kubeconfig) + assertAddons(t, client, srv, true, true, true) + _, err := client.kube.Discovery().ServerResourcesForGroupVersion("helm.cattle.io/v1") + if err == nil { + t.Fatal("helm chart API is served") + } + if err := client.kube.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/letsencrypt-prod").Do(ctx).Error(); err == nil { + t.Fatal("letsencrypt cluster issuer was written") + } + if err := client.kube.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/selfsigned").Do(ctx).Error(); err == nil { + t.Fatal("selfsigned cluster issuer was written") + } + fmt.Println(helmOffChecked) +} + +const helmOffChecked = "helm-controller-disabled-checked" + +func assertIssuerRetries(ctx context.Context, t *testing.T, kubeconfig string, srv config.Server) { + t.Helper() + withEmail := srv + withEmail.ClusterIssuerEmail = "ops@example.com" + done := make(chan error, 1) + go func() { + done <- stage.ApplyIssuer(ctx, kubeconfig, withEmail) + }() + client := kubeClient(t, kubeconfig).kube + deadline := time.Now().Add(time.Second) + for time.Now().Before(deadline) { + if issuerPresent(ctx, client) { + t.Fatal("cluster issuer was written before its CRD") + } + select { + case err := <-done: + t.Fatalf("issuer apply returned before the CRD: %v", err) + default: + } + time.Sleep(100 * time.Millisecond) + } + if err := stage.Apply(ctx, kubeconfig, srv, []byte(clusterIssuerCRD)); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(30 * time.Second): + t.Fatal("cluster issuer was not applied") + } + body, err := client.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/letsencrypt-prod").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + raw := string(body) + for _, want := range []string{ + "ops@example.com", + "letsencrypt-prod-account-key", + "https://acme-v02.api.letsencrypt.org/directory", + "traefik", + } { + if !strings.Contains(raw, want) { + t.Fatalf("issuer missing %s\n%s", want, raw) + } + } + signed, err := client.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/selfsigned").DoRaw(ctx) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(signed), "selfSigned") { + t.Fatalf("selfsigned issuer\n%s", signed) + } +} + +func bootServer(t *testing.T, srv *config.Server) *Runtime { + t.Helper() + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip(runtime.GOOS) + } + // The socket path has to stay under the platform limit. The test name is + // part of t.TempDir and makes that path too long. + dir, err := os.MkdirTemp("/tmp", "ek") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + store, err := datastore.Open(ctx, datastore.Config{DataDir: dir}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + srv.DataDir = dir + srv.WriteKubeconfig = filepath.Join(dir, "edgelet-kube.yaml") + srv.BindAddress = "127.0.0.1" + srv.HTTPSListenPort = freePort(t) + srv.NodeIP = "192.0.2.10" + srv.ClusterCIDR = "10.20.0.0/16" + srv.ServiceCIDR = "10.50.0.0/16" + srv.ClusterDNS = "10.50.0.25" + srv.ClusterDomain = "example.test" + srv.NodePodCIDR = "10.20.0.0/24" + srv.DefaultLocalStoragePath = filepath.Join(dir, "volumes") + rt, err := Start(ctx, Config{ + Server: *srv, + Store: store, + CNIConfDir: filepath.Join(dir, "net.d"), + CNIBinDir: filepath.Join(dir, "bin"), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(rt.Stop) + return rt +} + +func issuerPresent(ctx context.Context, client kubernetes.Interface) bool { + err := client.Discovery().RESTClient().Get().AbsPath("/apis/cert-manager.io/v1/clusterissuers/letsencrypt-prod").Do(ctx).Error() + return err == nil +} + +const clusterIssuerCRD = `apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: clusterissuers.cert-manager.io +spec: + group: cert-manager.io + names: + kind: ClusterIssuer + listKind: ClusterIssuerList + plural: clusterissuers + singular: clusterissuer + scope: Cluster + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + x-kubernetes-preserve-unknown-fields: true +` diff --git a/kube/internal/control/names.go b/kube/internal/control/names.go new file mode 100644 index 0000000..a968e23 --- /dev/null +++ b/kube/internal/control/names.go @@ -0,0 +1,308 @@ +package control + +import ( + "crypto/x509" + "crypto/x509/pkix" + "errors" + "fmt" + "net" + "os" + "strings" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + utilnet "k8s.io/apimachinery/pkg/util/net" +) + +// hostIPs lists addresses on this host. The serving certificate includes +// them only when tls-san-security is false. +var hostIPs = hostInterfaceIPs + +// nodeIPForKubelet is the address kubelet uses as the node IP when node-ip +// is unset. +var nodeIPForKubelet = kubeletNodeIP + +func advertiseAddress(srv config.Server) (string, error) { + if srv.AdvertiseAddress != "" { + if net.ParseIP(srv.AdvertiseAddress) == nil { + return "", fmt.Errorf("advertise-address %q is not an IP", srv.AdvertiseAddress) + } + return srv.AdvertiseAddress, nil + } + return nodeIP(srv) +} + +// nodeIP is the address published on LoadBalancer Services. +// It is node-ip when that is set, otherwise the address kubelet uses. +func nodeIP(srv config.Server) (string, error) { + if srv.NodeIP != "" { + ip := net.ParseIP(srv.NodeIP) + if ip == nil { + return "", fmt.Errorf("node-ip %q is not an IP", srv.NodeIP) + } + return ip.String(), nil + } + name, err := nodeName(srv) + if err != nil { + return "", err + } + ip, err := nodeIPForKubelet(name) + if err != nil { + return "", err + } + return ip.String(), nil +} + +func nodeName(srv config.Server) (string, error) { + if srv.NodeName != "" { + return srv.NodeName, nil + } + name, err := os.Hostname() + if err != nil || name == "" { + return "", errors.New("node name is empty") + } + return name, nil +} + +func servingCertificate(srv config.Server) (*x509.Certificate, error) { + names := newNameSet() + names.addDNS("localhost") + names.addIP(net.ParseIP("127.0.0.1")) + names.addIP(net.ParseIP("::1")) + + name, err := nodeName(srv) + if err != nil { + return nil, err + } + if ip := net.ParseIP(name); ip != nil { + names.addIP(ip) + } else { + names.addDNS(name) + } + if srv.NodeIP != "" { + if err := names.addRequiredIP("node-ip", srv.NodeIP); err != nil { + return nil, err + } + } else { + ip, err := nodeIPForKubelet(name) + if err != nil { + return nil, err + } + names.addIP(ip) + } + if srv.NodeExternalIP != "" { + if err := names.addRequiredIP("node-external-ip", srv.NodeExternalIP); err != nil { + return nil, err + } + } + cidr := srv.ServiceCIDR + if cidr == "" { + cidr = config.DefaultServiceCIDR + } + serviceIP, err := config.FirstServiceAddress(cidr) + if err != nil { + return nil, err + } + if err := names.addRequiredIP("service-cidr", serviceIP); err != nil { + return nil, err + } + for _, dns := range kubernetesServiceNames(srv.ClusterDomain) { + names.addDNS(dns) + } + for _, san := range srv.TLSSan { + names.addSAN(san) + } + if !srv.TLSSanSecurity { + extras, err := hostIPs() + if err != nil { + return nil, err + } + for _, ip := range extras { + names.addIP(ip) + } + } + return names.certificate(), nil +} + +// kubeletServingCertificate is the certificate kubelet presents on its port. +// The API verifies it with the cluster CA, so the node name and node address +// are the names the API dials. +func kubeletServingCertificate(srv config.Server) (*x509.Certificate, error) { + names := newNameSet() + name, err := nodeName(srv) + if err != nil { + return nil, err + } + if ip := net.ParseIP(name); ip != nil { + names.addIP(ip) + } else { + names.addDNS(name) + } + node := srv.NodeIP + if node == "" { + ip, err := nodeIPForKubelet(name) + if err != nil { + return nil, err + } + node = ip.String() + } + if err := names.addRequiredIP("node-ip", node); err != nil { + return nil, err + } + cert := names.certificate() + cert.Subject.CommonName = name + return cert, nil +} + +func kubernetesServiceNames(domain string) []string { + names := []string{ + "kubernetes", + "kubernetes.default", + "kubernetes.default.svc", + } + domain = strings.Trim(domain, ".") + if domain != "" { + names = append(names, "kubernetes.default.svc."+domain) + } + return names +} + +func kubeletNodeIP(nodeName string) (net.IP, error) { + if ip := net.ParseIP(nodeName); validNodeIP(ip) { + return canonicalIP(ip), nil + } + if ips, err := net.LookupIP(nodeName); err == nil { + var fallback net.IP + for _, ip := range ips { + if !validNodeIP(ip) { + continue + } + if ip.To4() != nil { + return canonicalIP(ip), nil + } + if fallback == nil { + fallback = ip + } + } + if fallback != nil { + return canonicalIP(fallback), nil + } + } + ip, err := utilnet.ChooseHostInterface() + if err != nil { + return nil, fmt.Errorf("node IP: %w", err) + } + if !validNodeIP(ip) { + return nil, fmt.Errorf("node IP %s is not usable", ip) + } + return canonicalIP(ip), nil +} + +func validNodeIP(ip net.IP) bool { + return ip != nil && !ip.IsUnspecified() && !ip.IsLoopback() && !ip.IsMulticast() && !ip.IsLinkLocalUnicast() +} + +func hostInterfaceIPs() ([]net.IP, error) { + addrs, err := net.InterfaceAddrs() + if err != nil { + return nil, fmt.Errorf("host addresses: %w", err) + } + var out []net.IP + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + if ip == nil || ip.IsLoopback() || ip.IsUnspecified() { + continue + } + out = append(out, canonicalIP(ip)) + } + return out, nil +} + +func canonicalIP(ip net.IP) net.IP { + if ip == nil { + return nil + } + if v4 := ip.To4(); v4 != nil { + return append(net.IP(nil), v4...) + } + return append(net.IP(nil), ip...) +} + +type nameSet struct { + dns []string + ips []net.IP + seenDNS map[string]struct{} + seenIP map[string]struct{} +} + +func newNameSet() *nameSet { + return &nameSet{ + seenDNS: map[string]struct{}{}, + seenIP: map[string]struct{}{}, + } +} + +func (n *nameSet) addDNS(name string) { + name = strings.TrimSpace(name) + if name == "" { + return + } + key := strings.ToLower(name) + if _, ok := n.seenDNS[key]; ok { + return + } + n.seenDNS[key] = struct{}{} + n.dns = append(n.dns, name) +} + +func (n *nameSet) addIP(ip net.IP) { + ip = canonicalIP(ip) + if ip == nil { + return + } + key := ip.String() + if _, ok := n.seenIP[key]; ok { + return + } + n.seenIP[key] = struct{}{} + n.ips = append(n.ips, ip) +} + +func (n *nameSet) addRequiredIP(field, raw string) error { + ip := net.ParseIP(strings.TrimSpace(raw)) + if ip == nil { + return fmt.Errorf("%s %q is not an IP", field, raw) + } + n.addIP(ip) + return nil +} + +func (n *nameSet) addSAN(raw string) { + raw = strings.TrimSpace(raw) + if raw == "" { + return + } + if ip := net.ParseIP(raw); ip != nil { + n.addIP(ip) + return + } + n.addDNS(raw) +} + +func (n *nameSet) certificate() *x509.Certificate { + return &x509.Certificate{ + Subject: pkix.Name{CommonName: "kube-apiserver"}, + DNSNames: append([]string(nil), n.dns...), + IPAddresses: append([]net.IP(nil), n.ips...), + KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour), + } +} diff --git a/kube/internal/control/proc.go b/kube/internal/control/proc.go new file mode 100644 index 0000000..fac8a92 --- /dev/null +++ b/kube/internal/control/proc.go @@ -0,0 +1,211 @@ +package control + +import ( + "bytes" + "context" + "fmt" + "io" + + "github.com/eclipse-iofog/edgelet-kube/internal/charts" + "github.com/spf13/pflag" + utilerrors "k8s.io/apimachinery/pkg/util/errors" + utilfeature "k8s.io/apiserver/pkg/util/feature" + cliflag "k8s.io/component-base/cli/flag" + apiapp "k8s.io/kubernetes/cmd/kube-apiserver/app" + apioptions "k8s.io/kubernetes/cmd/kube-apiserver/app/options" + cmapp "k8s.io/kubernetes/cmd/kube-controller-manager/app" + cmoptions "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" + proxyapp "k8s.io/kubernetes/cmd/kube-proxy/app" + schedapp "k8s.io/kubernetes/cmd/kube-scheduler/app" + schedoptions "k8s.io/kubernetes/cmd/kube-scheduler/app/options" + kubeletapp "k8s.io/kubernetes/cmd/kubelet/app" + kubeletoptions "k8s.io/kubernetes/cmd/kubelet/app/options" +) + +var ( + startKubelet = launchKubelet + startKubeProxy = launchKubeProxy +) + +func runAPIServer(ctx context.Context, args []string) error { + opts := apioptions.NewServerRunOptions() + if err := parseFlags("kube-apiserver", opts.Flags(), args); err != nil { + return err + } + if err := opts.GenericServerRunOptions.ComponentGlobalsRegistry.Set(); err != nil { + return err + } + completed, err := opts.Complete(ctx) + if err != nil { + return err + } + if errs := completed.Validate(); len(errs) > 0 { + return utilerrors.NewAggregate(errs) + } + cfg, err := apiapp.NewConfig(completed) + if err != nil { + return err + } + finished, err := cfg.Complete() + if err != nil { + return err + } + server, err := apiapp.CreateServerChain(finished) + if err != nil { + return err + } + prepared, err := server.PrepareRun() + if err != nil { + return err + } + handler := server.GenericAPIServer.Handler + handler.FullHandlerChain = charts.Handler(handler.FullHandlerChain) + return prepared.Run(ctx) +} + +func runControllerManager(ctx context.Context, args []string) error { + opts, err := cmoptions.NewKubeControllerManagerOptions() + if err != nil { + return err + } + known := cmapp.KnownControllers() + disabled := cmapp.ControllersDisabledByDefault() + aliases := cmapp.ControllerAliases() + if err := parseFlags("kube-controller-manager", opts.Flags(known, disabled, aliases), args); err != nil { + return err + } + if err := opts.ComponentGlobalsRegistry.Set(); err != nil { + return err + } + cfg, err := opts.Config(ctx, known, disabled, aliases) + if err != nil { + return err + } + return cmapp.Run(ctx, cfg.Complete()) +} + +func runScheduler(ctx context.Context, args []string) error { + opts := schedoptions.NewOptions() + if err := parseFlags("kube-scheduler", *opts.Flags, args); err != nil { + return err + } + completed, sched, err := schedapp.Setup(ctx, opts) + if err != nil { + return err + } + return schedapp.Run(ctx, completed, sched) +} + +func launchKubelet(ctx context.Context, args []string) error { + server, err := loadKubelet(args) + if err != nil { + return err + } + // Run dereferences this value before it will build one itself. + deps, err := kubeletapp.UnsecuredDependencies(ctx, server, utilfeature.DefaultFeatureGate) + if err != nil { + return err + } + return kubeletapp.Run(ctx, server, deps, utilfeature.DefaultFeatureGate) +} + +func launchKubeProxy(ctx context.Context, args []string) error { + opts, err := loadKubeProxy(args) + if err != nil { + return err + } + return opts.Run(ctx) +} + +func loadKubelet(args []string) (*kubeletoptions.KubeletServer, error) { + flags := kubeletoptions.NewKubeletFlags() + cfg, err := kubeletoptions.NewKubeletConfiguration() + if err != nil { + return nil, err + } + fs := pflag.NewFlagSet("kubelet", pflag.ContinueOnError) + var buf bytes.Buffer + fs.SetOutput(&buf) + flags.AddFlags(fs) + kubeletoptions.AddKubeletConfigFlags(fs, cfg) + acceptRuntimeFlags(fs) + if err := fs.Parse(args); err != nil { + return nil, flagParseError("kubelet", err, &buf) + } + if extra := fs.Args(); len(extra) > 0 { + return nil, fmt.Errorf("kubelet: unknown command %s", extra[0]) + } + server := &kubeletoptions.KubeletServer{ + KubeletFlags: *flags, + KubeletConfiguration: *cfg, + } + if err := kubeletoptions.ValidateKubeletServer(server); err != nil { + return nil, err + } + return server, nil +} + +func loadKubeProxy(args []string) (*proxyapp.Options, error) { + opts := proxyapp.NewOptions() + fs := pflag.NewFlagSet("kube-proxy", pflag.ContinueOnError) + var buf bytes.Buffer + fs.SetOutput(&buf) + opts.AddFlags(fs) + if err := fs.Parse(args); err != nil { + return nil, flagParseError("kube-proxy", err, &buf) + } + if err := opts.Complete(fs); err != nil { + return nil, err + } + if err := opts.Validate(); err != nil { + return nil, err + } + return opts, nil +} + +// acceptRuntimeFlags keeps the sandbox image and CNI directory flags on the +// kubelet command line. This build leaves both settings to the container +// runtime, which is started with the same values. +func acceptRuntimeFlags(fs *pflag.FlagSet) { + var confDir, binDir, pause string + if fs.Lookup("cni-conf-dir") == nil { + fs.StringVar(&confDir, "cni-conf-dir", "", "CNI configuration directory") + } + if fs.Lookup("cni-bin-dir") == nil { + fs.StringVar(&binDir, "cni-bin-dir", "", "CNI plugin directory") + } + if fs.Lookup("pod-infra-container-image") == nil { + fs.StringVar(&pause, "pod-infra-container-image", "", "sandbox image") + } +} + +func parseFlags(name string, sets cliflag.NamedFlagSets, args []string) error { + fs := pflag.NewFlagSet(name, pflag.ContinueOnError) + var buf bytes.Buffer + fs.SetOutput(&buf) + for _, set := range sets.FlagSets { + fs.AddFlagSet(set) + } + if err := fs.Parse(args); err != nil { + return flagParseError(name, err, &buf) + } + return nil +} + +func flagParseError(name string, err error, buf io.Reader) error { + detail, _ := io.ReadAll(buf) + if len(detail) == 0 { + return fmt.Errorf("%s: %w", name, err) + } + return fmt.Errorf("%s: %w: %s", name, err, bytes.TrimSpace(detail)) +} + +func report(errCh chan<- error, name string, err error) { + if err == nil { + return + } + select { + case errCh <- fmt.Errorf("%s: %w", name, err): + default: + } +} diff --git a/kube/internal/control/resolv.go b/kube/internal/control/resolv.go new file mode 100644 index 0000000..920e55f --- /dev/null +++ b/kube/internal/control/resolv.go @@ -0,0 +1,80 @@ +package control + +import ( + "net" + "os" + "strings" +) + +const ( + hostResolvPath = "/etc/resolv.conf" + systemdResolvPath = "/run/systemd/resolve/resolv.conf" +) + +// hostResolvConf is the resolver file kubelet copies into pods. +// An explicit path is kept. Otherwise a file whose nameservers are only +// loopback addresses is the systemd stub, and CoreDNS would forward to +// itself, so the upstream file is used when it names a real resolver. +func hostResolvConf(configured string) string { + return chooseResolvConf(configured, hostResolvPath, systemdResolvPath) +} + +func chooseResolvConf(configured, host, upstream string) string { + if configured != "" { + return configured + } + if nameserversAreLoopback(host) && hasNonLoopbackNameserver(upstream) { + return upstream + } + return host +} + +func nameserversAreLoopback(path string) bool { + servers, ok := nameservers(path) + if !ok || len(servers) == 0 { + return false + } + for _, ip := range servers { + if !ip.IsLoopback() { + return false + } + } + return true +} + +func hasNonLoopbackNameserver(path string) bool { + servers, ok := nameservers(path) + if !ok { + return false + } + for _, ip := range servers { + if !ip.IsLoopback() { + return true + } + } + return false +} + +func nameservers(path string) ([]net.IP, bool) { + body, err := os.ReadFile(path) // #nosec G304 -- path is the host or configured resolv.conf + if err != nil { + return nil, false + } + var servers []net.IP + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") { + continue + } + fields := strings.Fields(line) + if len(fields) < 2 || fields[0] != "nameserver" { + continue + } + ip := net.ParseIP(fields[1]) + if ip == nil { + continue + } + servers = append(servers, ip) + } + return servers, true +} diff --git a/kube/internal/control/resolv_test.go b/kube/internal/control/resolv_test.go new file mode 100644 index 0000000..5ef4e70 --- /dev/null +++ b/kube/internal/control/resolv_test.go @@ -0,0 +1,50 @@ +package control + +import ( + "os" + "path/filepath" + "testing" +) + +func TestChooseResolvConfSkipsStub(t *testing.T) { + dir := t.TempDir() + host := filepath.Join(dir, "stub.conf") + upstream := filepath.Join(dir, "upstream.conf") + writeResolv(t, host, "nameserver 127.0.0.53\n") + writeResolv(t, upstream, "nameserver 192.0.2.53\n") + if got := chooseResolvConf("", host, upstream); got != upstream { + t.Fatalf("resolv %s", got) + } + if got := chooseResolvConf(host, host, upstream); got != host { + t.Fatalf("configured resolv %s", got) + } +} + +func TestChooseResolvConfKeepsRealNameserver(t *testing.T) { + dir := t.TempDir() + host := filepath.Join(dir, "host.conf") + upstream := filepath.Join(dir, "upstream.conf") + writeResolv(t, host, "nameserver 192.0.2.1\n") + writeResolv(t, upstream, "nameserver 192.0.2.53\n") + if got := chooseResolvConf("", host, upstream); got != host { + t.Fatalf("resolv %s", got) + } +} + +func TestChooseResolvConfKeepsStubWhenUpstreamIsLoopback(t *testing.T) { + dir := t.TempDir() + host := filepath.Join(dir, "stub.conf") + upstream := filepath.Join(dir, "also-stub.conf") + writeResolv(t, host, "nameserver 127.0.0.53\n") + writeResolv(t, upstream, "nameserver 127.0.0.1\n") + if got := chooseResolvConf("", host, upstream); got != host { + t.Fatalf("resolv %s", got) + } +} + +func writeResolv(t *testing.T, path, body string) { + t.Helper() + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/kube/internal/control/selinux.go b/kube/internal/control/selinux.go new file mode 100644 index 0000000..17bfbf6 --- /dev/null +++ b/kube/internal/control/selinux.go @@ -0,0 +1,25 @@ +package control + +import ( + "errors" + + goselinux "github.com/opencontainers/selinux/go-selinux" +) + +// errNoSELinux is returned when selinux is enabled on a host without SELinux. +var errNoSELinux = errors.New("selinux is enabled on a host without SELinux") + +// hostSELinux reports whether the host is running SELinux. +var hostSELinux = func() bool { return goselinux.GetEnabled() } + +// CheckSELinux returns an error when selinux is requested on a host that +// has no SELinux. A false setting leaves the host unchanged. No policy is installed. +func CheckSELinux(enabled bool) error { + if !enabled { + return nil + } + if !hostSELinux() { + return errNoSELinux + } + return nil +} diff --git a/kube/internal/control/servicelb_test.go b/kube/internal/control/servicelb_test.go new file mode 100644 index 0000000..318851b --- /dev/null +++ b/kube/internal/control/servicelb_test.go @@ -0,0 +1,357 @@ +package control + +import ( + "context" + "net" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" +) + +func TestNodeIPForServices(t *testing.T) { + srv := config.Defaults() + srv.AdvertiseAddress = "198.51.100.8" + srv.NodeIP = "192.0.2.10" + srv.NodeExternalIP = "203.0.113.5" + got, err := nodeIP(srv) + if err != nil { + t.Fatal(err) + } + if got != "192.0.2.10" { + t.Fatalf("address %s", got) + } + srv.NodeIP = "" + orig := nodeIPForKubelet + t.Cleanup(func() { nodeIPForKubelet = orig }) + nodeIPForKubelet = func(string) (net.IP, error) { + return net.ParseIP("192.0.2.11"), nil + } + got, err = nodeIP(srv) + if err != nil { + t.Fatal(err) + } + if got != "192.0.2.11" { + t.Fatalf("address %s", got) + } + srv.NodeIP = "not-an-ip" + if _, err := nodeIP(srv); err == nil { + t.Fatal("accepted a bad node IP") + } +} + +func TestServiceLB(t *testing.T) { + if runtime.GOOS != "linux" && runtime.GOOS != "darwin" { + t.Skip(runtime.GOOS) + } + // The API processes can be started once in a process. Each case runs + // in its own process so this test can share the package with the other + // API startup test. + mode := os.Getenv("EDGELET_KUBE_SERVICE_LB") + if mode == "" { + for _, mode := range []string{"on", "off"} { + t.Run(mode, func(t *testing.T) { + cmd := exec.Command(os.Args[0], "-test.run=^TestServiceLB$", "-test.count=1", "-test.timeout=10m") + cmd.Env = append(os.Environ(), "EDGELET_KUBE_SERVICE_LB="+mode) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + }) + } + return + } + switch mode { + case "on": + testServiceLBOn(t) + case "off": + testServiceLBOff(t) + default: + t.Fatalf("unknown service load balancer case %s", mode) + } +} + +func testServiceLBOn(t *testing.T) { + var started atomic.Int32 + orig := startLoadBalancer + startLoadBalancer = func(ctx context.Context, kubeconfig, address string) error { + started.Add(1) + return orig(ctx, kubeconfig, address) + } + t.Cleanup(func() { startLoadBalancer = orig }) + + client := startControl(t, nil) + if !waitCount(&started, 1, 5*time.Second) { + t.Fatal("load balancer controller was not started") + } + createService(t, client, loadBalancerService("web")) + createService(t, client, &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: "cluster", Namespace: "default"}, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeClusterIP, + Selector: map[string]string{"app": "cluster"}, + Ports: []corev1.ServicePort{{Port: 80, TargetPort: intstr.FromInt(80)}}, + }, + }) + waitIngress(t, client, "web", "192.0.2.10", true) + cluster, err := client.CoreV1().Services("default").Get(t.Context(), "cluster", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if len(cluster.Status.LoadBalancer.Ingress) != 0 { + t.Fatalf("cluster ingress %v", cluster.Status.LoadBalancer.Ingress) + } + assertNoLoadBalancerWorkload(t, client) + if loadBalancerProcess() { + t.Fatal("load balancer process is running") + } +} + +func testServiceLBOff(t *testing.T) { + var started atomic.Int32 + orig := startLoadBalancer + startLoadBalancer = func(ctx context.Context, kubeconfig, address string) error { + started.Add(1) + return orig(ctx, kubeconfig, address) + } + t.Cleanup(func() { startLoadBalancer = orig }) + + client := startControl(t, []string{"servicelb"}) + if waitCount(&started, 1, 300*time.Millisecond) { + t.Fatal("load balancer controller was started") + } + createService(t, client, loadBalancerService("web")) + waitIngress(t, client, "web", "192.0.2.10", false) + assertNoLoadBalancerWorkload(t, client) + if loadBalancerProcess() { + t.Fatal("load balancer process is running") + } +} + +func waitCount(started *atomic.Int32, want int32, d time.Duration) bool { + deadline := time.NewTimer(d) + defer deadline.Stop() + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for started.Load() != want { + select { + case <-deadline.C: + return false + case <-ticker.C: + } + } + return true +} + +func startControl(t *testing.T, disable []string) kubernetes.Interface { + t.Helper() + dir := t.TempDir() + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + store, err := datastore.Open(ctx, datastore.Config{DataDir: dir}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + srv := config.Defaults() + srv.DataDir = dir + srv.WriteKubeconfig = filepath.Join(dir, "edgelet-kube.yaml") + srv.BindAddress = "127.0.0.1" + srv.HTTPSListenPort = freePort(t) + srv.AdvertiseAddress = "198.51.100.8" + srv.NodeIP = "192.0.2.10" + srv.NodeExternalIP = "203.0.113.5" + srv.ClusterCIDR = "10.20.0.0/16" + srv.ServiceCIDR = "10.50.0.0/16" + srv.ClusterDNS = "10.50.0.25" + srv.ClusterDomain = "example.test" + srv.NodePodCIDR = "10.20.0.0/24" + srv.DefaultLocalStoragePath = filepath.Join(dir, "volumes") + srv.Disable = disable + rt, err := Start(ctx, Config{ + Server: srv, + Store: store, + CNIConfDir: filepath.Join(dir, "net.d"), + CNIBinDir: filepath.Join(dir, "bin"), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(rt.Stop) + cfg, err := clientcmd.BuildConfigFromFlags("", rt.Kubeconfig) + if err != nil { + t.Fatal(err) + } + client, err := kubernetes.NewForConfig(cfg) + if err != nil { + t.Fatal(err) + } + return client +} + +func createService(t *testing.T, client kubernetes.Interface, svc *corev1.Service) { + t.Helper() + if _, err := client.CoreV1().Services(svc.Namespace).Create(t.Context(), svc, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } +} + +func loadBalancerService(name string) *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeLoadBalancer, + Selector: map[string]string{"app": name}, + Ports: []corev1.ServicePort{{Name: "http", Port: 80, TargetPort: intstr.FromInt(8080), Protocol: corev1.ProtocolTCP}}, + }, + } +} + +func waitIngress(t *testing.T, client kubernetes.Interface, name, ip string, assigned bool) { + t.Helper() + ctx := t.Context() + wait := 10 * time.Second + if assigned { + wait = 30 * time.Second + } + deadline := time.NewTimer(wait) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last string + for { + svc, err := client.CoreV1().Services("default").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + last = err.Error() + } else if assigned { + ingress := svc.Status.LoadBalancer.Ingress + if len(ingress) == 1 && ingress[0].IP == ip && ingress[0].Hostname == "" { + return + } + last = ingressString(ingress) + } else if len(svc.Status.LoadBalancer.Ingress) > 0 { + t.Fatalf("ingress %v", svc.Status.LoadBalancer.Ingress) + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + if assigned { + t.Fatalf("ingress %s", last) + } + return + case <-ticker.C: + } + } +} + +func ingressString(ingress []corev1.LoadBalancerIngress) string { + if len(ingress) == 0 { + return "pending" + } + parts := make([]string, len(ingress)) + for i, item := range ingress { + parts[i] = item.IP + if item.Hostname != "" { + parts[i] = item.Hostname + } + } + return strings.Join(parts, ",") +} + +func assertNoLoadBalancerWorkload(t *testing.T, client kubernetes.Interface) { + t.Helper() + ctx := t.Context() + sets, err := client.AppsV1().DaemonSets(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) + if err != nil { + t.Fatal(err) + } + if len(sets.Items) != 0 { + names := make([]string, len(sets.Items)) + for i, set := range sets.Items { + names[i] = set.Namespace + "/" + set.Name + } + t.Fatalf("daemonsets %s", strings.Join(names, ", ")) + } + pods, err := client.CoreV1().Pods(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) + if err != nil { + t.Fatal(err) + } + for _, pod := range pods.Items { + if loadBalancerWorkload(pod.Name, images(pod)) { + t.Fatalf("pod %s/%s", pod.Namespace, pod.Name) + } + } +} + +func images(pod corev1.Pod) []string { + out := make([]string, 0, len(pod.Spec.Containers)) + for _, container := range pod.Spec.Containers { + out = append(out, container.Image) + } + return out +} + +func loadBalancerWorkload(name string, images []string) bool { + fields := append([]string{name}, images...) + for _, field := range fields { + field = strings.ToLower(field) + if strings.Contains(field, "klipper-lb") || strings.Contains(field, "svclb") { + return true + } + } + return false +} + +func loadBalancerProcess() bool { + return processNamed("klipper-lb", "klipper", "svclb") +} + +func processNamed(names ...string) bool { + want := map[string]struct{}{} + for _, name := range names { + want[name] = struct{}{} + } + if _, err := os.Stat("/proc"); err == nil { + entries, err := os.ReadDir("/proc") + if err != nil { + return false + } + for _, entry := range entries { + body, err := os.ReadFile("/proc/" + entry.Name() + "/cmdline") + if err != nil || len(body) == 0 { + continue + } + argv0 := string(body) + if i := strings.IndexByte(argv0, 0); i >= 0 { + argv0 = argv0[:i] + } + if _, ok := want[filepath.Base(argv0)]; ok { + return true + } + } + return false + } + out, err := exec.Command("ps", "-ax", "-o", "comm=").Output() + if err != nil { + return false + } + for _, line := range strings.Split(string(out), "\n") { + if _, ok := want[filepath.Base(strings.TrimSpace(line))]; ok { + return true + } + } + return false +} diff --git a/kube/internal/control/start.go b/kube/internal/control/start.go new file mode 100644 index 0000000..1558a5b --- /dev/null +++ b/kube/internal/control/start.go @@ -0,0 +1,326 @@ +package control + +import ( + "context" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "strconv" + "sync" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/datastore" + "github.com/eclipse-iofog/edgelet-kube/internal/helm" + "github.com/eclipse-iofog/edgelet-kube/internal/network" + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "github.com/eclipse-iofog/edgelet-kube/internal/servicelb" + "github.com/eclipse-iofog/edgelet-kube/internal/stage" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/clientcmd" +) + +// Config selects the API processes started after the datastore is open. +type Config struct { + // Server is the loaded server configuration. + Server config.Server + // Store is the open datastore. The API processes use its endpoint. + Store *datastore.Store + // CNIConfDir is the conflist directory. Empty uses the installed directory. + CNIConfDir string + // CNIBinDir is the CNI plugin directory in the extracted bundle. + // Empty uses the directory of this executable. + CNIBinDir string + // PodNetwork writes the conflist. Nil writes the bridge conflist. + // The function does not wait on the apiserver. + PodNetwork func(dir, podCIDR string) error + // Manifests are additional YAML documents applied after the built-in addons. + // Chart objects are supplied by the caller. + Manifests []byte +} + +// Runtime is the running API processes. +type Runtime struct { + // Kubeconfig is the admin client file. + Kubeconfig string + + cancel context.CancelFunc + wg sync.WaitGroup +} + +// Stop asks the API processes to exit and waits for them to return. +func (r *Runtime) Stop() { + if r == nil || r.cancel == nil { + return + } + r.cancel() + done := make(chan struct{}) + go func() { + r.wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(20 * time.Second): + } + r.cancel = nil +} + +// Start runs kube-apiserver against the open datastore, writes the bridge +// conflist, then starts kube-controller-manager, kube-scheduler, kubelet, +// and kube-proxy. Image import has already finished. The conflist write does +// not wait on the apiserver and finishes before kubelet creates a sandbox. +// Addon manifests are applied after those processes, once the apiserver is ready. +// The Helm controller starts after that apply, and only once the HelmChart API +// is served. The load balancer controller starts after the Helm controller and +// writes the node IP onto LoadBalancer Services. kube-proxy programs forwarding. +// When servicelb is disabled, the load balancer does not start and those +// Services stay pending. When the Helm controller is disabled, its CRD is not +// applied, chart objects are not staged, and the controller does not start. +// The cluster issuers are applied after the chart objects and retry until +// cert-manager serves its CRDs. selfsigned is written whenever cert-manager +// is staged. An empty email writes no letsencrypt-prod. +func Start(ctx context.Context, cfg Config) (*Runtime, error) { + if err := CheckSELinux(cfg.Server.SELinux); err != nil { + return nil, err + } + if err := requireServer(cfg.Server); err != nil { + return nil, err + } + if cfg.Store == nil || cfg.Store.Endpoint == "" { + return nil, errors.New("datastore endpoint is empty") + } + encPath, err := encryptionConfig(cfg.Server) + if err != nil { + return nil, err + } + advertise, err := advertiseAddress(cfg.Server) + if err != nil { + return nil, err + } + paths, err := ensureCerts(cfg.Server) + if err != nil { + return nil, err + } + kArgs, err := kubeletArgs(cfg.Server, advertise, paths, cfg.CNIConfDir, cfg.CNIBinDir) + if err != nil { + return nil, err + } + pArgs, err := kubeProxyArgs(cfg.Server, advertise, paths) + if err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(ctx) + rt := &Runtime{Kubeconfig: paths.AdminKubeconfig, cancel: cancel} + errCh := make(chan error, 9) + stop := func(err error) (*Runtime, error) { + cancel() + rt.Stop() + return nil, err + } + rt.launch(ctx, "kube-apiserver", errCh, func(ctx context.Context) error { + return runAPIServer(ctx, apiServerArgs(cfg.Server, cfg.Store.Endpoint, advertise, encPath, paths)) + }) + write := cfg.PodNetwork + if write == nil { + write = network.Write + } + if err := write(flagValue(kArgs, "cni-conf-dir"), cfg.Server.NodePodCIDR); err != nil { + return stop(err) + } + if err := waitReady(ctx, paths.AdminKubeconfig, errCh); err != nil { + return stop(err) + } + controllerPort, schedulerPort := componentPorts(cfg.Server.HTTPSListenPort, 0, 0) + controllerArgs, err := controllerManagerArgs(cfg.Server, cfg.Store.LeaderElect, controllerPort, paths) + if err != nil { + return stop(err) + } + rt.launch(ctx, "kube-controller-manager", errCh, func(ctx context.Context) error { + return runControllerManager(ctx, controllerArgs) + }) + rt.launch(ctx, "kube-scheduler", errCh, func(ctx context.Context) error { + return runScheduler(ctx, schedulerArgs(cfg.Server, cfg.Store.LeaderElect, schedulerPort, paths)) + }) + if err := applyBundledPath(cfg.Server.PreferBundledBin, flagValue(kArgs, "cni-bin-dir")); err != nil { + return stop(err) + } + rt.launch(ctx, "kubelet", errCh, func(ctx context.Context) error { + return startKubelet(ctx, kArgs) + }) + rt.launch(ctx, "kube-proxy", errCh, func(ctx context.Context) error { + return startKubeProxy(ctx, pArgs) + }) + if err := waitPort(ctx, controllerPort, errCh); err != nil { + return stop(fmt.Errorf("kube-controller-manager: %w", err)) + } + if err := waitPort(ctx, schedulerPort, errCh); err != nil { + return stop(fmt.Errorf("kube-scheduler: %w", err)) + } + if err := stage.Apply(ctx, paths.AdminKubeconfig, cfg.Server, cfg.Manifests); err != nil { + return stop(err) + } + if !cfg.Server.DisableHelmController { + kubeconfig := paths.AdminKubeconfig + server := cfg.Server + rt.launch(ctx, "helm-controller", errCh, func(ctx context.Context) error { + return startHelm(ctx, kubeconfig, server) + }) + } + if !addonDisabled(cfg.Server.Disable, "servicelb") { + address, err := nodeIP(cfg.Server) + if err != nil { + return stop(err) + } + rt.launch(ctx, "servicelb", errCh, func(ctx context.Context) error { + return startLoadBalancer(ctx, paths.AdminKubeconfig, address) + }) + } + kubeconfig := paths.AdminKubeconfig + server := cfg.Server + rt.launch(ctx, "cluster-issuer", errCh, func(ctx context.Context) error { + return stage.ApplyIssuer(ctx, kubeconfig, server) + }) + return rt, nil +} + +// startLoadBalancer runs the in-process controller. +var startLoadBalancer = servicelb.Run + +// startHelm runs the in-process Helm controller after its CRD is applied. +var startHelm = helm.Run + +func addonDisabled(names []string, name string) bool { + for _, item := range names { + if item == name { + return true + } + } + return false +} + +func (r *Runtime) launch(ctx context.Context, name string, errCh chan<- error, run func(context.Context) error) { + r.wg.Add(1) + go func() { + defer r.wg.Done() + defer func() { + if rec := recover(); rec != nil { + report(errCh, name, fmt.Errorf("%v", rec)) + } + }() + err := run(ctx) + if err != nil && ctx.Err() == nil { + report(errCh, name, err) + } + }() +} + +// encryptionConfig is the secrets encryption file when startup is allowed +// and the file exists. An empty path omits the apiserver flag. +func encryptionConfig(srv config.Server) (string, error) { + enc, err := datastore.PrepareEncryption(srv.DataDir, srv.SecretsEncryption) + if err != nil { + return "", err + } + return enc.ProviderConfig, nil +} + +// PreferBundledBin sets PATH before containerd starts. +// The bridge plugin is executed by that child and locates iptables from the child's PATH. +// When prefer is true, the bundled aux directory comes first. +func PreferBundledBin(prefer bool) error { + return applyBundledPath(prefer, "") +} + +// applyBundledPath sets PATH for kubelet, kube-proxy, and the containerd child. +// prefer puts the bundle aux directory first. iptables, iptables-save, and +// iptables-restore there name xtables-nft-multi. +func applyBundledPath(prefer bool, cniBinDir string) error { + _, bin, err := cniDirs("", cniBinDir) + if err != nil { + return err + } + path := (paths.Layout{BundledBin: filepath.Join(bin, "aux")}).BinPath(prefer, os.Getenv("PATH")) + return os.Setenv("PATH", path) +} + +func requireServer(srv config.Server) error { + if srv.ClusterCIDR == "" || srv.ServiceCIDR == "" || srv.ClusterDomain == "" || srv.NodePodCIDR == "" { + return errors.New("cluster network is not configured") + } + if srv.BindAddress == "" || srv.HTTPSListenPort == 0 { + return errors.New("API bind address is not configured") + } + return nil +} + +func waitReady(ctx context.Context, kubeconfig string, errCh <-chan error) error { + deadline := time.NewTimer(2 * time.Minute) + defer deadline.Stop() + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + var last error + for { + last = readyz(ctx, kubeconfig) + if last == nil { + return nil + } + select { + case err := <-errCh: + return err + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return fmt.Errorf("kube-apiserver did not become ready: %w", last) + case <-ticker.C: + } + } +} + +func waitPort(ctx context.Context, port int, errCh <-chan error) error { + addr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) + deadline := time.NewTimer(2 * time.Minute) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + conn, err := net.DialTimeout("tcp", addr, 200*time.Millisecond) + if err == nil { + _ = conn.Close() + return nil + } + last = err + select { + case err := <-errCh: + return err + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return fmt.Errorf("port %d did not open: %w", port, last) + case <-ticker.C: + } + } +} + +func readyz(ctx context.Context, kubeconfig string) error { + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + return err + } + cfg.Timeout = 5 * time.Second + client, err := kubernetes.NewForConfig(cfg) + if err != nil { + return err + } + body, err := client.Discovery().RESTClient().Get().AbsPath("/readyz").DoRaw(ctx) + if err != nil { + return err + } + if string(body) != "ok" && len(body) == 0 { + return errors.New("readyz returned an empty body") + } + return nil +} diff --git a/kube/internal/datastore/doc.go b/kube/internal/datastore/doc.go new file mode 100644 index 0000000..eb92138 --- /dev/null +++ b/kube/internal/datastore/doc.go @@ -0,0 +1,5 @@ +// Package datastore opens kine for the runtime database. +// An empty endpoint uses SQLite. Any other endpoint is handed to kine. +// Secrets encryption writes its config only when the flag is set on a first boot. +// Kube-apiserver is not started. +package datastore diff --git a/kube/internal/datastore/encryption.go b/kube/internal/datastore/encryption.go new file mode 100644 index 0000000..fc99f22 --- /dev/null +++ b/kube/internal/datastore/encryption.go @@ -0,0 +1,165 @@ +package datastore + +import ( + "crypto/rand" + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" +) + +const encryptionFileName = "encryption-config.json" + +// Encryption is the secrets-encryption decision for one boot. +type Encryption struct { + // ProviderConfig is the encryption config file when the caller sets + // encryption-provider-config. Empty tells the caller not to set it. + ProviderConfig string +} + +// EncryptionConfigPath is the secrets encryption file for dataDir. +// An empty dataDir uses the default data directory. +func EncryptionConfigPath(dataDir string) string { + if dataDir == "" { + dataDir = bundle.DefaultDataDir + } + return filepath.Join(dataDir, "server", "cred", encryptionFileName) +} + +// PrepareEncryption applies the secrets-encryption flag before the database +// file is created. A false flag writes no key file. A true flag on a first +// boot writes encryption-config.json mode 0600, aescbc. A true flag when +// the database file exists and the key file does not is an error. A false +// flag when the key file exists is an error. An existing key file is kept. +func PrepareEncryption(dataDir string, enabled bool) (Encryption, error) { + key := EncryptionConfigPath(dataDir) + keyPresent, err := filePresent(key) + if err != nil { + return Encryption{}, err + } + if !enabled { + if keyPresent { + return Encryption{}, fmt.Errorf("secrets encryption is off and %s is present", key) + } + return Encryption{}, nil + } + if keyPresent { + return Encryption{ProviderConfig: key}, nil + } + db := StateDB(dataDir) + dbPresent, err := filePresent(db) + if err != nil { + return Encryption{}, err + } + if dbPresent { + return Encryption{}, fmt.Errorf("secrets encryption is on, %s is present, and %s is absent", db, key) + } + if err := writeEncryptionConfig(key); err != nil { + return Encryption{}, err + } + return Encryption{ProviderConfig: key}, nil +} + +func filePresent(path string) (bool, error) { + _, err := os.Stat(path) + if err == nil { + return true, nil + } + if os.IsNotExist(err) { + return false, nil + } + return false, err +} + +func writeEncryptionConfig(path string) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create encryption config directory: %w", err) + } + if err := os.Chmod(dir, 0o700); err != nil { // #nosec G302 -- directory must be owner-traversable + return fmt.Errorf("create encryption config directory: %w", err) + } + body, err := encryptionDocument() + if err != nil { + return err + } + tmp, err := os.CreateTemp(dir, ".encryption-config-*") + if err != nil { + return fmt.Errorf("write encryption config: %w", err) + } + tmpName := tmp.Name() + defer func() { + _ = os.Remove(tmpName) + }() + if _, err := tmp.Write(body); err != nil { + _ = tmp.Close() + return fmt.Errorf("write encryption config: %w", err) + } + if err := tmp.Chmod(0o600); err != nil { + _ = tmp.Close() + return fmt.Errorf("write encryption config: %w", err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("write encryption config: %w", err) + } + if err := os.Rename(tmpName, path); err != nil { + return fmt.Errorf("write encryption config: %w", err) + } + return nil +} + +type encryptionConfig struct { + Kind string `json:"kind"` + APIVersion string `json:"apiVersion"` + Resources []encryptionResource `json:"resources"` +} + +type encryptionResource struct { + Resources []string `json:"resources"` + Providers []encryptionProvider `json:"providers"` +} + +type identityProvider struct{} + +type encryptionProvider struct { + AESCBC *aesCBC `json:"aescbc,omitempty"` + Identity *identityProvider `json:"identity,omitempty"` +} + +type aesCBC struct { + Keys []encryptionKey `json:"keys"` +} + +type encryptionKey struct { + Name string `json:"name"` + Secret string `json:"secret"` +} + +func encryptionDocument() ([]byte, error) { + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, fmt.Errorf("generate encryption key: %w", err) + } + doc := encryptionConfig{ + Kind: "EncryptionConfiguration", + APIVersion: "apiserver.config.k8s.io/v1", + Resources: []encryptionResource{{ + Resources: []string{"secrets"}, + Providers: []encryptionProvider{ + {AESCBC: &aesCBC{Keys: []encryptionKey{{ + Name: "aescbckey", + Secret: base64.StdEncoding.EncodeToString(key), + }}}}, + {Identity: &identityProvider{}}, + }, + }}, + } + body, err := json.Marshal(doc) + if err != nil { + return nil, fmt.Errorf("encode encryption config: %w", err) + } + return body, nil +} diff --git a/kube/internal/datastore/encryption_test.go b/kube/internal/datastore/encryption_test.go new file mode 100644 index 0000000..13cbe59 --- /dev/null +++ b/kube/internal/datastore/encryption_test.go @@ -0,0 +1,284 @@ +package datastore + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +func shortDir(t *testing.T, name string) string { + t.Helper() + dir := filepath.Join("/tmp", fmt.Sprintf("ek-%d-%s", os.Getpid(), name)) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + return dir +} + +func TestEncryptionConfigPath(t *testing.T) { + if got := EncryptionConfigPath(""); got != "/var/lib/edgelet-kube/server/cred/encryption-config.json" { + t.Fatal(got) + } +} + +func TestEncryptionOffWritesNoFile(t *testing.T) { + dir := shortDir(t, "off") + got, err := PrepareEncryption(dir, false) + if err != nil { + t.Fatal(err) + } + if got.ProviderConfig != "" { + t.Fatalf("provider config %s", got.ProviderConfig) + } + if fileExists(EncryptionConfigPath(dir)) { + t.Fatal("wrote encryption config") + } + if _, err := os.Stat(filepath.Join(dir, "server")); !os.IsNotExist(err) { + t.Fatal("created the cred directory") + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + store, err := Open(ctx, Config{DataDir: dir}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + if store.EncryptionConfig != "" { + t.Fatalf("provider config %s", store.EncryptionConfig) + } + if store.LeaderElect { + t.Fatal("leader election is on") + } + if !fileExists(StateDB(dir)) { + t.Fatal("state.db was not created") + } + if fileExists(EncryptionConfigPath(dir)) { + t.Fatal("wrote encryption config") + } +} + +func TestEncryptionFirstBoot(t *testing.T) { + dir := shortDir(t, "boot") + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + store, err := Open(ctx, Config{DataDir: dir, SecretsEncryption: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + + path := EncryptionConfigPath(dir) + if store.EncryptionConfig != path { + t.Fatalf("provider config %s", store.EncryptionConfig) + } + if store.LeaderElect { + t.Fatal("leader election is on") + } + if store.Path != StateDB(dir) { + t.Fatalf("path %s", store.Path) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode %o", info.Mode().Perm()) + } + body, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + assertAESCBC(t, body) + + again, err := PrepareEncryption(dir, true) + if err != nil { + t.Fatal(err) + } + if again.ProviderConfig != path { + t.Fatalf("provider config %s", again.ProviderConfig) + } + kept, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(body, kept) { + t.Fatal("encryption config changed") + } + + store.Close() + reopened, err := Open(ctx, Config{DataDir: dir, SecretsEncryption: true}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(reopened.Close) + if reopened.EncryptionConfig != path { + t.Fatalf("provider config %s", reopened.EncryptionConfig) + } + kept, err = os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(body, kept) { + t.Fatal("encryption config changed") + } +} + +func TestEncryptionOnExistingDatabase(t *testing.T) { + dir := t.TempDir() + db := StateDB(dir) + if err := os.MkdirAll(filepath.Dir(db), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(db, []byte("existing"), 0o600); err != nil { + t.Fatal(err) + } + _, err := PrepareEncryption(dir, true) + if err == nil || !strings.Contains(err.Error(), "absent") { + t.Fatal(err) + } + if fileExists(EncryptionConfigPath(dir)) { + t.Fatal("wrote encryption config") + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if _, err := Open(ctx, Config{DataDir: dir, SecretsEncryption: true}); err == nil || !strings.Contains(err.Error(), "absent") { + t.Fatal(err) + } + if fileExists(EncryptionConfigPath(dir)) { + t.Fatal("wrote encryption config") + } +} + +func TestEncryptionOffKeyPresent(t *testing.T) { + dir := t.TempDir() + path := EncryptionConfigPath(dir) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + const body = "existing-key\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + _, err := PrepareEncryption(dir, false) + if err == nil || !strings.Contains(err.Error(), "is off") { + t.Fatal(err) + } + kept, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(kept) != body { + t.Fatalf("key file %q", kept) + } + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if _, err := Open(ctx, Config{DataDir: dir}); err == nil || !strings.Contains(err.Error(), "is off") { + t.Fatal(err) + } + if fileExists(StateDB(dir)) { + t.Fatal("created state.db") + } +} + +func TestEncryptionKeepsExistingKey(t *testing.T) { + dir := t.TempDir() + path := EncryptionConfigPath(dir) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + const body = "existing-key\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + db := StateDB(dir) + if err := os.MkdirAll(filepath.Dir(db), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(db, []byte("existing"), 0o600); err != nil { + t.Fatal(err) + } + + got, err := PrepareEncryption(dir, true) + if err != nil { + t.Fatal(err) + } + if got.ProviderConfig != path { + t.Fatalf("provider config %s", got.ProviderConfig) + } + kept, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(kept) != body { + t.Fatalf("key file %q", kept) + } +} + +func assertAESCBC(t *testing.T, body []byte) { + t.Helper() + var doc map[string]any + if err := json.Unmarshal(body, &doc); err != nil { + t.Fatal(err) + } + if doc["kind"] != "EncryptionConfiguration" || doc["apiVersion"] != "apiserver.config.k8s.io/v1" { + t.Fatalf("document %#v", doc) + } + resources := valueAs[[]any](t, doc["resources"]) + if len(resources) != 1 { + t.Fatalf("resources %#v", doc["resources"]) + } + resource := valueAs[map[string]any](t, resources[0]) + names := valueAs[[]any](t, resource["resources"]) + if len(names) != 1 || names[0] != "secrets" { + t.Fatalf("resources %#v", resource["resources"]) + } + providers := valueAs[[]any](t, resource["providers"]) + if len(providers) != 2 { + t.Fatalf("providers %#v", resource["providers"]) + } + first := valueAs[map[string]any](t, providers[0]) + aescbc := valueAs[map[string]any](t, first["aescbc"]) + keys := valueAs[[]any](t, aescbc["keys"]) + if len(keys) != 1 { + t.Fatalf("aescbc %#v", first["aescbc"]) + } + key := valueAs[map[string]any](t, keys[0]) + if key["name"] != "aescbckey" { + t.Fatalf("key %#v", key) + } + secret := valueAs[string](t, key["secret"]) + raw, err := base64.StdEncoding.DecodeString(secret) + if err != nil { + t.Fatal(err) + } + if len(raw) != 32 { + t.Fatalf("key length %d", len(raw)) + } + second := valueAs[map[string]any](t, providers[1]) + if _, ok := second["identity"]; !ok { + t.Fatalf("providers %#v", providers) + } + if bytes.Contains(body, []byte("secretbox")) { + t.Fatalf("document %s", body) + } +} + +func valueAs[T any](t *testing.T, v any) T { + t.Helper() + got, ok := v.(T) + if !ok { + var zero T + t.Fatalf("got %T, want %T", v, zero) + } + return got +} diff --git a/kube/internal/datastore/endpoint.go b/kube/internal/datastore/endpoint.go new file mode 100644 index 0000000..146d880 --- /dev/null +++ b/kube/internal/datastore/endpoint.go @@ -0,0 +1,84 @@ +package datastore + +import ( + "fmt" + "net/url" + "strings" + + kinetls "github.com/k3s-io/kine/pkg/tls" +) + +// prepare returns the DSN and backend TLS handed to kine. +// A non-nats endpoint is unchanged. On nats://, a credentials file is +// injected as credsFile and URL userinfo is dropped. A credentials file or +// CA adds noEmbed and the scheme stays nats://. The CA, client certificate, +// and key stay in the TLS config. bucket, replicas, and revHistory are left +// on the URL. This does not look up a server name. +func prepare(cfg Config) (string, kinetls.Config, error) { + tlsCfg := kinetls.Config{ + CAFile: cfg.CAFile, + CertFile: cfg.CertFile, + KeyFile: cfg.KeyFile, + } + endpoint := strings.TrimSpace(cfg.Endpoint) + if !natsEndpoint(endpoint) { + return endpoint, tlsCfg, nil + } + dsn, err := natsDSN(endpoint, cfg.NATSCreds, cfg.CAFile != "") + if err != nil { + return "", kinetls.Config{}, err + } + return dsn, tlsCfg, nil +} + +func natsEndpoint(endpoint string) bool { + first, _, _ := strings.Cut(endpoint, ",") + scheme, _, ok := strings.Cut(first, "://") + return ok && scheme == "nats" +} + +// natsDSN applies external NATS rules. With neither credentials nor a CA, +// the endpoint is returned unchanged, including a bare nats://. +func natsDSN(endpoint, creds string, ca bool) (string, error) { + if creds == "" && !ca { + return endpoint, nil + } + parts := strings.Split(endpoint, ",") + rewritten := make([]string, len(parts)) + for i, part := range parts { + u, err := url.Parse(part) + if err != nil { + return "", fmt.Errorf("parse datastore endpoint: %w", err) + } + if u.Scheme != "nats" { + return "", fmt.Errorf("datastore endpoint scheme %s", u.Scheme) + } + if i == 0 { + q := u.Query() + if creds != "" { + q.Set("credsFile", creds) + u.User = nil + } + if !q.Has("noEmbed") { + q.Set("noEmbed", "") + } + u.RawQuery = q.Encode() + } else if creds != "" { + u.User = nil + } + rewritten[i] = u.String() + } + return strings.Join(rewritten, ","), nil +} + +// sqliteFile returns the filesystem path in a sqlite DSN, without query parameters. +func sqliteFile(dsn string) string { + _, addr, ok := strings.Cut(dsn, "://") + if !ok { + return "" + } + if i := strings.Index(addr, "?"); i >= 0 { + addr = addr[:i] + } + return addr +} diff --git a/kube/internal/datastore/endpoint_test.go b/kube/internal/datastore/endpoint_test.go new file mode 100644 index 0000000..e9fbb49 --- /dev/null +++ b/kube/internal/datastore/endpoint_test.go @@ -0,0 +1,330 @@ +package datastore + +import ( + "context" + "errors" + "fmt" + "net" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/k3s-io/kine/pkg/drivers/sqlite" + kinetls "github.com/k3s-io/kine/pkg/tls" +) + +func TestNATSCredsDropUserinfo(t *testing.T) { + const creds = "/var/lib/edgelet-kube/nats.creds" + dsn, tlsCfg, err := prepare(Config{ + Endpoint: "nats://user:secret@nats.example:4222?bucket=kube&replicas=3&revHistory=20", + NATSCreds: creds, + CertFile: "/cert.pem", + KeyFile: "/key.pem", + }) + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(dsn) + if err != nil { + t.Fatal(err) + } + if u.Scheme != "nats" { + t.Fatalf("scheme %s", u.Scheme) + } + if u.User != nil { + t.Fatalf("userinfo %s", u.User) + } + if strings.Contains(dsn, "secret") || strings.Contains(dsn, "user:") { + t.Fatalf("userinfo remains in %s", dsn) + } + q := u.Query() + if q.Get("credsFile") != creds { + t.Fatalf("credsFile %q", q.Get("credsFile")) + } + if !q.Has("noEmbed") { + t.Fatalf("missing noEmbed in %s", dsn) + } + if q.Get("bucket") != "kube" || q.Get("replicas") != "3" || q.Get("revHistory") != "20" { + t.Fatalf("query %s", q.Encode()) + } + if tlsCfg.CertFile != "/cert.pem" || tlsCfg.KeyFile != "/key.pem" { + t.Fatalf("client certificate %+v", tlsCfg) + } + if strings.Contains(dsn, "cert.pem") || strings.Contains(dsn, "key.pem") { + t.Fatalf("certificate leaked into %s", dsn) + } +} + +func TestNATSCAKeepsScheme(t *testing.T) { + const ca = "/var/lib/edgelet-kube/nats-ca.pem" + in := "nats://user:secret@nats.example:4222?bucket=kube&replicas=2&revHistory=8" + dsn, tlsCfg, err := prepare(Config{Endpoint: in, CAFile: ca}) + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(dsn) + if err != nil { + t.Fatal(err) + } + if u.Scheme != "nats" { + t.Fatalf("scheme %s", u.Scheme) + } + if strings.HasPrefix(dsn, "tls:") { + t.Fatalf("scheme rewritten %s", dsn) + } + if !u.Query().Has("noEmbed") { + t.Fatalf("missing noEmbed in %s", dsn) + } + if u.User == nil || u.User.Username() != "user" { + t.Fatalf("userinfo %v", u.User) + } + q := u.Query() + if q.Get("bucket") != "kube" || q.Get("replicas") != "2" || q.Get("revHistory") != "8" { + t.Fatalf("query %s", q.Encode()) + } + if q.Get("credsFile") != "" { + t.Fatalf("credsFile %q", q.Get("credsFile")) + } + if tlsCfg.CAFile != ca { + t.Fatalf("CA %q", tlsCfg.CAFile) + } + if strings.Contains(dsn, ca) { + t.Fatalf("CA leaked into %s", dsn) + } + + bare, _, err := prepare(Config{Endpoint: "nats://", CAFile: ca}) + if err != nil { + t.Fatal(err) + } + u, err = url.Parse(bare) + if err != nil { + t.Fatal(err) + } + if u.Scheme != "nats" || u.Host != "" || !u.Query().Has("noEmbed") { + t.Fatalf("bare endpoint %s", bare) + } +} + +func TestNATSClientCertOptional(t *testing.T) { + in := "nats://nats.example:4222?bucket=kube&replicas=3&revHistory=4" + dsn, tlsCfg, err := prepare(Config{ + Endpoint: in, + CertFile: "/cert.pem", + KeyFile: "/key.pem", + }) + if err != nil { + t.Fatal(err) + } + if dsn != in { + t.Fatalf("dsn %s", dsn) + } + if tlsCfg != (kinetls.Config{CertFile: "/cert.pem", KeyFile: "/key.pem"}) { + t.Fatalf("tls %+v", tlsCfg) + } + + dsn, tlsCfg, err = prepare(Config{Endpoint: in}) + if err != nil { + t.Fatal(err) + } + if dsn != in { + t.Fatalf("dsn %s", dsn) + } + if tlsCfg != (kinetls.Config{}) { + t.Fatalf("tls %+v", tlsCfg) + } +} + +func TestSQLAndEtcdPassThrough(t *testing.T) { + endpoints := []string{ + "mysql://user:secret@db.example/kube", + "postgres://user:secret@db.example/kube", + "http://etcd.example:2379", + "https://etcd.example:2379", + "sqlite:///tmp/custom.db?_journal_mode=WAL", + } + for _, endpoint := range endpoints { + got, tlsCfg, err := prepare(Config{ + Endpoint: endpoint, + CAFile: "/ca.pem", + CertFile: "/cert.pem", + KeyFile: "/key.pem", + NATSCreds: "/nats.creds", + }) + if err != nil { + t.Fatal(err) + } + if got != endpoint { + t.Fatalf("dsn %s", got) + } + if strings.Contains(got, "noEmbed") || strings.Contains(got, "credsFile") { + t.Fatalf("nats parameters in %s", got) + } + if tlsCfg != (kinetls.Config{CAFile: "/ca.pem", CertFile: "/cert.pem", KeyFile: "/key.pem"}) { + t.Fatalf("tls %+v", tlsCfg) + } + } +} + +func TestAbsentFlagsDoNotQueryBus(t *testing.T) { + queried := false + prev := net.DefaultResolver + net.DefaultResolver = &net.Resolver{ + PreferGo: true, + Dial: func(context.Context, string, string) (net.Conn, error) { + queried = true + return nil, errors.New("network query") + }, + } + t.Cleanup(func() { net.DefaultResolver = prev }) + + endpoints := []string{ + "", + "postgres://db.example/kube", + "mysql://db.example/kube", + "http://etcd.example:2379", + "https://etcd.example:2379", + "sqlite:///tmp/state.db", + "nats://nats.example:4222?bucket=kine&replicas=1&revHistory=10", + "nats://", + } + for _, endpoint := range endpoints { + got, tlsCfg, err := prepare(Config{Endpoint: endpoint}) + if err != nil { + t.Fatal(err) + } + if got != endpoint { + t.Fatalf("endpoint %q became %q", endpoint, got) + } + if tlsCfg != (kinetls.Config{}) { + t.Fatalf("tls %+v", tlsCfg) + } + } + if queried { + t.Fatal("queried a network name") + } +} + +func TestNATSCredsOnSeveralHosts(t *testing.T) { + dsn, _, err := prepare(Config{ + Endpoint: "nats://user:secret@a.example:4222?bucket=kube,nats://user:secret@b.example:4222", + NATSCreds: "/nats.creds", + }) + if err != nil { + t.Fatal(err) + } + if strings.Contains(dsn, "secret") || strings.Contains(dsn, "user:") { + t.Fatalf("userinfo remains in %s", dsn) + } + parts := strings.Split(dsn, ",") + if len(parts) != 2 { + t.Fatalf("dsn %s", dsn) + } + first, err := url.Parse(parts[0]) + if err != nil { + t.Fatal(err) + } + if first.Host != "a.example:4222" || first.Query().Get("credsFile") != "/nats.creds" || !first.Query().Has("noEmbed") { + t.Fatalf("first %s", parts[0]) + } + if first.Query().Get("bucket") != "kube" { + t.Fatalf("bucket %s", first.RawQuery) + } + second, err := url.Parse(parts[1]) + if err != nil { + t.Fatal(err) + } + if second.Host != "b.example:4222" || second.User != nil { + t.Fatalf("second %s", parts[1]) + } +} + +func TestSQLiteEndpointLeaderElectionOff(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-sqlite-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + db := filepath.Join(dir, "custom.db") + dsn := "sqlite://" + db + "?" + sqlite.DefaultParams + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + store, err := Open(ctx, Config{DataDir: dir, Endpoint: dsn}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + + if store.LeaderElect { + t.Fatal("leader election is on") + } + if store.Path != db { + t.Fatalf("path %s", store.Path) + } + if journalMode(t, db) != 2 { + t.Fatal("journal mode") + } + if fileExists(filepath.Join(dir, "db", "state.db")) { + t.Fatal("created state.db") + } +} + +func TestExternalEtcdLeaderElectionOn(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-etcd-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + for _, endpoint := range []string{"http://127.0.0.1:2379", "https://127.0.0.1:2379"} { + store, err := Open(ctx, Config{DataDir: dir, Endpoint: endpoint, CAFile: "/ca.pem"}) + if err != nil { + t.Fatal(err) + } + if !store.LeaderElect { + t.Fatalf("%s leader election is off", endpoint) + } + if store.Endpoint != endpoint { + t.Fatalf("%s endpoint %s", endpoint, store.Endpoint) + } + store.Close() + } + if fileExists(filepath.Join(dir, "db", "state.db")) { + t.Fatal("created state.db") + } +} + +func TestEmptyEndpointIgnoresNATSFlags(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-empty-nats-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + store, err := Open(ctx, Config{ + DataDir: dir, + CAFile: "/ca.pem", + CertFile: "/cert.pem", + KeyFile: "/key.pem", + NATSCreds: "/nats.creds", + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + if store.LeaderElect { + t.Fatal("leader election is on") + } + if !strings.HasPrefix(store.Endpoint, "unix://") || !strings.Contains(store.Endpoint, "/kine.sock") { + t.Fatalf("endpoint %s", store.Endpoint) + } + if store.Path != filepath.Join(dir, "db", "state.db") { + t.Fatalf("path %s", store.Path) + } +} diff --git a/kube/internal/datastore/sqlite.go b/kube/internal/datastore/sqlite.go new file mode 100644 index 0000000..d52a898 --- /dev/null +++ b/kube/internal/datastore/sqlite.go @@ -0,0 +1,198 @@ +package datastore + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/k3s-io/kine/pkg/drivers/generic" + "github.com/k3s-io/kine/pkg/drivers/sqlite" + "github.com/k3s-io/kine/pkg/endpoint" + kinetls "github.com/k3s-io/kine/pkg/tls" +) + +const ( + dbDirName = "db" + dbFileName = "state.db" + socketName = "kine.sock" + + // agentDB is the agent process database. This runtime does not open it. + agentDB = "/var/lib/edgelet/edgelet.db" +) + +// Config selects the data directory and the datastore endpoint. +// An empty Endpoint uses SQLite under DataDir. +type Config struct { + // DataDir is the runtime data directory. Empty uses the default data directory. + DataDir string + // Endpoint is the datastore endpoint. Empty selects SQLite. + Endpoint string + // CAFile is the backend CA. On nats:// the client uses TLS to this CA. + CAFile string + // CertFile is the optional client certificate. + CertFile string + // KeyFile is the optional client key. + KeyFile string + // NATSCreds is the NATS credentials file. It is injected as credsFile. + NATSCreds string + // SecretsEncryption encrypts secrets at rest when true. + // A first boot writes the encryption config before the database file. + // The apiserver is not started. + SecretsEncryption bool +} + +// Store is an open kine datastore. +type Store struct { + // Path is the SQLite database file. + Path string + // Endpoint is the address kine is serving. + Endpoint string + // LeaderElect reports whether this backend wants leader election. + LeaderElect bool + // EncryptionConfig is the secrets encryption file. + // Empty tells the caller not to set encryption-provider-config. + EncryptionConfig string + + cancel context.CancelFunc + wg *sync.WaitGroup +} + +// StateDB is the SQLite file used when the datastore endpoint is empty. +func StateDB(dataDir string) string { + if dataDir == "" { + dataDir = bundle.DefaultDataDir + } + return filepath.Join(dataDir, dbDirName, dbFileName) +} + +// Open starts kine. An empty endpoint opens SQLite at StateDB with kine's WAL +// settings and leaves leader election off. Any other endpoint is handed to +// kine after NATS credentials and CA rules are applied. An empty endpoint +// does not start NATS. Secrets encryption is decided before the database +// file is created. Open does not start kube-apiserver and does not open +// the agent database. +func Open(ctx context.Context, cfg Config) (*Store, error) { + enc, err := PrepareEncryption(cfg.DataDir, cfg.SecretsEncryption) + if err != nil { + return nil, err + } + store, err := open(ctx, cfg) + if err != nil { + return nil, err + } + store.EncryptionConfig = enc.ProviderConfig + return store, nil +} + +func open(ctx context.Context, cfg Config) (*Store, error) { + if strings.TrimSpace(cfg.Endpoint) == "" { + dbPath := StateDB(cfg.DataDir) + if err := rejectAgentDB(dbPath); err != nil { + return nil, err + } + dsn := "sqlite://" + dbPath + "?" + sqlite.DefaultParams + return listen(ctx, cfg.DataDir, dsn, dbPath, kinetls.Config{}, "open sqlite datastore") + } + dsn, tlsCfg, err := prepare(cfg) + if err != nil { + return nil, err + } + scheme, _, _ := strings.Cut(dsn, "://") + if scheme == "sqlite" { + dbPath := sqliteFile(dsn) + if err := rejectAgentDB(dbPath); err != nil { + return nil, err + } + if dbPath != "" && dbPath != ":memory:" { + if err := os.MkdirAll(filepath.Dir(dbPath), 0o700); err != nil { + return nil, fmt.Errorf("create datastore directory: %w", err) + } + } + return listen(ctx, cfg.DataDir, dsn, dbPath, tlsCfg, "open sqlite datastore") + } + return listen(ctx, cfg.DataDir, dsn, "", tlsCfg, "open datastore") +} + +func listen(ctx context.Context, dataDir, dsn, dbPath string, tlsCfg kinetls.Config, errPrefix string) (*Store, error) { + dir := dataDir + if dir == "" { + dir = bundle.DefaultDataDir + } + dbDir := filepath.Join(dir, dbDirName) + if localSocket(dsn) { + if err := os.MkdirAll(dbDir, 0o700); err != nil { + return nil, fmt.Errorf("create datastore directory: %w", err) + } + } + sock := filepath.Join(dbDir, socketName) + ctx, cancel := context.WithCancel(ctx) + wg := &sync.WaitGroup{} + // Intervals match kine's built-in server defaults. + serving, err := endpoint.Listen(ctx, endpoint.Config{ + WaitGroup: wg, + Listener: "unix://" + sock, + Endpoint: dsn, + BackendTLSConfig: tlsCfg, + NotifyInterval: 5 * time.Second, + EmulatedETCDVersion: "3.6.11", + CompactTimeout: 5 * time.Second, + CompactMinRetain: 1000, + CompactBatchSize: 1000, + PollBatchSize: 500, + PollInterval: time.Second, + ConnectionPoolConfig: generic.ConnectionPoolConfig{ + MaxIdleTime: 2 * time.Minute, + }, + }) + if err != nil { + cancel() + return nil, fmt.Errorf("%s: %w", errPrefix, err) + } + return &Store{ + Path: dbPath, + Endpoint: strings.Join(serving.Endpoints, ","), + LeaderElect: serving.LeaderElect, + cancel: cancel, + wg: wg, + }, nil +} + +// localSocket reports whether kine serves this endpoint on a local socket. +// External etcd is passed through and does not listen. +func localSocket(dsn string) bool { + scheme, _, _ := strings.Cut(dsn, "://") + switch scheme { + case "http", "https", "unix", "unixs": + return false + default: + return true + } +} + +func rejectAgentDB(path string) error { + if path == "" { + return nil + } + clean := filepath.Clean(path) + if clean == agentDB || filepath.Base(clean) == filepath.Base(agentDB) { + return fmt.Errorf("refusing agent database %s", path) + } + return nil +} + +// Close stops kine and closes the database. +func (s *Store) Close() { + if s == nil || s.cancel == nil { + return + } + s.cancel() + s.cancel = nil + if s.wg != nil { + s.wg.Wait() + } +} diff --git a/kube/internal/datastore/sqlite_test.go b/kube/internal/datastore/sqlite_test.go new file mode 100644 index 0000000..f73f32b --- /dev/null +++ b/kube/internal/datastore/sqlite_test.go @@ -0,0 +1,136 @@ +package datastore + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/sirupsen/logrus" +) + +func TestMain(m *testing.M) { + logrus.SetOutput(io.Discard) + m.Run() +} + +func TestEmptyEndpointOpensSQLite(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-db-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + + agentExisted := fileExists(agentDB) + defaultExisted := fileExists(StateDB("")) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + store, err := Open(ctx, Config{DataDir: dir}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + + if store.LeaderElect { + t.Fatal("leader election is on") + } + if store.EncryptionConfig != "" { + t.Fatalf("encryption config %s", store.EncryptionConfig) + } + if fileExists(EncryptionConfigPath(dir)) { + t.Fatal("encryption config was written") + } + want := filepath.Join(dir, "db", "state.db") + if store.Path != want { + t.Fatalf("path %s", store.Path) + } + if !strings.Contains(store.Endpoint, "kine.sock") { + t.Fatalf("kine endpoint %q", store.Endpoint) + } + info, err := os.Stat(want) + if err != nil { + t.Fatal(err) + } + if info.IsDir() || info.Size() == 0 { + t.Fatalf("state.db size %d dir %v", info.Size(), info.IsDir()) + } + if mode := journalMode(t, want); mode != 2 { + t.Fatalf("journal mode %d", mode) + } + if fileExists(filepath.Join(dir, "edgelet.db")) || fileExists(filepath.Join(dir, "db", "edgelet.db")) { + t.Fatal("agent database was created in the data dir") + } + if fileExists(filepath.Join(dir, "db", "etcd")) { + t.Fatal("etcd directory was created") + } + if !agentExisted && fileExists(agentDB) { + t.Fatal("agent database was created") + } + if !defaultExisted && fileExists(StateDB("")) { + t.Fatal("default database was created for a temporary data dir") + } +} + +func TestDefaultDatabasePath(t *testing.T) { + if got := StateDB(""); got != "/var/lib/edgelet-kube/db/state.db" { + t.Fatal(got) + } +} + +func TestSetEndpointDoesNotOpenSQLite(t *testing.T) { + dir := filepath.Join("/tmp", fmt.Sprintf("edgelet-kube-db-set-%d", os.Getpid())) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + _, err := Open(ctx, Config{DataDir: dir, Endpoint: "foo://db.example/kube"}) + if err == nil { + t.Fatal("opened a set endpoint") + } + if fileExists(filepath.Join(dir, "db", "state.db")) { + t.Fatal("created state.db") + } +} + +func TestSQLiteEndpointRejectsAgentDB(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + _, err := Open(ctx, Config{Endpoint: "sqlite://" + agentDB}) + if err == nil { + t.Fatal("opened the agent database") + } +} + +func journalMode(t *testing.T, path string) byte { + t.Helper() + f, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = f.Close() + }() + hdr := make([]byte, 20) + if _, err := io.ReadFull(f, hdr); err != nil { + t.Fatal(err) + } + if string(hdr[:16]) != "SQLite format 3\x00" { + t.Fatalf("header %q", hdr[:16]) + } + return hdr[18] +} + +func fileExists(path string) bool { + _, err := os.Stat(path) + return err == nil +} diff --git a/kube/internal/dispatch/dispatch.go b/kube/internal/dispatch/dispatch.go new file mode 100644 index 0000000..6946d21 --- /dev/null +++ b/kube/internal/dispatch/dispatch.go @@ -0,0 +1,114 @@ +// Package dispatch decides which fat-runtime command the thin binary execs. +package dispatch + +import ( + "errors" + "fmt" + "path/filepath" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" +) + +// ErrUsage is returned when the arguments do not name a runtime command. +var ErrUsage = errors.New("usage: edgelet-kube server|kubectl|ctr|crictl") + +// Command is the exec the thin binary performs after extract. +type Command struct { + // Args is the argv passed to the fat runtime. Args[0] is the invoked name. + Args []string + // DataDir is where the bundle is extracted. + DataDir string +} + +// Parse reads the data directory and the fat-runtime argv from args. +// A flag wins over envDataDir. An empty envDataDir uses the default data directory. +func Parse(args []string, envDataDir string) (Command, error) { + if len(args) == 0 { + return Command{}, ErrUsage + } + dataDir, err := dataDir(args, envDataDir) + if err != nil { + return Command{}, err + } + execArgs, err := execArgs(args) + if err != nil { + return Command{}, err + } + return Command{Args: execArgs, DataDir: dataDir}, nil +} + +func dataDir(args []string, envDataDir string) (string, error) { + dir := envDataDir + if dir == "" { + dir = bundle.DefaultDataDir + } + flag := "--" + bundle.DataDirFlag + for i := 1; i < len(args); i++ { + arg := args[i] + switch { + case arg == flag: + if i+1 >= len(args) || args[i+1] == "" || strings.HasPrefix(args[i+1], "-") { + return "", fmt.Errorf("%s requires a path", bundle.DataDirFlag) + } + dir = args[i+1] + i++ + case strings.HasPrefix(arg, flag+"="): + value := strings.TrimPrefix(arg, flag+"=") + if value == "" { + return "", fmt.Errorf("%s requires a path", bundle.DataDirFlag) + } + dir = value + } + } + return dir, nil +} + +func execArgs(args []string) ([]string, error) { + base := filepath.Base(args[0]) + if bundle.Client(base) { + return append([]string(nil), args...), nil + } + command, err := firstCommand(args) + if err != nil { + return nil, err + } + if command == bundle.ServerCommand { + return append([]string(nil), args...), nil + } + if bundle.Client(command) { + return clientArgs(args, command), nil + } + return nil, ErrUsage +} + +func firstCommand(args []string) (string, error) { + flag := "--" + bundle.DataDirFlag + for i := 1; i < len(args); i++ { + arg := args[i] + switch { + case arg == "--": + return "", ErrUsage + case arg == flag: + i++ + case strings.HasPrefix(arg, flag+"="): + case strings.HasPrefix(arg, "-"): + default: + return arg, nil + } + } + return "", ErrUsage +} + +func clientArgs(args []string, name string) []string { + out := []string{name} + skipped := false + for i := 1; i < len(args); i++ { + if !skipped && args[i] == name { + skipped = true + continue + } + out = append(out, args[i]) + } + return out +} diff --git a/kube/internal/dispatch/dispatch_test.go b/kube/internal/dispatch/dispatch_test.go new file mode 100644 index 0000000..6f48cfb --- /dev/null +++ b/kube/internal/dispatch/dispatch_test.go @@ -0,0 +1,103 @@ +package dispatch + +import ( + "errors" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" +) + +func TestParseServerUsesDefaultDataDir(t *testing.T) { + got, err := Parse([]string{"edgelet-kube", "server"}, "") + if err != nil { + t.Fatal(err) + } + if got.DataDir != bundle.DefaultDataDir { + t.Fatalf("data dir %q", got.DataDir) + } + if len(got.Args) != 2 || got.Args[0] != "edgelet-kube" || got.Args[1] != "server" { + t.Fatalf("args %#v", got.Args) + } +} + +func TestParseFlagWinsOverEnv(t *testing.T) { + got, err := Parse([]string{"edgelet-kube", "--data-dir", "/from-flag", "server"}, "/from-env") + if err != nil { + t.Fatal(err) + } + if got.DataDir != "/from-flag" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestParseDataDirEqualsForm(t *testing.T) { + got, err := Parse([]string{"/usr/local/bin/edgelet-kube", "server", "--data-dir=/var/tmp/kube"}, "/from-env") + if err != nil { + t.Fatal(err) + } + if got.DataDir != "/var/tmp/kube" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestParseLastDataDirWins(t *testing.T) { + got, err := Parse([]string{"edgelet-kube", "server", "--data-dir", "/a", "--data-dir=/b"}, "") + if err != nil { + t.Fatal(err) + } + if got.DataDir != "/b" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestParseDataDirRequiresPath(t *testing.T) { + _, err := Parse([]string{"edgelet-kube", "server", "--data-dir"}, "") + if err == nil { + t.Fatal("expected an error") + } +} + +func TestParseClientSubcommand(t *testing.T) { + got, err := Parse([]string{"edgelet-kube", "--data-dir", "/data", "kubectl", "get", "pods"}, "") + if err != nil { + t.Fatal(err) + } + want := []string{"kubectl", "--data-dir", "/data", "get", "pods"} + if len(got.Args) != len(want) { + t.Fatalf("args %#v", got.Args) + } + for i := range want { + if got.Args[i] != want[i] { + t.Fatalf("args %#v", got.Args) + } + } + if got.DataDir != "/data" { + t.Fatalf("data dir %q", got.DataDir) + } +} + +func TestParseArgv0Client(t *testing.T) { + args := []string{"/usr/local/bin/crictl", "ps"} + got, err := Parse(args, "/data") + if err != nil { + t.Fatal(err) + } + if len(got.Args) != 2 || got.Args[0] != args[0] || got.Args[1] != "ps" { + t.Fatalf("args %#v", got.Args) + } +} + +func TestParseUsage(t *testing.T) { + for _, args := range [][]string{ + {"edgelet-kube"}, + {"edgelet-kube", "version"}, + {"edgelet-kube", "rotate"}, + {"edgelet-kube", "reencrypt"}, + nil, + } { + _, err := Parse(args, "") + if !errors.Is(err, ErrUsage) { + t.Fatalf("args %#v err %v", args, err) + } + } +} diff --git a/kube/internal/helm/doc.go b/kube/internal/helm/doc.go new file mode 100644 index 0000000..a8715eb --- /dev/null +++ b/kube/internal/helm/doc.go @@ -0,0 +1,2 @@ +// Package helm runs the Helm controller once the HelmChart API is served. +package helm diff --git a/kube/internal/helm/helm_test.go b/kube/internal/helm/helm_test.go new file mode 100644 index 0000000..1209685 --- /dev/null +++ b/kube/internal/helm/helm_test.go @@ -0,0 +1,117 @@ +package helm + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +func TestJobImageUsesPin(t *testing.T) { + var want string + for _, ref := range airgap.Images() { + name, _, _ := strings.Cut(ref, "@") + repo, _, ok := strings.Cut(name, ":") + if ok && strings.HasSuffix(repo, "rancher/klipper-helm") { + want = ref + } + } + if want == "" { + t.Fatal("klipper-helm is not on the image list") + } + got, err := jobImage("") + if err != nil { + t.Fatal(err) + } + if got != want { + t.Fatalf("job image %s", got) + } + prefixed, err := jobImage("registry.example:5000") + if err != nil { + t.Fatal(err) + } + if prefixed != "registry.example:5000/"+want { + t.Fatalf("job image %s", prefixed) + } + srv := config.Defaults() + srv.SystemDefaultRegistry = "registry.example:5000" + opts, port, err := controllerOptions(srv) + if err != nil { + t.Fatal(err) + } + if opts.DefaultJobImage != prefixed { + t.Fatalf("controller image %s", opts.DefaultJobImage) + } + if port != "6443" { + t.Fatalf("port %s", port) + } +} + +func TestControllerStaysDownWithoutChartAPI(t *testing.T) { + called := false + orig := startLeading + startLeading = func(context.Context, string, config.Server) error { + called = true + return nil + } + t.Cleanup(func() { startLeading = orig }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.NotFound(w, r) + })) + t.Cleanup(server.Close) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + err := Run(ctx, writeKubeconfig(t, server.URL), config.Defaults()) + if err == nil { + t.Fatal("expected the chart API to be absent") + } + if called { + t.Fatal("controller started without the chart API") + } +} + +func TestControllerStartsAfterChartAPI(t *testing.T) { + called := false + orig := startLeading + startLeading = func(context.Context, string, config.Server) error { + called = true + return nil + } + t.Cleanup(func() { startLeading = orig }) + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.URL.Path, "helm.cattle.io/v1") { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"kind":"APIResourceList","apiVersion":"v1","groupVersion":"helm.cattle.io/v1","resources":[{"name":"helmcharts","singularName":"helmchart","namespaced":true,"kind":"HelmChart","verbs":["get","list","watch"]},{"name":"helmchartconfigs","singularName":"helmchartconfig","namespaced":true,"kind":"HelmChartConfig","verbs":["get","list","watch"]}]}`)) + })) + t.Cleanup(server.Close) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := Run(ctx, writeKubeconfig(t, server.URL), config.Defaults()); err != nil { + t.Fatal(err) + } + if !called { + t.Fatal("controller was not started") + } +} + +func writeKubeconfig(t *testing.T, server string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "kubeconfig") + body := "apiVersion: v1\nkind: Config\nclusters:\n- name: t\n cluster:\n server: " + server + "\n insecure-skip-tls-verify: true\nusers:\n- name: t\n user: {}\ncontexts:\n- name: t\n context:\n cluster: t\n user: t\ncurrent-context: t\n" + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return path +} diff --git a/kube/internal/helm/run.go b/kube/internal/helm/run.go new file mode 100644 index 0000000..2fa0fc1 --- /dev/null +++ b/kube/internal/helm/run.go @@ -0,0 +1,355 @@ +package helm + +import ( + "context" + "errors" + "fmt" + "os" + "strconv" + "strings" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + helmapp "github.com/k3s-io/helm-controller/pkg/app" + helmconfig "github.com/k3s-io/helm-controller/pkg/config" + helmchart "github.com/k3s-io/helm-controller/pkg/controllers/chart" + helmapi "github.com/k3s-io/helm-controller/pkg/generated/controllers/helm.cattle.io" + "github.com/rancher/lasso/pkg/cache" + "github.com/rancher/lasso/pkg/client" + "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/v3/pkg/apply" + batchfactory "github.com/rancher/wrangler/v3/pkg/generated/controllers/batch" + corev1factory "github.com/rancher/wrangler/v3/pkg/generated/controllers/core" + rbacfactory "github.com/rancher/wrangler/v3/pkg/generated/controllers/rbac" + "github.com/rancher/wrangler/v3/pkg/generic" + "github.com/rancher/wrangler/v3/pkg/ratelimit" + "github.com/rancher/wrangler/v3/pkg/schemes" + "github.com/rancher/wrangler/v3/pkg/start" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/discovery" + "k8s.io/client-go/kubernetes" + typedv1 "k8s.io/client-go/kubernetes/typed/core/v1" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/tools/leaderelection" + "k8s.io/client-go/tools/leaderelection/resourcelock" + "k8s.io/client-go/tools/record" + "k8s.io/client-go/util/workqueue" + "k8s.io/klog/v2" +) + +const ( + controllerName = "helm-controller" + // LeaseName is the leader lock in kube-system. + LeaseName = "helm-controller" +) + +// startLeading watches HelmChart objects. It is not called until that API is served. +var startLeading = lead + +// Run starts the Helm controller. It returns before any watch when the +// HelmChart API is not served. +func Run(ctx context.Context, kubeconfig string, srv config.Server) error { + if err := waitChartAPI(ctx, kubeconfig); err != nil { + return err + } + return startLeading(ctx, kubeconfig, srv) +} + +func waitChartAPI(ctx context.Context, kubeconfig string) error { + deadline := time.NewTimer(time.Minute) + defer deadline.Stop() + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + var last error + for { + last = chartAPIServed(ctx, kubeconfig) + if last == nil { + return nil + } + select { + case <-ctx.Done(): + return fmt.Errorf("helm chart API is not served: %w", last) + case <-deadline.C: + return fmt.Errorf("helm chart API is not served: %w", last) + case <-ticker.C: + } + } +} + +func chartAPIServed(ctx context.Context, kubeconfig string) error { + if kubeconfig == "" { + return errors.New("kubeconfig is empty") + } + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + return err + } + cfg.Timeout = 5 * time.Second + disco, err := discovery.NewDiscoveryClientForConfig(cfg) + if err != nil { + return err + } + list, err := disco.ServerResourcesForGroupVersion("helm.cattle.io/v1") + if err != nil { + return err + } + have := map[string]bool{} + for _, resource := range list.APIResources { + have[resource.Name] = true + } + if !have["helmcharts"] || !have["helmchartconfigs"] { + return errors.New("helm chart API is not served") + } + return nil +} + +func lead(ctx context.Context, kubeconfig string, srv config.Server) error { + opts, port, err := controllerOptions(srv) + if err != nil { + return err + } + cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig( + &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}, + &clientcmd.ConfigOverrides{}, + ).ClientConfig() + if err != nil { + return err + } + cfg.RateLimiter = ratelimit.None + cfg.UserAgent = controllerName + kube, err := kubernetes.NewForConfig(cfg) + if err != nil { + return err + } + if err := ensureSystemNamespace(ctx, kube); err != nil { + return err + } + ctx, cancel := context.WithCancel(ctx) + defer cancel() + watching := make(chan error, 1) + go func() { + defer func() { + if rec := recover(); rec != nil { + watching <- fmt.Errorf("helm controller: %v", rec) + } + }() + leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{ + Lock: leaseLock(kube), + LeaseDuration: 45 * time.Second, + RenewDeadline: 30 * time.Second, + RetryPeriod: 2 * time.Second, + ReleaseOnCancel: true, + Callbacks: leaderelection.LeaderCallbacks{ + OnStartedLeading: func(ctx context.Context) { + watching <- runControllers(ctx, cfg, opts, port) + }, + OnStoppedLeading: func() {}, + }, + }) + }() + select { + case <-ctx.Done(): + return nil + case err := <-watching: + if err != nil { + return err + } + <-ctx.Done() + return nil + } +} + +func leaseLock(kube kubernetes.Interface) resourcelock.Interface { + lock, err := resourcelock.New( + resourcelock.LeasesResourceLock, + metav1.NamespaceSystem, + LeaseName, + kube.CoreV1(), + kube.CoordinationV1(), + resourcelock.ResourceLockConfig{Identity: leaseIdentity()}, + ) + if err != nil { + panic(err) + } + return lock +} + +func leaseIdentity() string { + name, err := os.Hostname() + if err != nil || name == "" { + return controllerName + } + return name +} + +func ensureSystemNamespace(ctx context.Context, kube kubernetes.Interface) error { + _, err := kube.CoreV1().Namespaces().Get(ctx, metav1.NamespaceSystem, metav1.GetOptions{}) + if err == nil { + return nil + } + if !apierrors.IsNotFound(err) { + return err + } + _, err = kube.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{Name: metav1.NamespaceSystem}, + }, metav1.CreateOptions{}) + if apierrors.IsAlreadyExists(err) { + return nil + } + return err +} + +func runControllers(ctx context.Context, cfg *rest.Config, opts *helmconfig.Controller, port string) error { + helmchart.DefaultJobImage = opts.DefaultJobImage + helmchart.JobResources = opts.JobResources + helmchart.JobTolerations = opts.JobTolerations + + apply, err := apply.NewForConfig(cfg) + if err != nil { + return err + } + apply = apply.WithSetOwnerReference(false, false).WithDynamicLookup().WithContext(ctx) + + scf, err := sharedFactory(cfg) + if err != nil { + return err + } + coreFactory, err := corev1factory.NewFactoryFromConfigWithOptions(cfg, &generic.FactoryOptions{ + SharedControllerFactory: scf, + }) + if err != nil { + return err + } + batchFactory, err := batchfactory.NewFactoryFromConfigWithOptions(cfg, &generic.FactoryOptions{ + SharedControllerFactory: scf, + }) + if err != nil { + return err + } + rbacFactory, err := rbacfactory.NewFactoryFromConfigWithOptions(cfg, &generic.FactoryOptions{ + SharedControllerFactory: scf, + }) + if err != nil { + return err + } + helmFactory, err := helmapi.NewFactoryFromConfigWithOptions(cfg, &generic.FactoryOptions{ + SharedControllerFactory: scf, + }) + if err != nil { + return err + } + + kube, err := kubernetes.NewForConfig(cfg) + if err != nil { + return err + } + broadcaster := record.NewBroadcaster(record.WithContext(ctx)) + go func() { + <-ctx.Done() + broadcaster.Shutdown() + }() + broadcaster.StartStructuredLogging(0) + broadcaster.StartRecordingToSink(&typedv1.EventSinkImpl{Interface: kube.CoreV1().Events("")}) + recorder := broadcaster.NewRecorder(schemes.All, corev1.EventSource{ + Component: controllerName, + Host: opts.NodeName, + }) + + helmchart.Register( + ctx, + "", + controllerName, + opts.JobClusterRole, + port, + apply, + recorder, + batchFactory.Batch().V1(), + coreFactory.Core().V1(), + helmFactory.Helm().V1(), + rbacFactory.Rbac().V1(), + ) + klog.FromContext(ctx).Info("starting helm controller", "jobImage", helmchart.DefaultJobImage, "port", port) + return start.All(ctx, 50, coreFactory, batchFactory, rbacFactory, helmFactory) +} + +func sharedFactory(cfg *rest.Config) (controller.SharedControllerFactory, error) { + rateLimit := workqueue.NewItemExponentialFailureRateLimiter(5*time.Millisecond, 60*time.Second) + clientFactory, err := client.NewSharedClientFactory(cfg, nil) + if err != nil { + return nil, err + } + cacheFactory := cache.NewSharedCachedFactory(clientFactory, nil) + return controller.NewSharedControllerFactory(cacheFactory, &controller.SharedControllerFactoryOptions{ + DefaultRateLimiter: rateLimit, + DefaultWorkers: 50, + }), nil +} + +func controllerOptions(srv config.Server) (*helmconfig.Controller, string, error) { + image, err := jobImage(srv.SystemDefaultRegistry) + if err != nil { + return nil, "", err + } + if srv.HTTPSListenPort == 0 { + return nil, "", errors.New("API port is not configured") + } + args := []string{ + "--threads=2", + "--job-cluster-role=cluster-admin", + "--default-job-image=" + image, + `--job-resources={"requests":{"cpu":"0.1","memory":"10M"},"limits":{"cpu":"32","memory":"32G"}}`, + } + args = append(args, flagArgs(srv.HelmControllerArg)...) + opts, err := helmapp.Config(args) + if err != nil { + return nil, "", err + } + if opts.DefaultJobImage == "" { + opts.DefaultJobImage = image + } + if opts.NodeName == "" { + opts.NodeName = leaseIdentity() + } + return opts, strconv.Itoa(srv.HTTPSListenPort), nil +} + +func jobImage(registry string) (string, error) { + var match string + for _, ref := range airgap.Images() { + name, _, _ := strings.Cut(ref, "@") + repo, _, ok := strings.Cut(name, ":") + if !ok { + continue + } + if repo != "docker.io/rancher/klipper-helm" && !strings.HasSuffix(repo, "/rancher/klipper-helm") { + continue + } + if match != "" && match != ref { + return "", errors.New("more than one pinned helm job image") + } + match = ref + } + if match == "" { + return "", errors.New("pinned helm job image is not on the list") + } + return airgap.Resolve(registry, match), nil +} + +func flagArgs(args []string) []string { + out := make([]string, 0, len(args)) + for _, arg := range args { + arg = strings.TrimSpace(arg) + if arg == "" { + continue + } + if !strings.HasPrefix(arg, "-") { + arg = "--" + arg + } + out = append(out, arg) + } + return out +} diff --git a/kube/internal/images/archive.go b/kube/internal/images/archive.go new file mode 100644 index 0000000..10ca449 --- /dev/null +++ b/kube/internal/images/archive.go @@ -0,0 +1,78 @@ +package images + +import ( + "compress/gzip" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/klauspost/compress/zstd" +) + +func isArchive(path string) bool { + name := strings.ToLower(filepath.Base(path)) + switch { + case strings.HasSuffix(name, ".tar.gz"), strings.HasSuffix(name, ".tgz"): + return true + case strings.HasSuffix(name, ".tar.zst"): + return true + case strings.HasSuffix(name, ".tar"): + return true + default: + return false + } +} + +func openArchive(path string) (io.ReadCloser, error) { + file, err := os.Open(path) // #nosec G304 -- path is an image archive chosen for import + if err != nil { + return nil, err + } + name := strings.ToLower(filepath.Base(path)) + switch { + case strings.HasSuffix(name, ".tar.gz"), strings.HasSuffix(name, ".tgz"): + reader, err := gzip.NewReader(file) + if err != nil { + _ = file.Close() + return nil, fmt.Errorf("open %s: %w", path, err) + } + return &multiCloser{Reader: reader, closers: []io.Closer{reader, file}}, nil + case strings.HasSuffix(name, ".tar.zst"): + reader, err := zstd.NewReader(file) + if err != nil { + _ = file.Close() + return nil, fmt.Errorf("open %s: %w", path, err) + } + return &multiCloser{Reader: reader, closers: []io.Closer{zstdCloser{reader}, file}}, nil + case strings.HasSuffix(name, ".tar"): + return file, nil + default: + _ = file.Close() + return nil, fmt.Errorf("open %s: not an image archive", path) + } +} + +type zstdCloser struct { + *zstd.Decoder +} + +func (z zstdCloser) Close() error { + z.Decoder.Close() + return nil +} + +type multiCloser struct { + io.Reader + closers []io.Closer +} + +func (m *multiCloser) Close() error { + var err error + for _, closer := range m.closers { + err = errors.Join(err, closer.Close()) + } + return err +} diff --git a/kube/internal/images/doc.go b/kube/internal/images/doc.go new file mode 100644 index 0000000..ef6338c --- /dev/null +++ b/kube/internal/images/doc.go @@ -0,0 +1,4 @@ +// Package images imports archives into the containerd k8s.io namespace and pins them. +// An empty images directory pulls the pinned list. A tar added later is imported +// without a process restart. +package images diff --git a/kube/internal/images/images_test.go b/kube/internal/images/images_test.go new file mode 100644 index 0000000..3bd4a24 --- /dev/null +++ b/kube/internal/images/images_test.go @@ -0,0 +1,510 @@ +package images + +import ( + "bytes" + "compress/gzip" + "context" + "io" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +func TestPinList(t *testing.T) { + body, err := os.ReadFile(filepath.Join("..", "..", "scripts", "airgap", "image-list.txt")) + if err != nil { + t.Fatal(err) + } + var want []string + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + want = append(want, line) + } + got := airgap.Images() + if !slices.Equal(got, want) { + t.Fatalf("list %v", got) + } + if len(got) != 12 { + t.Fatalf("got %d images", len(got)) + } + if !strings.HasPrefix(got[0], "docker.io/portainer/pause:latest@sha256:df6d2fb5") { + t.Fatal(got[0]) + } +} + +func TestEmptyDirectoryPullsAndPins(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + if err := run(ctx, dir, time.Second, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + want := airgap.ImagesFor(runtime.GOARCH) + if !slices.Equal(store.pulled(), want) { + t.Fatalf("pulled %v", store.pulled()) + } + for _, ref := range want { + if !store.isPinned(ref) { + t.Fatalf("%s is not pinned", ref) + } + } + if len(store.imported()) != 0 { + t.Fatalf("imported %v", store.imported()) + } +} + +func TestDirectoryWithFileDoesNotPull(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "readme.txt"), []byte("notes"), 0o644); err != nil { + t.Fatal(err) + } + if err := run(ctx, dir, time.Second, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } +} + +func TestArchiveIsImportedAndPinned(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + const ref = "example.com/already:1" + if err := os.WriteFile(filepath.Join(dir, "already.tar"), []byte(ref), 0o644); err != nil { + t.Fatal(err) + } + if err := run(ctx, dir, time.Second, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } + if !store.isPinned(ref) { + t.Fatalf("pinned %#v", store.pinnedCopy()) + } +} + +func TestTarAddedAfterStartIsImported(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "readme.txt"), []byte("notes"), 0o644); err != nil { + t.Fatal(err) + } + if err := run(ctx, dir, 50*time.Millisecond, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + const ref = "example.com/added:1" + if err := os.WriteFile(filepath.Join(dir, "added.tar"), []byte(ref), 0o644); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for !store.isPinned(ref) { + if time.Now().After(deadline) { + t.Fatalf("image was not imported, pinned %#v", store.pinnedCopy()) + } + time.Sleep(20 * time.Millisecond) + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } +} + +func TestOpenGzipArchive(t *testing.T) { + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "layer.tar.gz") + if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + reader, err := openArchive(path) + if err != nil { + t.Fatal(err) + } + defer func() { + _ = reader.Close() + }() + body, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + if string(body) != "hello" { + t.Fatalf("body %q", body) + } +} + +func TestPrefixRetagsPinList(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + const registry = "registry.example" + if err := run(ctx, t.TempDir(), time.Second, io.Discard, store, registry); err != nil { + t.Fatal(err) + } + pulled := airgap.ImagesFor(runtime.GOARCH) + if !slices.Equal(store.pulled(), pulled) { + t.Fatalf("pulled %v", store.pulled()) + } + if len(airgap.Images()) != 12 { + t.Fatalf("got %d images", len(airgap.Images())) + } + for _, ref := range pulled { + for _, name := range airgap.PrefixedNames(registry, ref) { + if !store.isPinned(name) { + t.Fatalf("%s is not pinned", name) + } + } + if !strings.HasPrefix(airgap.Resolve(registry, ref), registry+"/") { + t.Fatalf("resolve %s", airgap.Resolve(registry, ref)) + } + } + pauseName, _, _ := strings.Cut(airgap.Images()[0], "@") + pause := airgap.Resolve(registry, pauseName) + if pause != registry+"/"+pauseName || !store.isPinned(pause) { + t.Fatalf("pause %s pinned %v", pause, store.isPinned(pause)) + } +} + +func TestEmptyRegistryLeavesPinList(t *testing.T) { + for _, registry := range []string{"", " ", "/"} { + if !slices.Equal(airgap.Names(registry), airgap.Images()) { + t.Fatalf("registry %q changed the pin list", registry) + } + } + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + if err := run(ctx, t.TempDir(), time.Second, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + want := airgap.ImagesFor(runtime.GOARCH) + if !slices.Equal(store.pulled(), want) { + t.Fatalf("pulled %v", store.pulled()) + } + for _, ref := range want { + if !store.isPinned(ref) { + t.Fatalf("%s is not pinned", ref) + } + } +} + +func TestOperatorImageIsNotRewritten(t *testing.T) { + const registry = "registry.example" + const operator = "example.com/operator-app:9" + if airgap.Resolve(registry, operator) != operator { + t.Fatalf("resolve %s", airgap.Resolve(registry, operator)) + } + if len(airgap.PrefixedNames(registry, operator)) != 0 { + t.Fatal("operator image was prefixed") + } + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "operator.tar"), []byte(operator), 0o644); err != nil { + t.Fatal(err) + } + if err := run(ctx, dir, time.Second, io.Discard, store, registry); err != nil { + t.Fatal(err) + } + if !store.isPinned(operator) { + t.Fatal("operator image was not pinned") + } + for name := range store.pinnedCopy() { + if strings.Contains(name, registry) { + t.Fatalf("rewrote %s", name) + } + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } +} + +func TestImportRetagsListedImage(t *testing.T) { + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + dir := t.TempDir() + ref := airgap.Images()[0] + if err := os.WriteFile(filepath.Join(dir, "pause.tar"), []byte(ref), 0o644); err != nil { + t.Fatal(err) + } + const registry = "registry.example" + if err := run(ctx, dir, time.Second, io.Discard, store, registry); err != nil { + t.Fatal(err) + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } + for _, name := range airgap.PrefixedNames(registry, ref) { + if !store.isPinned(name) { + t.Fatalf("%s is not pinned", name) + } + } + if !store.isPinned(ref) { + t.Fatal("imported name was not pinned") + } +} + +func TestEmptyDirectoryAndArchivePinTheSameNames(t *testing.T) { + if Namespace != "k8s.io" { + t.Fatal(Namespace) + } + empty := pinnedNames(t, t.TempDir(), "") + dir := t.TempDir() + writeAirgapArchive(t, dir) + seeded := pinnedNames(t, dir, "") + if !slices.Equal(empty, seeded) { + t.Fatalf("empty %v archive %v", empty, seeded) + } + want := slices.Clone(airgap.ImagesFor(runtime.GOARCH)) + slices.Sort(want) + if !slices.Equal(empty, want) { + t.Fatalf("pinned %v", empty) + } +} + +func TestRegistryPauseNameIsPinnedOnBothPaths(t *testing.T) { + const registry = "registry.example" + pauseName, _, _ := strings.Cut(airgap.Images()[0], "@") + pause := airgap.Resolve(registry, pauseName) + if pause != registry+"/"+pauseName { + t.Fatalf("pause %s", pause) + } + empty := pinnedNames(t, t.TempDir(), registry) + dir := t.TempDir() + writeAirgapArchive(t, dir) + seeded := pinnedNames(t, dir, registry) + if !slices.Contains(empty, pause) || !slices.Contains(seeded, pause) { + t.Fatalf("empty %v archive %v", empty, seeded) + } + if !slices.Equal(empty, seeded) { + t.Fatalf("empty %v archive %v", empty, seeded) + } +} + +func pinnedNames(t *testing.T, dir, registry string) []string { + t.Helper() + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + if err := run(ctx, dir, time.Second, io.Discard, store, registry); err != nil { + t.Fatal(err) + } + names := store.pinnedNames() + if len(store.imported()) > 0 && len(store.pulled()) > 0 { + t.Fatalf("pulled %v and imported %v", store.pulled(), store.imported()) + } + return names +} + +func writeAirgapArchive(t *testing.T, dir string) { + t.Helper() + var raw bytes.Buffer + if err := airgap.WriteTar(&raw, airgap.ImagesFor(runtime.GOARCH)); err != nil { + t.Fatal(err) + } + if err := airgap.Compress(filepath.Join(dir, airgap.AssetAMD64), bytes.NewReader(raw.Bytes())); err != nil { + t.Fatal(err) + } +} + +func TestAirgapArchiveImportsPinList(t *testing.T) { + if Namespace != "k8s.io" { + t.Fatal(Namespace) + } + dir := t.TempDir() + archive := filepath.Join(dir, airgap.AssetAMD64) + var raw bytes.Buffer + if err := airgap.WriteTar(&raw, airgap.Images()); err != nil { + t.Fatal(err) + } + if err := airgap.Compress(archive, bytes.NewReader(raw.Bytes())); err != nil { + t.Fatal(err) + } + names, err := airgap.ListFile(archive) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(names, airgap.Images()) { + t.Fatalf("names %v", names) + } + if len(names) != 12 { + t.Fatalf("got %d images", len(names)) + } + store := newMemStore() + ctx, cancel := context.WithCancel(t.Context()) + t.Cleanup(cancel) + if err := run(ctx, dir, time.Second, io.Discard, store, ""); err != nil { + t.Fatal(err) + } + if len(store.pulled()) != 0 { + t.Fatalf("pulled %v", store.pulled()) + } + if !slices.Equal(store.importedRefs(), airgap.Images()) { + t.Fatalf("imported %v", store.importedRefs()) + } + if len(store.pinnedCopy()) != len(airgap.Images()) { + t.Fatalf("pinned %#v", store.pinnedCopy()) + } + for _, ref := range airgap.Images() { + if !store.isPinned(ref) { + t.Fatalf("%s is not pinned", ref) + } + } +} + +func TestArchiveNames(t *testing.T) { + for _, name := range []string{"a.tar", "a.TAR", "a.tar.gz", "a.tgz", "a.tar.zst"} { + if !isArchive(name) { + t.Fatalf("%s should be an archive", name) + } + } + for _, name := range []string{"a.txt", "a.tar.gz.txt", "image-list.txt"} { + if isArchive(name) { + t.Fatalf("%s should not be an archive", name) + } + } +} + +type memStore struct { + mu sync.Mutex + pulls []string + imports []string + importRefs []string + present map[string]bool + pinned map[string]bool +} + +func newMemStore() *memStore { + return &memStore{ + present: map[string]bool{}, + pinned: map[string]bool{}, + } +} + +func (m *memStore) Pull(_ context.Context, ref string) error { + m.mu.Lock() + defer m.mu.Unlock() + m.pulls = append(m.pulls, ref) + m.present[ref] = true + return nil +} + +func (m *memStore) Import(_ context.Context, path string) ([]string, error) { + names, err := airgap.ListFile(path) + if err != nil { + body, readErr := os.ReadFile(path) + if readErr != nil { + return nil, readErr + } + names = []string{strings.TrimSpace(string(body))} + } + m.mu.Lock() + defer m.mu.Unlock() + m.imports = append(m.imports, path) + m.importRefs = append(m.importRefs, names...) + for _, name := range names { + m.present[name] = true + } + return names, nil +} + +func (m *memStore) Retag(_ context.Context, from, to string) error { + if from == to { + return nil + } + m.mu.Lock() + defer m.mu.Unlock() + if !m.present[from] { + return os.ErrNotExist + } + m.present[to] = true + return nil +} + +func (m *memStore) Pin(_ context.Context, names []string) error { + m.mu.Lock() + defer m.mu.Unlock() + for _, name := range names { + if !m.present[name] { + return os.ErrNotExist + } + m.pinned[name] = true + } + return nil +} + +func (m *memStore) Close() error { + return nil +} + +func (m *memStore) pulled() []string { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.pulls) +} + +func (m *memStore) imported() []string { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.imports) +} + +func (m *memStore) importedRefs() []string { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.importRefs) +} + +func (m *memStore) isPinned(name string) bool { + m.mu.Lock() + defer m.mu.Unlock() + return m.pinned[name] +} + +func (m *memStore) pinnedNames() []string { + m.mu.Lock() + defer m.mu.Unlock() + names := make([]string, 0, len(m.pinned)) + for name, pinned := range m.pinned { + if pinned { + names = append(names, name) + } + } + slices.Sort(names) + return names +} + +func (m *memStore) pinnedCopy() map[string]bool { + m.mu.Lock() + defer m.mu.Unlock() + out := make(map[string]bool, len(m.pinned)) + for name, pinned := range m.pinned { + out[name] = pinned + } + return out +} diff --git a/kube/internal/images/run.go b/kube/internal/images/run.go new file mode 100644 index 0000000..d4a9149 --- /dev/null +++ b/kube/internal/images/run.go @@ -0,0 +1,277 @@ +package images + +import ( + "context" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "sync" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/paths" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "github.com/fsnotify/fsnotify" +) + +// Config selects the images directory and the containerd socket. +type Config struct { + // Dir is the images directory. An empty value uses paths.ImagesDir. + Dir string + // Socket is the containerd gRPC socket. + Socket string + // Pull replaces the registry fetch. A nil Pull uses the CRI image service. + Pull func(ctx context.Context, ref string) error + // Registry is the prefix applied to pin-list images. Empty leaves those names unchanged. + Registry string + // Settle is how long a new archive must stay unchanged before import. + // An empty value waits one second. + Settle time.Duration + // Log receives watch errors. A nil Log uses standard error. + Log io.Writer +} + +type fileState struct { + size int64 + mod time.Time +} + +type runner struct { + dir string + store Store + settle time.Duration + log io.Writer + registry string + + mu sync.Mutex + seen map[string]fileState +} + +// Run imports archives from the images directory into containerd and pins them. +// An empty directory pulls the pinned list. Run returns after that initial import. +// The directory stays watched until ctx is canceled, so a tar added later is +// imported without a process restart. Kubelet is not started. +func Run(ctx context.Context, cfg Config) error { + if cfg.Dir == "" { + cfg.Dir = paths.ImagesDir + } + if cfg.Settle <= 0 { + cfg.Settle = time.Second + } + if cfg.Log == nil { + cfg.Log = os.Stderr + } + store, err := openStore(cfg.Socket) + if err != nil { + return err + } + if cfg.Pull != nil { + store = &pullFunc{Store: store, pull: cfg.Pull} + } + return run(ctx, cfg.Dir, cfg.Settle, cfg.Log, store, cfg.Registry) +} + +type pullFunc struct { + Store + pull func(context.Context, string) error +} + +func (p *pullFunc) Pull(ctx context.Context, ref string) error { + return p.pull(ctx, ref) +} + +func run(ctx context.Context, dir string, settle time.Duration, log io.Writer, store Store, registry string) error { + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- image import directory is operator-visible + _ = store.Close() + return fmt.Errorf("create images directory: %w", err) + } + r := &runner{ + dir: dir, + store: store, + settle: settle, + log: log, + registry: registry, + seen: map[string]fileState{}, + } + watcher, err := fsnotify.NewWatcher() + if err != nil { + _ = store.Close() + return fmt.Errorf("watch images directory: %w", err) + } + if err := watcher.Add(dir); err != nil { + _ = watcher.Close() + _ = store.Close() + return fmt.Errorf("watch images directory: %w", err) + } + done := make(chan struct{}) + go func() { + r.loop(ctx, watcher) + close(done) + }() + err = r.scan(ctx) + if err != nil { + _ = watcher.Close() + <-done + return err + } + go func() { + <-ctx.Done() + _ = watcher.Close() + }() + return nil +} + +func (r *runner) scan(ctx context.Context) error { + entries, err := os.ReadDir(r.dir) + if err != nil { + return fmt.Errorf("read images directory: %w", err) + } + var archives []string + visible := 0 + for _, entry := range entries { + name := entry.Name() + if name == "" || strings.HasPrefix(name, ".") { + continue + } + visible++ + path := filepath.Join(r.dir, name) + if entry.IsDir() || !isArchive(name) { + continue + } + archives = append(archives, path) + } + if visible == 0 { + return r.pullList(ctx) + } + for _, path := range archives { + if err := r.importFile(ctx, path); err != nil { + return err + } + } + return nil +} + +func (r *runner) pullList(ctx context.Context) error { + for _, ref := range airgap.ImagesFor(runtime.GOARCH) { + if err := ctx.Err(); err != nil { + return err + } + if err := r.store.Pull(ctx, ref); err != nil { + return err + } + names, err := r.tag(ctx, []string{ref}) + if err != nil { + return err + } + if err := r.store.Pin(ctx, names); err != nil { + return err + } + } + return nil +} + +func (r *runner) importFile(ctx context.Context, path string) error { + info, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if info.IsDir() || !isArchive(path) { + return nil + } + r.mu.Lock() + prev, ok := r.seen[path] + r.mu.Unlock() + if ok && prev.size == info.Size() && prev.mod.Equal(info.ModTime()) { + return nil + } + names, err := r.store.Import(ctx, path) + if err != nil { + return err + } + names, err = r.tag(ctx, names) + if err != nil { + return err + } + if err := r.store.Pin(ctx, names); err != nil { + return err + } + r.mu.Lock() + r.seen[path] = fileState{size: info.Size(), mod: info.ModTime()} + r.mu.Unlock() + return nil +} + +func (r *runner) tag(ctx context.Context, names []string) ([]string, error) { + out := slices.Clone(names) + for _, name := range names { + for _, alias := range airgap.PrefixedNames(r.registry, name) { + if slices.Contains(out, alias) { + continue + } + if err := r.store.Retag(ctx, name, alias); err != nil { + return nil, err + } + out = append(out, alias) + } + } + return out, nil +} + +func (r *runner) loop(ctx context.Context, watcher *fsnotify.Watcher) { + defer func() { + _ = watcher.Close() + _ = r.store.Close() + }() + var timer *time.Timer + var timerC <-chan time.Time + pending := map[string]struct{}{} + for { + select { + case <-ctx.Done(): + return + case err, ok := <-watcher.Errors: + if !ok { + return + } + _, _ = fmt.Fprintf(r.log, "edgelet-kube: watch images: %v\n", err) + case event, ok := <-watcher.Events: + if !ok { + return + } + if !event.Has(fsnotify.Create) && !event.Has(fsnotify.Write) && !event.Has(fsnotify.Rename) { + continue + } + if !isArchive(event.Name) { + continue + } + pending[event.Name] = struct{}{} + if timer == nil { + timer = time.NewTimer(r.settle) + timerC = timer.C + } else { + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + timer.Reset(r.settle) + } + case <-timerC: + timer = nil + timerC = nil + for path := range pending { + delete(pending, path) + if err := r.importFile(ctx, path); err != nil && ctx.Err() == nil { + _, _ = fmt.Fprintf(r.log, "edgelet-kube: import %s: %v\n", path, err) + } + } + } + } +} diff --git a/kube/internal/images/store.go b/kube/internal/images/store.go new file mode 100644 index 0000000..16cfd5c --- /dev/null +++ b/kube/internal/images/store.go @@ -0,0 +1,25 @@ +package images + +import "context" + +const ( + // Namespace is the containerd namespace kubelet uses. + Namespace = "k8s.io" + // PinnedLabel marks an image so garbage collection does not remove it. + PinnedLabel = "io.cri-containerd.pinned" + // PinnedValue is the value of PinnedLabel. + PinnedValue = "pinned" + + managedLabel = "io.cri-containerd.image" + managedValue = "managed" +) + +// Store pulls, imports, and pins images in Namespace. +type Store interface { + Pull(ctx context.Context, ref string) error + Import(ctx context.Context, path string) ([]string, error) + // Retag copies from to another name in Namespace. + Retag(ctx context.Context, from, to string) error + Pin(ctx context.Context, names []string) error + Close() error +} diff --git a/kube/internal/images/store_linux.go b/kube/internal/images/store_linux.go new file mode 100644 index 0000000..a253b28 --- /dev/null +++ b/kube/internal/images/store_linux.go @@ -0,0 +1,185 @@ +//go:build linux && cgo + +package images + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + containerd "github.com/containerd/containerd/v2/client" + ctdimages "github.com/containerd/containerd/v2/core/images" + "github.com/containerd/containerd/v2/pkg/namespaces" + "github.com/containerd/errdefs" + kubecontainerd "github.com/eclipse-iofog/edgelet-kube/internal/containerd" + "google.golang.org/grpc" + runtimev1 "k8s.io/cri-api/pkg/apis/runtime/v1" +) + +type criStore struct { + client *containerd.Client + conn *grpc.ClientConn + images runtimev1.ImageServiceClient +} + +func openStore(socket string) (Store, error) { + if socket == "" { + return nil, errors.New("containerd socket is required") + } + client, err := containerd.New(socket, containerd.WithDefaultNamespace(Namespace)) + if err != nil { + return nil, fmt.Errorf("containerd client: %w", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := client.NamespaceService().Create(ctx, Namespace, nil); err != nil && !errdefs.IsAlreadyExists(err) { + _ = client.Close() + return nil, fmt.Errorf("containerd namespace: %w", err) + } + conn, err := kubecontainerd.Dial(socket) + if err != nil { + _ = client.Close() + return nil, err + } + return &criStore{ + client: client, + conn: conn, + images: runtimev1.NewImageServiceClient(conn), + }, nil +} + +func (s *criStore) Pull(ctx context.Context, ref string) error { + if _, err := s.images.PullImage(ctx, &runtimev1.PullImageRequest{ + Image: &runtimev1.ImageSpec{Image: ref}, + }); err != nil { + return fmt.Errorf("pull %s: %w", ref, err) + } + // The image service records the tag and the digest separately. Keep the + // requested name, and the tag without a digest, so a later retag can find it. + return s.keepNames(ctx, ref) +} + +func (s *criStore) keepNames(ctx context.Context, ref string) error { + ctx = namespaces.WithNamespace(ctx, Namespace) + service := s.client.ImageService() + source, err := imageByName(ctx, service, ref) + if err != nil { + return fmt.Errorf("pull %s: %w", ref, err) + } + tag, _, _ := strings.Cut(ref, "@") + for _, name := range []string{ref, tag} { + if name == "" || name == source.Name { + continue + } + image := source + image.Name = name + if _, err := service.Create(ctx, image); err != nil && !errdefs.IsAlreadyExists(err) { + return fmt.Errorf("pull %s: %w", name, err) + } + } + return nil +} + +func imageByName(ctx context.Context, service ctdimages.Store, ref string) (ctdimages.Image, error) { + if image, err := service.Get(ctx, ref); err == nil || !errdefs.IsNotFound(err) { + return image, err + } + tag, digest, hasDigest := strings.Cut(ref, "@") + if image, err := service.Get(ctx, tag); err == nil || !errdefs.IsNotFound(err) { + return image, err + } + if hasDigest { + if i := strings.LastIndex(tag, ":"); i > 0 { + if image, err := service.Get(ctx, tag[:i]+"@"+digest); err == nil || !errdefs.IsNotFound(err) { + return image, err + } + } + } + return ctdimages.Image{}, errdefs.ErrNotFound +} + +func (s *criStore) Import(ctx context.Context, path string) ([]string, error) { + reader, err := openArchive(path) + if err != nil { + return nil, err + } + defer func() { + _ = reader.Close() + }() + ctx = namespaces.WithNamespace(ctx, Namespace) + imported, err := s.client.Import(ctx, reader, containerd.WithAllPlatforms(true)) + if err != nil { + return nil, fmt.Errorf("import %s: %w", path, err) + } + names := make([]string, 0, len(imported)) + for _, image := range imported { + if image.Name != "" { + names = append(names, image.Name) + } + } + if len(names) == 0 { + return nil, fmt.Errorf("import %s: archive contained no images", path) + } + return names, nil +} + +func (s *criStore) Retag(ctx context.Context, from, to string) error { + if from == to { + return nil + } + ctx = namespaces.WithNamespace(ctx, Namespace) + service := s.client.ImageService() + image, err := service.Get(ctx, from) + if err != nil { + return fmt.Errorf("retag %s: %w", from, err) + } + image.Name = to + if _, err := service.Create(ctx, image); err != nil { + if !errdefs.IsAlreadyExists(err) { + return fmt.Errorf("retag %s: %w", to, err) + } + if err := service.Delete(ctx, to); err != nil { + return fmt.Errorf("retag %s: %w", to, err) + } + if _, err := service.Create(ctx, image); err != nil { + return fmt.Errorf("retag %s: %w", to, err) + } + } + return nil +} + +func (s *criStore) Pin(ctx context.Context, names []string) error { + ctx = namespaces.WithNamespace(ctx, Namespace) + service := s.client.ImageService() + for _, name := range names { + image, err := service.Get(ctx, name) + if err != nil { + return fmt.Errorf("pin %s: %w", name, err) + } + if image.Labels[PinnedLabel] == PinnedValue && image.Labels[managedLabel] == managedValue { + continue + } + if image.Labels == nil { + image.Labels = map[string]string{} + } + image.Labels[PinnedLabel] = PinnedValue + image.Labels[managedLabel] = managedValue + if _, err := service.Update(ctx, image, "labels"); err != nil { + return fmt.Errorf("pin %s: %w", name, err) + } + } + return nil +} + +func (s *criStore) Close() error { + var err error + if s.conn != nil { + err = s.conn.Close() + } + if s.client != nil { + err = errors.Join(err, s.client.Close()) + } + return err +} diff --git a/kube/internal/images/store_stub.go b/kube/internal/images/store_stub.go new file mode 100644 index 0000000..b5d954d --- /dev/null +++ b/kube/internal/images/store_stub.go @@ -0,0 +1,9 @@ +//go:build !linux || !cgo + +package images + +import "errors" + +func openStore(string) (Store, error) { + return nil, errors.New("image import requires linux") +} diff --git a/kube/internal/kubectl/kubectl.go b/kube/internal/kubectl/kubectl.go new file mode 100644 index 0000000..12e155d --- /dev/null +++ b/kube/internal/kubectl/kubectl.go @@ -0,0 +1,74 @@ +// Package kubectl runs the Kubernetes client embedded in the fat runtime. +package kubectl + +import ( + "os" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/version" + "k8s.io/kubectl/pkg/cmd" +) + +// adminKubeconfig is the admin file used when kubectl is given no kubeconfig. +var adminKubeconfig = config.DefaultKubeconfig + +// Run executes kubectl with args. Runtime flags that belong to this process +// are removed before the client sees them. When neither KUBECONFIG nor +// --kubeconfig is set, the admin file is used if it exists. +func Run(args []string) error { + version.Pin() + args = withoutRuntimeFlags(args) + if err := useAdminKubeconfig(args); err != nil { + return err + } + command := cmd.NewDefaultKubectlCommand() + command.SetArgs(args) + return command.Execute() +} + +func useAdminKubeconfig(args []string) error { + if os.Getenv("KUBECONFIG") != "" || hasKubeconfigFlag(args) { + return nil + } + info, err := os.Stat(adminKubeconfig) + if err != nil { + if os.IsNotExist(err) { + return nil + } + return err + } + if info.IsDir() { + return nil + } + return os.Setenv("KUBECONFIG", adminKubeconfig) +} + +func hasKubeconfigFlag(args []string) bool { + for _, arg := range args { + if arg == "--" { + return false + } + if arg == "--kubeconfig" || strings.HasPrefix(arg, "--kubeconfig=") { + return true + } + } + return false +} + +func withoutRuntimeFlags(args []string) []string { + flag := "--" + bundle.DataDirFlag + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + arg := args[i] + switch { + case arg == flag: + i++ + case strings.HasPrefix(arg, flag+"="): + default: + out = append(out, arg) + } + } + return out +} diff --git a/kube/internal/kubectl/kubectl_test.go b/kube/internal/kubectl/kubectl_test.go new file mode 100644 index 0000000..da1a7a3 --- /dev/null +++ b/kube/internal/kubectl/kubectl_test.go @@ -0,0 +1,112 @@ +package kubectl + +import ( + "bytes" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +func TestVersionReportsPin(t *testing.T) { + stdout, stderr := capture(t, func() { + if err := Run([]string{"--data-dir", t.TempDir(), "version", "--client=true"}); err != nil { + t.Fatal(err) + } + }) + got := stdout + stderr + if !strings.Contains(got, airgap.KubernetesVersion()) { + t.Fatalf("kubectl version\n%s", got) + } +} + +func TestDataDirFlagIsRemoved(t *testing.T) { + got := withoutRuntimeFlags([]string{"--data-dir", "/var/lib/edgelet-kube", "version", "--client=true"}) + if strings.Join(got, " ") != "version --client=true" { + t.Fatalf("args %v", got) + } + got = withoutRuntimeFlags([]string{"--data-dir=/tmp/work", "get", "nodes"}) + if strings.Join(got, " ") != "get nodes" { + t.Fatalf("args %v", got) + } +} + +func TestAdminKubeconfigIsUsedWhenUnset(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "edgelet-kube.yaml") + if err := os.WriteFile(path, []byte("apiVersion: v1\n"), 0o600); err != nil { + t.Fatal(err) + } + old := adminKubeconfig + adminKubeconfig = path + t.Cleanup(func() { adminKubeconfig = old }) + t.Setenv("KUBECONFIG", "") + if err := useAdminKubeconfig([]string{"get", "nodes"}); err != nil { + t.Fatal(err) + } + if os.Getenv("KUBECONFIG") != path { + t.Fatalf("KUBECONFIG %s", os.Getenv("KUBECONFIG")) + } +} + +func TestKubeconfigFlagAndEnvWin(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "edgelet-kube.yaml") + if err := os.WriteFile(path, []byte("apiVersion: v1\n"), 0o600); err != nil { + t.Fatal(err) + } + old := adminKubeconfig + adminKubeconfig = path + t.Cleanup(func() { adminKubeconfig = old }) + + t.Setenv("KUBECONFIG", "") + if err := useAdminKubeconfig([]string{"--kubeconfig", "/tmp/other", "get", "nodes"}); err != nil { + t.Fatal(err) + } + if os.Getenv("KUBECONFIG") != "" { + t.Fatalf("KUBECONFIG %s", os.Getenv("KUBECONFIG")) + } + if err := useAdminKubeconfig([]string{"--kubeconfig=/tmp/other", "get", "nodes"}); err != nil { + t.Fatal(err) + } + if os.Getenv("KUBECONFIG") != "" { + t.Fatalf("KUBECONFIG %s", os.Getenv("KUBECONFIG")) + } + + t.Setenv("KUBECONFIG", "/tmp/already") + if err := useAdminKubeconfig([]string{"get", "nodes"}); err != nil { + t.Fatal(err) + } + if os.Getenv("KUBECONFIG") != "/tmp/already" { + t.Fatalf("KUBECONFIG %s", os.Getenv("KUBECONFIG")) + } +} + +func capture(t *testing.T, fn func()) (string, string) { + t.Helper() + outR, outW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + errR, errW, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + oldOut, oldErr := os.Stdout, os.Stderr + os.Stdout, os.Stderr = outW, errW + fn() + _ = outW.Close() + _ = errW.Close() + os.Stdout, os.Stderr = oldOut, oldErr + var stdout, stderr bytes.Buffer + if _, err := io.Copy(&stdout, outR); err != nil { + t.Fatal(err) + } + if _, err := io.Copy(&stderr, errR); err != nil { + t.Fatal(err) + } + return stdout.String(), stderr.String() +} diff --git a/kube/internal/network/write.go b/kube/internal/network/write.go new file mode 100644 index 0000000..faf693a --- /dev/null +++ b/kube/internal/network/write.go @@ -0,0 +1,93 @@ +// Package network writes the node bridge conflist. +// Write does not contact the apiserver. It finishes before kubelet creates a sandbox. +package network + +import ( + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" +) + +// FileName is the only conflist in the CNI configuration directory. +const FileName = "10-bridge.conflist" + +type conflist struct { + CNIVersion string `json:"cniVersion"` + Name string `json:"name"` + Plugins []plugin `json:"plugins"` +} + +type plugin struct { + Type string `json:"type"` + Bridge string `json:"bridge,omitempty"` + IsGateway bool `json:"isGateway,omitempty"` + IPMasq bool `json:"ipMasq,omitempty"` + HairpinMode bool `json:"hairpinMode,omitempty"` + IPAM *ipam `json:"ipam,omitempty"` + Capabilities map[string]bool `json:"capabilities,omitempty"` +} + +type ipam struct { + Type string `json:"type"` + Ranges [][]subnet `json:"ranges"` + Routes []route `json:"routes,omitempty"` +} + +type subnet struct { + Subnet string `json:"subnet"` +} + +type route struct { + Dst string `json:"dst"` +} + +// Write writes one bridge conflist into dir. +// podCIDR is the node pod range. Hairpin stays on. The write does not contact the apiserver. +func Write(dir, podCIDR string) error { + if _, _, err := net.ParseCIDR(podCIDR); err != nil { + return fmt.Errorf("node pod network %q is not a network", podCIDR) + } + body, err := json.Marshal(conflist{ + CNIVersion: "1.0.0", + Name: "bridge", + Plugins: []plugin{ + { + Type: "bridge", + Bridge: "cni0", + IsGateway: true, + IPMasq: true, + HairpinMode: true, + IPAM: &ipam{ + Type: "host-local", + Ranges: [][]subnet{ + {{Subnet: podCIDR}}, + }, + Routes: []route{{Dst: "0.0.0.0/0"}}, + }, + }, + { + Type: "portmap", + Capabilities: map[string]bool{"portMappings": true}, + }, + }, + }) + if err != nil { + return err + } + body = append(body, '\n') + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- CNI reads this config directory + return fmt.Errorf("create cni config directory: %w", err) + } + path := filepath.Join(dir, FileName) + tmp := path + ".tmp" + if err := os.WriteFile(tmp, body, 0o644); err != nil { // #nosec G306 -- bridge conflist is not secret + return fmt.Errorf("write cni config: %w", err) + } + if err := os.Rename(tmp, path); err != nil { + _ = os.Remove(tmp) + return fmt.Errorf("write cni config: %w", err) + } + return nil +} diff --git a/kube/internal/network/write_test.go b/kube/internal/network/write_test.go new file mode 100644 index 0000000..a4ae3bc --- /dev/null +++ b/kube/internal/network/write_test.go @@ -0,0 +1,109 @@ +package network + +import ( + "bytes" + "encoding/json" + "net" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/allocator" + "github.com/containernetworking/plugins/plugins/ipam/host-local/backend/disk" +) + +func TestSandboxAddressInNodePodCIDR(t *testing.T) { + dir := t.TempDir() + const podCIDR = "10.20.0.0/24" + if err := Write(dir, podCIDR); err != nil { + t.Fatal(err) + } + if err := Write(dir, podCIDR); err != nil { + t.Fatal(err) + } + files := conflistFiles(t, dir) + if len(files) != 1 || files[0] != FileName { + t.Fatalf("conflists %v", files) + } + + body, err := os.ReadFile(filepath.Join(dir, FileName)) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(body, []byte(`"hairpinMode":true`)) { + t.Fatalf("hairpinMode %s", body) + } + if bytes.Contains(body, []byte("flannel")) { + t.Fatalf("second network %s", body) + } + var doc conflist + if err := json.Unmarshal(body, &doc); err != nil { + t.Fatal(err) + } + if len(doc.Plugins) != 2 { + t.Fatalf("plugins %d", len(doc.Plugins)) + } + bridge := doc.Plugins[0] + if bridge.Type != "bridge" || !bridge.IsGateway || !bridge.IPMasq || !bridge.HairpinMode { + t.Fatalf("bridge %+v", bridge) + } + if bridge.IPAM == nil || bridge.IPAM.Type != "host-local" || len(bridge.IPAM.Ranges) != 1 || len(bridge.IPAM.Ranges[0]) != 1 { + t.Fatalf("ipam %+v", bridge.IPAM) + } + if bridge.IPAM.Ranges[0][0].Subnet != podCIDR { + t.Fatalf("range %s", bridge.IPAM.Ranges[0][0].Subnet) + } + portmap := doc.Plugins[1] + if portmap.Type != "portmap" || !portmap.Capabilities["portMappings"] { + t.Fatalf("portmap %+v", portmap) + } + + _, podNet, err := net.ParseCIDR(podCIDR) + if err != nil { + t.Fatal(err) + } + raw, err := json.Marshal(bridge) + if err != nil { + t.Fatal(err) + } + ipam, _, err := allocator.LoadIPAMConfig(raw, "") + if err != nil { + t.Fatal(err) + } + store, err := disk.New(doc.Name, t.TempDir()) + if err != nil { + t.Fatal(err) + } + assigned, err := allocator.NewIPAllocator(&ipam.Ranges[0], store, 0).Get("sandbox", "eth0", nil) + if err != nil { + t.Fatal(err) + } + if !podNet.Contains(assigned.Address.IP) { + t.Fatalf("sandbox %s outside %s", assigned.Address.IP, podCIDR) + } +} + +func TestWriteRejectsPodNetwork(t *testing.T) { + if err := Write(t.TempDir(), "not-a-network"); err == nil { + t.Fatal("accepted a pod network that is not a CIDR") + } +} + +func conflistFiles(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + var names []string + for _, entry := range entries { + name := entry.Name() + if strings.HasSuffix(name, ".conflist") || strings.HasSuffix(name, ".conf") { + names = append(names, name) + } + } + slices.Sort(names) + return names +} diff --git a/kube/internal/paths/paths.go b/kube/internal/paths/paths.go new file mode 100644 index 0000000..22b3145 --- /dev/null +++ b/kube/internal/paths/paths.go @@ -0,0 +1,211 @@ +// Package paths is the on-disk layout of the runtime. +// Kubelet reads CNIConfDir and CNIBinDir as --cni-conf-dir and --cni-bin-dir. +package paths + +import ( + "fmt" + "os" + "path/filepath" + "strings" +) + +const ( + // ContainerdSocket is the containerd gRPC socket. + ContainerdSocket = "/run/edgelet-kube/containerd.sock" + // ContainerdRoot is the containerd persistent directory. + ContainerdRoot = "/var/lib/edgelet-kube/agent/containerd" + // ContainerdState is the containerd transient directory. + // It is the directory that holds ContainerdSocket. + ContainerdState = "/run/edgelet-kube" + // CNIConfDir is the CNI configuration directory. + // Kubelet receives it as --cni-conf-dir. + CNIConfDir = "/var/lib/edgelet-kube/agent/etc/cni/net.d" + // ImagesDir is the directory of image archives imported into containerd. + // An empty directory pulls the pinned image list. + ImagesDir = "/var/lib/edgelet-kube/agent/images" +) + +// Layout is the runtime directories for one extracted bundle. +type Layout struct { + // Socket is the containerd gRPC socket. + Socket string + // Root is the containerd persistent directory. + Root string + // State is the containerd transient directory. + State string + // CNIConfDir is the CNI configuration directory kubelet receives as --cni-conf-dir. + CNIConfDir string + // CNIBinDir is the CNI plugin directory in the extracted bundle. + // Kubelet receives it as --cni-bin-dir. + CNIBinDir string + // BundledBin is the aux directory in the extracted bundle. + // prefer-bundled-bin puts this directory ahead of host binaries. + BundledBin string +} + +// FromBundle returns the runtime layout for an extracted bundle directory. +func FromBundle(bundleDir string) (Layout, error) { + bin := filepath.Join(bundleDir, "bin") + layout := Layout{ + Socket: ContainerdSocket, + Root: ContainerdRoot, + State: ContainerdState, + CNIConfDir: CNIConfDir, + CNIBinDir: bin, + BundledBin: filepath.Join(bin, "aux"), + } + if err := layout.check(); err != nil { + return Layout{}, err + } + return layout, nil +} + +// KubeletCNIArgs are the kubelet flags for this layout's CNI directories. +func (l Layout) KubeletCNIArgs() []string { + return []string{ + "--cni-conf-dir=" + l.CNIConfDir, + "--cni-bin-dir=" + l.CNIBinDir, + } +} + +// BinPath is PATH for kubelet and kube-proxy. +// prefer puts BundledBin first. iptables, iptables-save, and iptables-restore +// in that directory name xtables-nft-multi. +// When prefer is false, host directories stay first and BundledBin is appended. +func (l Layout) BinPath(prefer bool, hostPath string) string { + bundled := filepath.Clean(l.BundledBin) + if bundled == "" || bundled == "." { + return hostPath + } + sep := string(os.PathListSeparator) + host := make([]string, 0) + if hostPath != "" { + for _, part := range strings.Split(hostPath, sep) { + if part == "" || filepath.Clean(part) == bundled { + continue + } + host = append(host, part) + } + } + if !prefer { + return strings.Join(append(host, bundled), sep) + } + return strings.Join(append([]string{bundled}, host...), sep) +} + +func (l Layout) check() error { + if filepath.Clean(l.CNIBinDir) == "/opt/cni/bin" { + return fmt.Errorf("unsupported cni binary directory %s", l.CNIBinDir) + } + switch filepath.Clean(l.Socket) { + case "/run/containerd/containerd.sock", "/var/run/containerd/containerd.sock": + return fmt.Errorf("unsupported containerd socket %s", l.Socket) + } + return nil +} + +// Place makes the CNI plugins and bundled host binaries available in the +// extracted bundle. The plugin directory is Layout.CNIBinDir. The aux +// directory is Layout.BundledBin. +func Place(bundleDir string) (Layout, error) { + layout, err := FromBundle(bundleDir) + if err != nil { + return Layout{}, err + } + if err := placeBundled(layout.CNIBinDir, layout.BundledBin); err != nil { + return Layout{}, err + } + return layout, nil +} + +func placeBundled(bin, aux string) error { + if err := requireFile(filepath.Join(bin, "cni")); err != nil { + return err + } + for _, name := range []string{"bridge", "host-local", "loopback", "portmap"} { + if err := ensureLink(bin, name, "cni"); err != nil { + return err + } + } + if err := requireFile(filepath.Join(bin, "ip")); err != nil { + return err + } + if err := requireFile(filepath.Join(bin, "busybox")); err != nil { + return err + } + if err := ensureLink(bin, "modprobe", "busybox"); err != nil { + return err + } + return alignIptables(aux) +} + +// iptablesNames are the commands kube-proxy and the bridge plugin exec. +// They name one binary so a chain check and a rule restore use the same table. +var iptablesNames = []string{ + "iptables", "iptables-save", "iptables-restore", + "ip6tables", "ip6tables-save", "ip6tables-restore", +} + +// alignIptables points the iptables family at xtables-nft-multi. +// The k3s-root tree ships those names on that binary. A link that was +// aimed at xtables-legacy-multi is replaced. +func alignIptables(aux string) error { + if err := requireFile(filepath.Join(aux, "xtables-nft-multi")); err != nil { + return err + } + for _, name := range iptablesNames { + if err := retargetLink(aux, name, "xtables-nft-multi"); err != nil { + return err + } + } + return nil +} + +func retargetLink(dir, name, target string) error { + path := filepath.Join(dir, name) + got, err := os.Readlink(path) + if err == nil && got == target { + return nil + } + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("bundled binary %s: %w", path, err) + } + if err == nil { + if err := os.Remove(path); err != nil { + return fmt.Errorf("place %s: %w", path, err) + } + } + if err := os.Symlink(target, path); err != nil { + return fmt.Errorf("place %s: %w", path, err) + } + return nil +} + +func requireFile(path string) error { + info, err := os.Stat(path) + if err != nil { + return fmt.Errorf("bundled binary %s: %w", path, err) + } + if !info.Mode().IsRegular() { + return fmt.Errorf("bundled binary %s is not a file", path) + } + return nil +} + +func ensureLink(dir, name, target string) error { + path := filepath.Join(dir, name) + got, err := os.Readlink(path) + if err == nil { + if got == target { + return nil + } + return fmt.Errorf("%s points at %s", path, got) + } + if !os.IsNotExist(err) { + return fmt.Errorf("bundled binary %s: %w", path, err) + } + if err := os.Symlink(target, path); err != nil { + return fmt.Errorf("place %s: %w", path, err) + } + return nil +} diff --git a/kube/internal/paths/paths_test.go b/kube/internal/paths/paths_test.go new file mode 100644 index 0000000..ed8134f --- /dev/null +++ b/kube/internal/paths/paths_test.go @@ -0,0 +1,183 @@ +package paths + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestImagesDir(t *testing.T) { + if ImagesDir != "/var/lib/edgelet-kube/agent/images" { + t.Fatal(ImagesDir) + } +} + +func TestFromBundleRecordsKubeletCNI(t *testing.T) { + dir := t.TempDir() + layout, err := FromBundle(dir) + if err != nil { + t.Fatal(err) + } + if layout.Socket != ContainerdSocket || layout.Root != ContainerdRoot || layout.State != ContainerdState { + t.Fatalf("layout %+v", layout) + } + if layout.CNIConfDir != CNIConfDir { + t.Fatalf("cni conf %s", layout.CNIConfDir) + } + if layout.CNIBinDir != filepath.Join(dir, "bin") { + t.Fatalf("cni bin %s", layout.CNIBinDir) + } + if layout.BundledBin != filepath.Join(dir, "bin", "aux") { + t.Fatalf("bundled bin %s", layout.BundledBin) + } + args := strings.Join(layout.KubeletCNIArgs(), " ") + for _, want := range []string{ + "--cni-conf-dir=" + CNIConfDir, + "--cni-bin-dir=" + layout.CNIBinDir, + } { + if !strings.Contains(args, want) { + t.Fatalf("kubelet args %q missing %s", args, want) + } + } + for _, blocked := range []string{"/opt/cni/bin", "/run/containerd/containerd.sock"} { + if strings.Contains(args, blocked) || strings.Contains(layout.Socket, blocked) { + t.Fatalf("layout uses %s", blocked) + } + } +} + +func TestBinPathPrefersBundledIptables(t *testing.T) { + layout := Layout{BundledBin: "/var/lib/edgelet-kube/data/bin/aux"} + host := "/usr/sbin:/sbin" + prefer := layout.BinPath(true, host) + if !strings.HasPrefix(prefer, layout.BundledBin+string(os.PathListSeparator)) { + t.Fatalf("PATH %s", prefer) + } + if strings.Index(prefer, layout.BundledBin) > strings.Index(prefer, "/usr/sbin") { + t.Fatalf("PATH %s", prefer) + } + hostFirst := layout.BinPath(false, host) + if !strings.HasPrefix(hostFirst, "/usr/sbin") || !strings.HasSuffix(hostFirst, layout.BundledBin) { + t.Fatalf("PATH %s", hostFirst) + } + again := layout.BinPath(true, prefer) + if again != prefer { + t.Fatalf("repeated PATH %s", again) + } +} + +func TestFromBundleRejectsHostCNI(t *testing.T) { + if _, err := FromBundle("/opt/cni"); err == nil { + t.Fatal("accepted the host cni directory") + } +} + +func TestPlaceBundledBins(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "bin") + aux := filepath.Join(bin, "aux") + if err := os.MkdirAll(aux, 0o755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"cni", "ip", "busybox"} { + if err := os.WriteFile(filepath.Join(bin, name), []byte(name), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(aux, "xtables-nft-multi"), []byte("iptables"), 0o755); err != nil { + t.Fatal(err) + } + + layout, err := Place(dir) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"bridge", "host-local", "loopback", "portmap"} { + assertLink(t, filepath.Join(bin, name), "cni") + } + assertLink(t, filepath.Join(bin, "modprobe"), "busybox") + for _, name := range []string{ + "iptables", "iptables-save", "iptables-restore", + "ip6tables", "ip6tables-save", "ip6tables-restore", + } { + assertLink(t, filepath.Join(aux, name), "xtables-nft-multi") + } + if layout.CNIBinDir != bin || layout.BundledBin != aux { + t.Fatalf("layout %+v", layout) + } + + again, err := Place(dir) + if err != nil { + t.Fatal(err) + } + if again.CNIBinDir != layout.CNIBinDir || again.BundledBin != layout.BundledBin { + t.Fatalf("second place %+v", again) + } +} + +func TestPlaceAlignsIptablesFamily(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "bin") + aux := filepath.Join(bin, "aux") + if err := os.MkdirAll(aux, 0o755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"cni", "ip", "busybox"} { + if err := os.WriteFile(filepath.Join(bin, name), []byte(name), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(aux, "xtables-nft-multi"), []byte("iptables"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("xtables-legacy-multi", filepath.Join(aux, "iptables")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("xtables-nft-multi", filepath.Join(aux, "iptables-save")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("xtables-nft-multi", filepath.Join(aux, "iptables-restore")); err != nil { + t.Fatal(err) + } + if _, err := Place(dir); err != nil { + t.Fatal(err) + } + for _, name := range []string{"iptables", "iptables-save", "iptables-restore"} { + assertLink(t, filepath.Join(aux, name), "xtables-nft-multi") + } +} + +func TestPlaceRejectsWrongCNILink(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "bin") + aux := filepath.Join(bin, "aux") + if err := os.MkdirAll(aux, 0o755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"cni", "ip", "busybox"} { + if err := os.WriteFile(filepath.Join(bin, name), []byte(name), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(aux, "xtables-nft-multi"), []byte("iptables"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("busybox", filepath.Join(bin, "bridge")); err != nil { + t.Fatal(err) + } + if _, err := Place(dir); err == nil { + t.Fatal("accepted bridge pointing away from cni") + } +} + +func assertLink(t *testing.T, path, target string) { + t.Helper() + got, err := os.Readlink(path) + if err != nil { + t.Fatal(err) + } + if got != target { + t.Fatalf("%s -> %s, want %s", path, got, target) + } +} diff --git a/kube/internal/registries/doc.go b/kube/internal/registries/doc.go new file mode 100644 index 0000000..ae7f8e9 --- /dev/null +++ b/kube/internal/registries/doc.go @@ -0,0 +1,3 @@ +// Package registries turns the registries file into containerd host configuration. +// A missing file is a normal boot: containerd uses upstream endpoints. +package registries diff --git a/kube/internal/registries/hosts.go b/kube/internal/registries/hosts.go new file mode 100644 index 0000000..675c05b --- /dev/null +++ b/kube/internal/registries/hosts.go @@ -0,0 +1,379 @@ +package registries + +import ( + "bytes" + "errors" + "fmt" + "net/url" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/containerd/containerd/v2/core/remotes/docker" + "go.yaml.in/yaml/v3" +) + +// Auth is registry username and password, or a pre-encoded auth token. +type Auth struct { + Username string `yaml:"username"` + Password string `yaml:"password"` + Token string `yaml:"auth"` +} + +type file struct { + Mirrors map[string]mirror `yaml:"mirrors"` + Configs map[string]hostBlock `yaml:"configs"` +} + +type mirror struct { + Endpoint []string `yaml:"endpoint"` + Rewrite map[string]string `yaml:"rewrite"` +} + +type hostBlock struct { + Auth *Auth `yaml:"auth"` + TLS *tlsConfig `yaml:"tls"` +} + +type tlsConfig struct { + CAFile string `yaml:"ca_file"` + CertFile string `yaml:"cert_file"` + KeyFile string `yaml:"key_file"` + InsecureSkipVerify bool `yaml:"insecure_skip_verify"` +} + +func (t *tlsConfig) configured() bool { + return t != nil && (t.CAFile != "" || t.CertFile != "" || t.KeyFile != "" || t.InsecureSkipVerify) +} + +type endpoint struct { + url string + override bool + rewrites map[string]string + tls *tlsConfig +} + +type hostSpec struct { + includeServer bool + serverURL string + serverTLS *tlsConfig + endpoints []endpoint +} + +// Prepare writes containerd hosts under dir from the registries file. +// A missing or empty file leaves dir empty so containerd uses upstream endpoints. +// disableDefault omits the upstream registry for names listed in the file. +// Registries that are not listed keep their default endpoint. +// The quoted "*" wildcard is written as the containerd default host and is +// used only when that registry has no entry of its own. +// Auth entries are returned for the containerd config. TLS, mirrors, and +// rewrites are written into the host files. +func Prepare(dir, filePath string, disableDefault bool) (map[string]Auth, error) { + if dir == "" || dir == "/" || dir == "." { + return nil, errors.New("registry config directory is required") + } + if err := resetDir(dir); err != nil { + return nil, err + } + if filePath == "" { + return nil, nil + } + body, err := os.ReadFile(filePath) // #nosec G304 -- path is the configured registries file + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("read registries %s: %w", filePath, err) + } + if len(bytes.TrimSpace(body)) == 0 { + return nil, nil + } + var doc file + if err := yaml.Unmarshal(body, &doc); err != nil { + return nil, fmt.Errorf("read registries %s: %w", filePath, err) + } + hosts, auths, err := build(filePath, doc, disableDefault) + if err != nil { + return nil, err + } + names := make([]string, 0, len(hosts)) + for name := range hosts { + names = append(names, name) + } + slices.Sort(names) + for _, name := range names { + spec := hosts[name] + if !spec.worthWriting() { + continue + } + hostDir := filepath.Join(dir, hostDirectory(name)) + if err := os.MkdirAll(hostDir, 0o755); err != nil { // #nosec G301 -- containerd reads this host directory + return nil, fmt.Errorf("create registry config %s: %w", hostDir, err) + } + if err := os.WriteFile(filepath.Join(hostDir, "hosts.toml"), render(spec), 0o644); err != nil { // #nosec G306 -- hosts.toml holds endpoints, not credentials + return nil, fmt.Errorf("write registry config %s: %w", hostDir, err) + } + } + if len(auths) == 0 { + return nil, nil + } + return auths, nil +} + +func resetDir(dir string) error { + if err := os.RemoveAll(dir); err != nil { + return fmt.Errorf("reset registry config %s: %w", dir, err) + } + if err := os.MkdirAll(dir, 0o755); err != nil { // #nosec G301 -- containerd reads the registry config directory + return fmt.Errorf("create registry config %s: %w", dir, err) + } + return nil +} + +func build(path string, doc file, disableDefault bool) (map[string]hostSpec, map[string]Auth, error) { + hosts := map[string]hostSpec{} + for name, cfg := range doc.Configs { + if name == "" { + continue + } + if name == "*" { + if cfg.TLS.configured() { + hosts["*"] = hostSpec{includeServer: true, serverTLS: cfg.TLS} + } + continue + } + server, err := registryURL(name) + if err != nil { + return nil, nil, fmt.Errorf("registries %s: %w", path, err) + } + hosts[name] = hostSpec{ + includeServer: true, + serverURL: server, + serverTLS: cfg.TLS, + } + } + for name, mirror := range doc.Mirrors { + if name == "" { + return nil, nil, fmt.Errorf("registries %s: mirror name is empty", path) + } + spec, ok := hosts[name] + if !ok { + spec = hostSpec{} + if name == "*" { + if !disableDefault { + spec.includeServer = true + spec.serverTLS = tlsFor(doc, "*") + } + } else if !disableDefault { + server, err := registryURL(name) + if err != nil { + return nil, nil, fmt.Errorf("registries %s: %w", path, err) + } + spec.includeServer = true + spec.serverURL = server + spec.serverTLS = tlsFor(doc, name) + } + } else if disableDefault { + spec.includeServer = false + spec.serverURL = "" + spec.serverTLS = nil + } + seen := map[string]bool{} + for i, raw := range mirror.Endpoint { + raw = strings.TrimSpace(raw) + if raw == "" { + return nil, nil, fmt.Errorf("registries %s: mirror %s has an empty endpoint", path, name) + } + registryName, endpointURL, override, err := normalizeEndpoint(raw) + if err != nil { + return nil, nil, fmt.Errorf("registries %s: mirror %s endpoint %d: %w", path, name, i, err) + } + if seen[endpointURL] { + continue + } + seen[endpointURL] = true + spec.endpoints = append(spec.endpoints, endpoint{ + url: endpointURL, + override: override, + rewrites: copyMap(mirror.Rewrite), + tls: tlsFor(doc, registryName), + }) + } + if spec.includeServer && len(spec.endpoints) > 0 { + last := spec.endpoints[len(spec.endpoints)-1] + if last.url == spec.serverURL && !last.override && len(last.rewrites) == 0 && !last.tls.configured() { + spec.endpoints = spec.endpoints[:len(spec.endpoints)-1] + } + } + hosts[name] = spec + } + auths := map[string]Auth{} + for name, cfg := range doc.Configs { + if name == "" || cfg.Auth == nil { + continue + } + if cfg.Auth.Username == "" && cfg.Auth.Password == "" && cfg.Auth.Token == "" { + continue + } + auths[name] = *cfg.Auth + } + return hosts, auths, nil +} + +func (s hostSpec) worthWriting() bool { + if len(s.endpoints) > 0 { + return true + } + return s.serverTLS.configured() +} + +func tlsFor(doc file, host string) *tlsConfig { + if cfg, ok := doc.Configs[host]; ok && cfg.TLS.configured() { + return cfg.TLS + } + if normalized, err := docker.DefaultHost(host); err == nil && normalized != host { + if cfg, ok := doc.Configs[normalized]; ok && cfg.TLS.configured() { + return cfg.TLS + } + } + if host == "registry-1.docker.io" { + if cfg, ok := doc.Configs["docker.io"]; ok && cfg.TLS.configured() { + return cfg.TLS + } + } + return nil +} + +func registryURL(host string) (string, error) { + _, endpointURL, _, err := normalizeEndpoint(host) + return endpointURL, err +} + +func normalizeEndpoint(endpoint string) (registryName, endpointURL string, override bool, err error) { + raw := endpoint + if !strings.Contains(endpoint, "://") { + endpoint = "//" + endpoint + } + parsed, err := url.Parse(endpoint) + if err != nil || parsed.Host == "" { + return "", "", false, fmt.Errorf("invalid registry endpoint %q", raw) + } + if parsed.Scheme == "" { + port := parsed.Port() + if docker.IsLocalhost(parsed.Host) && port != "" && port != "443" { + parsed.Scheme = "http" + } else { + parsed.Scheme = "https" + } + } + registryName = parsed.Host + host, err := docker.DefaultHost(registryName) + if err != nil { + return "", "", false, err + } + parsed.Host = host + if parsed.Host == "registry-1.docker.io" { + registryName = "docker.io" + } + parsed.RawQuery = "" + parsed.Fragment = "" + switch parsed.Path { + case "", "/", "/v2": + parsed.Path = "/v2" + parsed.RawPath = "" + return registryName, parsed.String(), false, nil + default: + return registryName, parsed.String(), true, nil + } +} + +func hostDirectory(host string) string { + if host == "*" { + return "_default" + } + idx := strings.LastIndex(host, ":") + if idx > 0 { + return host[:idx] + "_" + host[idx+1:] + "_" + } + return host +} + +func copyMap(in map[string]string) map[string]string { + if len(in) == 0 { + return nil + } + out := make(map[string]string, len(in)) + for key, value := range in { + out[key] = value + } + return out +} + +func render(spec hostSpec) []byte { + var b strings.Builder + if spec.includeServer { + b.WriteString("server = ") + b.WriteString(strconv.Quote(spec.serverURL)) + b.WriteByte('\n') + b.WriteString("capabilities = [\"pull\", \"resolve\", \"push\"]\n") + writeTLS(&b, spec.serverTLS, "") + } + for _, ep := range spec.endpoints { + if b.Len() > 0 { + b.WriteByte('\n') + } + b.WriteString("[host.") + b.WriteString(strconv.Quote(ep.url)) + b.WriteString("]\n") + b.WriteString(" capabilities = [\"pull\", \"resolve\"]\n") + if ep.override { + b.WriteString(" override_path = true\n") + } + writeTLS(&b, ep.tls, " ") + if len(ep.rewrites) > 0 { + b.WriteByte('\n') + b.WriteString(" [host.") + b.WriteString(strconv.Quote(ep.url)) + b.WriteString(".rewrite]\n") + keys := make([]string, 0, len(ep.rewrites)) + for key := range ep.rewrites { + keys = append(keys, key) + } + slices.Sort(keys) + for _, key := range keys { + b.WriteString(" ") + b.WriteString(strconv.Quote(key)) + b.WriteString(" = ") + b.WriteString(strconv.Quote(ep.rewrites[key])) + b.WriteByte('\n') + } + } + } + return []byte(b.String()) +} + +func writeTLS(b *strings.Builder, tls *tlsConfig, indent string) { + if !tls.configured() { + return + } + if tls.CAFile != "" { + b.WriteString(indent) + b.WriteString("ca = ") + b.WriteString(strconv.Quote(tls.CAFile)) + b.WriteByte('\n') + } + if tls.CertFile != "" || tls.KeyFile != "" { + b.WriteString(indent) + b.WriteString("client = [[") + b.WriteString(strconv.Quote(tls.CertFile)) + b.WriteString(", ") + b.WriteString(strconv.Quote(tls.KeyFile)) + b.WriteString("]]\n") + } + if tls.InsecureSkipVerify { + b.WriteString(indent) + b.WriteString("skip_verify = true\n") + } +} diff --git a/kube/internal/registries/hosts_test.go b/kube/internal/registries/hosts_test.go new file mode 100644 index 0000000..3141b9f --- /dev/null +++ b/kube/internal/registries/hosts_test.go @@ -0,0 +1,292 @@ +package registries + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "encoding/pem" + "fmt" + "math/big" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + dockerconfig "github.com/containerd/containerd/v2/core/remotes/docker/config" +) + +func TestMissingFileUsesUpstream(t *testing.T) { + dir := t.TempDir() + auths, err := Prepare(dir, filepath.Join(dir, "registries.yaml"), false) + if err != nil { + t.Fatal(err) + } + if len(auths) != 0 { + t.Fatalf("auths %#v", auths) + } + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("hosts written for a missing file: %d", len(entries)) + } + if got := endpoints(t, dir, "docker.io"); len(got) != 1 || got[0] != "https://registry-1.docker.io/v2" { + t.Fatalf("docker.io endpoints %v", got) + } + if got := endpoints(t, dir, "registry.k8s.io"); len(got) != 1 || got[0] != "https://registry.k8s.io/v2" { + t.Fatalf("registry.k8s.io endpoints %v", got) + } + if got := endpoints(t, dir, "quay.io"); len(got) != 1 || got[0] != "https://quay.io/v2" { + t.Fatalf("quay.io endpoints %v", got) + } +} + +func TestPrivateRegistryFileAndDisableDefault(t *testing.T) { + dir := t.TempDir() + ignored := filepath.Join(dir, "ignored.yaml") + if err := os.WriteFile(ignored, []byte("mirrors:\n quay.io:\n endpoint:\n - https://ignored.example\n"), 0o644); err != nil { + t.Fatal(err) + } + caFile, certFile, keyFile := writeCert(t) + chosen := filepath.Join(dir, "site.yaml") + body := fmt.Sprintf(` +mirrors: + docker.io: + endpoint: + - https://mirror.example.com/v2 + rewrite: + "^library/(.*)": "docker/$1" + "*": + endpoint: + - https://cache.example.com/v2 +configs: + mirror.example.com: + auth: + username: user + password: secret + tls: + ca_file: %s + cert_file: %s + key_file: %s + insecure_skip_verify: true + quay.io: + tls: + insecure_skip_verify: true +`, caFile, certFile, keyFile) + if err := os.WriteFile(chosen, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + hosts := filepath.Join(dir, "certs.d") + auths, err := Prepare(hosts, chosen, true) + if err != nil { + t.Fatal(err) + } + if auths["mirror.example.com"].Username != "user" || auths["mirror.example.com"].Password != "secret" { + t.Fatalf("auths %#v", auths) + } + if got := endpoints(t, hosts, "docker.io"); len(got) != 1 || got[0] != "https://mirror.example.com/v2" { + t.Fatalf("docker.io endpoints %v", got) + } + rewrites := rewritesFor(t, hosts, "docker.io", "mirror.example.com") + if rewrites["^library/(.*)"] != "docker/$1" { + t.Fatalf("rewrite %#v", rewrites) + } + hostsBody, err := os.ReadFile(filepath.Join(hosts, "docker.io", "hosts.toml")) + if err != nil { + t.Fatal(err) + } + text := string(hostsBody) + for _, want := range []string{ + "ca = " + strconv.Quote(caFile), + "client = [[" + strconv.Quote(certFile) + ", " + strconv.Quote(keyFile) + "]]", + "skip_verify = true", + "override_path = false", + } { + if want == "override_path = false" { + if strings.Contains(text, "override_path") { + t.Fatalf("override_path set\n%s", text) + } + continue + } + if !strings.Contains(text, want) { + t.Fatalf("missing %s\n%s", want, text) + } + } + if strings.Contains(text, "registry-1.docker.io") { + t.Fatalf("upstream fallback still present\n%s", text) + } + if got := endpoints(t, hosts, "quay.io"); len(got) != 1 || got[0] != "https://quay.io/v2" { + t.Fatalf("quay.io lost its endpoint %v", got) + } + quay, err := os.ReadFile(filepath.Join(hosts, "quay.io", "hosts.toml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(quay), "skip_verify = true") { + t.Fatalf("quay tls\n%s", quay) + } + if got := endpoints(t, hosts, "registry.k8s.io"); len(got) != 1 || got[0] != "https://cache.example.com/v2" { + t.Fatalf("wildcard endpoints %v", got) + } + if got := endpoints(t, hosts, "docker.io"); len(got) != 1 || got[0] == "https://cache.example.com/v2" { + t.Fatalf("wildcard replaced docker.io %v", got) + } +} + +func TestWildcardKeepsUpstreamWhenFallbackStays(t *testing.T) { + dir := filepath.Join(t.TempDir(), "certs.d") + file := filepath.Join(t.TempDir(), "registries.yaml") + if err := os.WriteFile(file, []byte(` +mirrors: + "*": + endpoint: + - https://cache.example.com/v2 +`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Prepare(dir, file, false); err != nil { + t.Fatal(err) + } + got := endpoints(t, dir, "quay.io") + if len(got) != 2 || got[0] != "https://cache.example.com/v2" || got[1] != "https://quay.io/v2" { + t.Fatalf("endpoints %v", got) + } +} + +func TestEndpointPathIsKept(t *testing.T) { + dir := filepath.Join(t.TempDir(), "certs.d") + file := filepath.Join(t.TempDir(), "registries.yaml") + if err := os.WriteFile(file, []byte(` +mirrors: + docker.io: + endpoint: + - https://registry.example.com/project/registry +`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Prepare(dir, file, true); err != nil { + t.Fatal(err) + } + body, err := os.ReadFile(filepath.Join(dir, "docker.io", "hosts.toml")) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), "override_path = true") { + t.Fatalf("hosts\n%s", body) + } + got := endpoints(t, dir, "docker.io") + if len(got) != 1 || got[0] != "https://registry.example.com/project/registry" { + t.Fatalf("endpoints %v", got) + } +} + +func TestAuthToken(t *testing.T) { + dir := filepath.Join(t.TempDir(), "certs.d") + file := filepath.Join(t.TempDir(), "registries.yaml") + if err := os.WriteFile(file, []byte("configs:\n registry.example:\n auth:\n auth: dXNlcjpwYXNz\n"), 0o644); err != nil { + t.Fatal(err) + } + auths, err := Prepare(dir, file, false) + if err != nil { + t.Fatal(err) + } + if auths["registry.example"].Token != "dXNlcjpwYXNz" { + t.Fatalf("auths %#v", auths) + } +} + +func TestLocalhostEndpointUsesHTTP(t *testing.T) { + dir := filepath.Join(t.TempDir(), "certs.d") + file := filepath.Join(t.TempDir(), "registries.yaml") + if err := os.WriteFile(file, []byte("mirrors:\n docker.io:\n endpoint:\n - 127.0.0.1:5000\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := Prepare(dir, file, true); err != nil { + t.Fatal(err) + } + got := endpoints(t, dir, "docker.io") + if len(got) != 1 || got[0] != "http://127.0.0.1:5000/v2" { + t.Fatalf("endpoints %v", got) + } + if got = endpoints(t, dir, "quay.io"); len(got) != 1 || got[0] != "https://quay.io/v2" { + t.Fatalf("unlisted registry %v", got) + } +} + +func writeCert(t *testing.T) (caFile, certFile, keyFile string) { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + BasicConstraintsValid: true, + IsCA: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + caFile = filepath.Join(dir, "ca.pem") + certFile = filepath.Join(dir, "cert.pem") + keyFile = filepath.Join(dir, "key.pem") + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyDER, err := x509.MarshalECPrivateKey(key) + if err != nil { + t.Fatal(err) + } + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}) + if err := os.WriteFile(caFile, certPEM, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(certFile, certPEM, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(keyFile, keyPEM, 0o644); err != nil { + t.Fatal(err) + } + return caFile, certFile, keyFile +} + +func endpoints(t *testing.T, dir, host string) []string { + t.Helper() + fn := dockerconfig.ConfigureHosts(t.Context(), dockerconfig.HostOptions{ + HostDir: dockerconfig.HostDirFromRoot(dir), + }) + got, err := fn(host) + if err != nil { + t.Fatal(err) + } + out := make([]string, 0, len(got)) + for _, item := range got { + out = append(out, item.Scheme+"://"+item.Host+item.Path) + } + return out +} + +func rewritesFor(t *testing.T, dir, registry, host string) map[string]string { + t.Helper() + fn := dockerconfig.ConfigureHosts(t.Context(), dockerconfig.HostOptions{ + HostDir: dockerconfig.HostDirFromRoot(dir), + }) + got, err := fn(registry) + if err != nil { + t.Fatal(err) + } + for _, item := range got { + if item.Host == host { + return item.Rewrites + } + } + t.Fatalf("host %s not found in %s", host, registry) + return nil +} diff --git a/kube/internal/servicelb/servicelb.go b/kube/internal/servicelb/servicelb.go new file mode 100644 index 0000000..895c550 --- /dev/null +++ b/kube/internal/servicelb/servicelb.go @@ -0,0 +1,154 @@ +// Package servicelb publishes the node IP on LoadBalancer Services. +// kube-proxy programs forwarding from that address. The controller does not +// create pods or DaemonSets. +package servicelb + +import ( + "context" + "errors" + "fmt" + "net" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/informers" + "k8s.io/client-go/kubernetes" + corelisters "k8s.io/client-go/listers/core/v1" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/tools/clientcmd" + "k8s.io/client-go/util/workqueue" +) + +// Run watches Services and writes address onto each LoadBalancer Service. +func Run(ctx context.Context, kubeconfig, address string) error { + ip := net.ParseIP(address) + if ip == nil { + return fmt.Errorf("node IP %q is not an IP", address) + } + if kubeconfig == "" { + return errors.New("kubeconfig is empty") + } + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + return err + } + cfg.UserAgent = "edgelet-kube" + client, err := kubernetes.NewForConfig(cfg) + if err != nil { + return err + } + return run(ctx, client, ip.String()) +} + +func run(ctx context.Context, client kubernetes.Interface, address string) error { + factory := informers.NewSharedInformerFactory(client, 30*time.Second) + services := factory.Core().V1().Services() + queue := workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[string]()) + defer queue.ShutDown() + c := &controller{ + client: client, + address: address, + lister: services.Lister(), + queue: queue, + } + if _, err := services.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: func(obj any) { c.enqueue(obj) }, + UpdateFunc: func(_, obj any) { c.enqueue(obj) }, + }); err != nil { + return err + } + factory.Start(ctx.Done()) + if !cache.WaitForCacheSync(ctx.Done(), services.Informer().HasSynced) { + if ctx.Err() != nil { + return nil + } + return errors.New("services were not listed") + } + go func() { + <-ctx.Done() + queue.ShutDown() + }() + for c.processNext(ctx) { + } + return nil +} + +type controller struct { + client kubernetes.Interface + address string + lister corelisters.ServiceLister + queue workqueue.TypedRateLimitingInterface[string] +} + +func (c *controller) enqueue(obj any) { + key, err := cache.MetaNamespaceKeyFunc(obj) + if err != nil { + return + } + c.queue.Add(key) +} + +func (c *controller) processNext(ctx context.Context) bool { + key, shutdown := c.queue.Get() + if shutdown { + return false + } + defer c.queue.Done(key) + err := c.sync(ctx, key) + if err != nil && ctx.Err() == nil { + c.queue.AddRateLimited(key) + return true + } + c.queue.Forget(key) + if ctx.Err() != nil { + c.queue.ShutDown() + return false + } + return true +} + +func (c *controller) sync(ctx context.Context, key string) error { + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return nil + } + svc, err := c.lister.Services(namespace).Get(name) + if apierrors.IsNotFound(err) { + return nil + } + if err != nil { + return err + } + if svc.DeletionTimestamp != nil { + return nil + } + if svc.Spec.Type != corev1.ServiceTypeLoadBalancer { + if !published(svc, c.address) { + return nil + } + updated := svc.DeepCopy() + updated.Status.LoadBalancer = corev1.LoadBalancerStatus{} + _, err = c.client.CoreV1().Services(namespace).UpdateStatus(ctx, updated, metav1.UpdateOptions{}) + if apierrors.IsNotFound(err) { + return nil + } + return err + } + if published(svc, c.address) { + return nil + } + updated := svc.DeepCopy() + updated.Status.LoadBalancer.Ingress = []corev1.LoadBalancerIngress{{IP: c.address}} + _, err = c.client.CoreV1().Services(namespace).UpdateStatus(ctx, updated, metav1.UpdateOptions{}) + if apierrors.IsNotFound(err) { + return nil + } + return err +} + +func published(svc *corev1.Service, address string) bool { + ingress := svc.Status.LoadBalancer.Ingress + return len(ingress) == 1 && ingress[0].IP == address && ingress[0].Hostname == "" +} diff --git a/kube/internal/servicelb/servicelb_test.go b/kube/internal/servicelb/servicelb_test.go new file mode 100644 index 0000000..5ab712e --- /dev/null +++ b/kube/internal/servicelb/servicelb_test.go @@ -0,0 +1,123 @@ +package servicelb + +import ( + "context" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/fake" +) + +func TestAssignsNodeIPWithoutDaemonSet(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + client := fake.NewSimpleClientset() + if _, err := client.CoreV1().Services("default").Create(ctx, loadBalancer("web"), metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + if _, err := client.CoreV1().Services("default").Create(ctx, &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: "cluster", Namespace: "default"}, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeClusterIP, + Selector: map[string]string{"app": "cluster"}, + Ports: []corev1.ServicePort{{Port: 80, TargetPort: intstr.FromInt(80)}}, + }, + }, metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + + errCh := make(chan error, 1) + go func() { errCh <- run(ctx, client, "192.0.2.10") }() + waitPublished(t, client, "web", "192.0.2.10", true) + cluster, err := client.CoreV1().Services("default").Get(ctx, "cluster", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + if len(cluster.Status.LoadBalancer.Ingress) != 0 { + t.Fatalf("cluster ingress %v", cluster.Status.LoadBalancer.Ingress) + } + + web, err := client.CoreV1().Services("default").Get(ctx, "web", metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + web.Spec.Type = corev1.ServiceTypeClusterIP + if _, err := client.CoreV1().Services("default").Update(ctx, web, metav1.UpdateOptions{}); err != nil { + t.Fatal(err) + } + waitPublished(t, client, "web", "192.0.2.10", false) + + sets, err := client.AppsV1().DaemonSets(metav1.NamespaceAll).List(ctx, metav1.ListOptions{}) + if err != nil { + t.Fatal(err) + } + if len(sets.Items) != 0 { + t.Fatalf("daemonsets %#v", sets.Items) + } + for _, action := range client.Actions() { + switch action.GetVerb() { + case "create", "update", "patch": + default: + continue + } + resource := action.GetResource().Resource + if resource == "daemonsets" || resource == "pods" { + t.Fatalf("%s %s", action.GetVerb(), resource) + } + } + select { + case err := <-errCh: + t.Fatal(err) + default: + } +} + +func TestRunRejectsBadAddress(t *testing.T) { + if err := Run(context.Background(), "", "not-an-ip"); err == nil { + t.Fatal("accepted a bad node IP") + } +} + +func loadBalancer(name string) *corev1.Service { + return &corev1.Service{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, + Spec: corev1.ServiceSpec{ + Type: corev1.ServiceTypeLoadBalancer, + Selector: map[string]string{"app": name}, + Ports: []corev1.ServicePort{{Name: "http", Port: 80, TargetPort: intstr.FromInt(8080), Protocol: corev1.ProtocolTCP}}, + }, + } +} + +func waitPublished(t *testing.T, client kubernetes.Interface, name, ip string, assigned bool) { + t.Helper() + ctx := t.Context() + deadline := time.NewTimer(10 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(20 * time.Millisecond) + defer ticker.Stop() + for { + svc, err := client.CoreV1().Services("default").Get(ctx, name, metav1.GetOptions{}) + if err != nil { + t.Fatal(err) + } + got := published(svc, ip) + if assigned && got { + return + } + if !assigned && len(svc.Status.LoadBalancer.Ingress) == 0 { + return + } + select { + case <-ctx.Done(): + t.Fatal(ctx.Err()) + case <-deadline.C: + t.Fatalf("ingress %v", svc.Status.LoadBalancer.Ingress) + case <-ticker.C: + } + } +} diff --git a/kube/internal/stage/apply.go b/kube/internal/stage/apply.go new file mode 100644 index 0000000..abdebd9 --- /dev/null +++ b/kube/internal/stage/apply.go @@ -0,0 +1,322 @@ +package stage + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/discovery" + "k8s.io/client-go/discovery/cached/memory" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/restmapper" + "k8s.io/client-go/tools/clientcmd" +) + +const fieldManager = "edgelet-kube" + +// Apply writes the built-in addon manifests to the API server, then the +// RuntimeClass objects for handlers this node registers, then the HelmChart +// CRD, then the HelmChart objects, then extra. extra is additional YAML +// supplied by the caller. A disabled addon is deleted. A catalog handler +// whose binary is absent has its RuntimeClass deleted. Disabling the +// metrics server does not change API aggregation. The HelmChart CRD and the +// HelmChart objects are omitted when the Helm controller is disabled. +func Apply(ctx context.Context, kubeconfig string, srv config.Server, extra []byte) error { + if kubeconfig == "" { + return errors.New("kubeconfig is empty") + } + manifests, err := addonManifests(srv) + if err != nil { + return err + } + runtimes, err := runtimeManifests(srv) + if err != nil { + return err + } + manifests = append(manifests, runtimes...) + crd, err := HelmChartCRD(srv) + if err != nil { + return err + } + charts, err := helmChartManifests(srv) + if err != nil { + return err + } + client, err := newApplier(kubeconfig) + if err != nil { + return err + } + deadline := time.NewTimer(2 * time.Minute) + defer deadline.Stop() + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + var last error + for { + last = client.syncAll(ctx, manifests, crd, charts, extra) + if last == nil { + return nil + } + if isFatal(last) { + return last + } + select { + case <-ctx.Done(): + return fmt.Errorf("addons were not applied: %w", ctx.Err()) + case <-deadline.C: + return fmt.Errorf("addons were not applied: %w", last) + case <-ticker.C: + } + } +} + +type fatalError struct { + err error +} + +func (e fatalError) Error() string { + return e.err.Error() +} + +func (e fatalError) Unwrap() error { + return e.err +} + +func isFatal(err error) bool { + var fatal fatalError + return errors.As(err, &fatal) +} + +type applier struct { + dynamic dynamic.Interface + cache discovery.CachedDiscoveryInterface + mapper *restmapper.DeferredDiscoveryRESTMapper +} + +func newApplier(kubeconfig string) (*applier, error) { + cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig) + if err != nil { + return nil, err + } + cfg.QPS = 50 + cfg.Burst = 100 + cfg.UserAgent = fieldManager + disco, err := discovery.NewDiscoveryClientForConfig(cfg) + if err != nil { + return nil, err + } + cache := memory.NewMemCacheClient(disco) + dyn, err := dynamic.NewForConfig(cfg) + if err != nil { + return nil, err + } + return &applier{ + dynamic: dyn, + cache: cache, + mapper: restmapper.NewDeferredDiscoveryRESTMapper(cache), + }, nil +} + +func (a *applier) syncAll(ctx context.Context, manifests []manifest, crd []byte, charts []manifest, extra []byte) error { + a.cache.Invalidate() + a.mapper.Reset() + for _, doc := range manifests { + if doc.enabled { + continue + } + if err := a.sync(ctx, doc.body, false); err != nil { + return err + } + } + for _, doc := range charts { + if doc.enabled { + continue + } + if err := a.sync(ctx, doc.body, false); err != nil { + return err + } + } + for _, body := range enabledBodies(manifests, crd, charts, extra) { + if err := a.sync(ctx, body, true); err != nil { + return err + } + } + return nil +} + +func enabledBodies(manifests []manifest, crd []byte, charts []manifest, extra []byte) [][]byte { + out := make([][]byte, 0, len(manifests)+len(charts)+2) + for _, doc := range manifests { + if doc.enabled { + out = append(out, doc.body) + } + } + if len(bytes.TrimSpace(crd)) > 0 { + out = append(out, crd) + } + for _, doc := range charts { + if doc.enabled { + out = append(out, doc.body) + } + } + if len(bytes.TrimSpace(extra)) > 0 { + out = append(out, extra) + } + return out +} + +// HelmChartCRD is the embedded helm.cattle.io/v1 chart API. +// It is empty when the Helm controller is disabled. +func HelmChartCRD(srv config.Server) ([]byte, error) { + if srv.DisableHelmController { + return nil, nil + } + body, err := files.ReadFile("helmchart-crd.yaml") + if err != nil { + return nil, fmt.Errorf("read helm chart API: %w", err) + } + return body, nil +} + +func (a *applier) sync(ctx context.Context, body []byte, enabled bool) error { + objs, err := decode(body) + if err != nil { + return fatalError{err: err} + } + for _, obj := range objs { + if !enabled && obj.GetKind() == "Namespace" { + continue + } + var syncErr error + if enabled { + syncErr = a.apply(ctx, obj) + } else { + syncErr = a.remove(ctx, obj) + } + if syncErr != nil { + return syncErr + } + if enabled && obj.GetKind() == "CustomResourceDefinition" { + a.cache.Invalidate() + a.mapper.Reset() + } + } + return nil +} + +func (a *applier) apply(ctx context.Context, obj *unstructured.Unstructured) error { + obj = obj.DeepCopy() + obj.SetManagedFields(nil) + obj.SetResourceVersion("") + obj.SetUID("") + ri, err := a.resource(obj) + if err != nil { + return classify(fmt.Errorf("apply %s: %w", objectID(obj), err)) + } + _, err = ri.Apply(ctx, obj.GetName(), obj, metav1.ApplyOptions{FieldManager: fieldManager, Force: true}) + if err != nil { + return classify(fmt.Errorf("apply %s: %w", objectID(obj), err)) + } + return nil +} + +func (a *applier) remove(ctx context.Context, obj *unstructured.Unstructured) error { + ri, err := a.resource(obj) + if meta.IsNoMatchError(err) { + return nil + } + if err != nil { + return classify(fmt.Errorf("delete %s: %w", objectID(obj), err)) + } + err = ri.Delete(ctx, obj.GetName(), metav1.DeleteOptions{}) + if err != nil && !apierrors.IsNotFound(err) { + return classify(fmt.Errorf("delete %s: %w", objectID(obj), err)) + } + return waitDeleted(ctx, ri, obj.GetName()) +} + +func waitDeleted(ctx context.Context, ri dynamic.ResourceInterface, name string) error { + deadline := time.NewTimer(15 * time.Second) + defer deadline.Stop() + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + for { + _, err := ri.Get(ctx, name, metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + if err != nil { + return fmt.Errorf("delete %s: %w", name, err) + } + return fmt.Errorf("delete %s timed out", name) + case <-ticker.C: + } + } +} + +func (a *applier) resource(obj *unstructured.Unstructured) (dynamic.ResourceInterface, error) { + gvk := obj.GroupVersionKind() + mapping, err := a.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + if meta.IsNoMatchError(err) { + a.cache.Invalidate() + a.mapper.Reset() + mapping, err = a.mapper.RESTMapping(gvk.GroupKind(), gvk.Version) + } + if err != nil { + return nil, err + } + ri := a.dynamic.Resource(mapping.Resource) + if mapping.Scope.Name() != meta.RESTScopeNameNamespace { + return ri, nil + } + ns := obj.GetNamespace() + if ns == "" { + return nil, fatalError{err: fmt.Errorf("%s has no namespace", objectID(obj))} + } + return ri.Namespace(ns), nil +} + +func classify(err error) error { + if apierrors.IsInvalid(err) || apierrors.IsBadRequest(err) || apierrors.IsUnauthorized(err) || apierrors.IsMethodNotSupported(err) { + return fatalError{err: err} + } + return err +} + +func objectID(obj *unstructured.Unstructured) string { + if ns := obj.GetNamespace(); ns != "" { + return obj.GetKind() + " " + ns + "/" + obj.GetName() + } + return obj.GetKind() + " " + obj.GetName() +} + +func decode(body []byte) ([]*unstructured.Unstructured, error) { + dec := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(body), 4096) + var out []*unstructured.Unstructured + for { + obj := &unstructured.Unstructured{} + err := dec.Decode(obj) + if errors.Is(err, io.EOF) { + return out, nil + } + if err != nil { + return nil, fmt.Errorf("decode manifest: %w", err) + } + if len(obj.Object) == 0 || obj.GetKind() == "" || obj.GetName() == "" { + continue + } + out = append(out, obj) + } +} diff --git a/kube/internal/stage/charts.go b/kube/internal/stage/charts.go new file mode 100644 index 0000000..213a7c9 --- /dev/null +++ b/kube/internal/stage/charts.go @@ -0,0 +1,239 @@ +package stage + +import ( + "bytes" + "errors" + "fmt" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/charts" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "go.yaml.in/yaml/v3" +) + +// chartOrigin is the in-cluster address of this apiserver. +const chartOrigin = "https://kubernetes.default.svc" + +type chartObject struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata objectMeta `yaml:"metadata"` + Spec chartSpec `yaml:"spec"` +} + +type objectMeta struct { + Name string `yaml:"name"` + Namespace string `yaml:"namespace"` +} + +type chartSpec struct { + Chart string `yaml:"chart"` + TargetNamespace string `yaml:"targetNamespace,omitempty"` + CreateNamespace bool `yaml:"createNamespace,omitempty"` + FailurePolicy string `yaml:"failurePolicy,omitempty"` + ForceConflicts bool `yaml:"forceConflicts,omitempty"` + ValuesContent string `yaml:"valuesContent,omitempty"` +} + +// helmChartManifests renders the Traefik, Gateway API CRD, and cert-manager releases. +// The chart URLs point at this apiserver. Nothing is returned when the Helm +// controller is disabled. The Gateway API chart installs CRDs only. Traefik +// stays an Ingress controller. +func helmChartManifests(srv config.Server) ([]manifest, error) { + if srv.DisableHelmController { + return nil, nil + } + names, err := charts.Names() + if err != nil { + return nil, err + } + traefikCRD, err := chartDocument(names, "traefik-crd", "", false, nil) + if err != nil { + return nil, err + } + traefikValues, err := traefikValues(srv) + if err != nil { + return nil, err + } + traefik, err := chartDocument(names, "traefik", "", false, traefikValues) + if err != nil { + return nil, err + } + gateway, err := chartDocument(names, "gateway-api-crd", "", false, nil) + if err != nil { + return nil, err + } + certValues, err := certManagerValues(srv) + if err != nil { + return nil, err + } + cert, err := chartDocument(names, "cert-manager", "cert-manager", true, certValues) + if err != nil { + return nil, err + } + return []manifest{ + { + name: "traefik", + enabled: !disabled(srv.Disable, "traefik"), + body: joinYAML(traefikCRD, traefik), + }, + { + name: "gateway-api-crd", + enabled: !disabled(srv.Disable, "gateway-api-crd"), + body: gateway, + }, + { + name: "cert-manager", + enabled: !addonOff(srv.Disable, "cert-manager"), + body: cert, + }, + }, nil +} + +func chartDocument(names []string, chart, namespace string, createNamespace bool, values map[string]any) ([]byte, error) { + file, err := chartFile(names, chart) + if err != nil { + return nil, err + } + spec := chartSpec{ + Chart: chartOrigin + charts.Prefix + file, + FailurePolicy: "retry", + ForceConflicts: true, + } + if namespace != "" { + spec.TargetNamespace = namespace + spec.CreateNamespace = createNamespace + } + if values != nil { + raw, err := yaml.Marshal(values) + if err != nil { + return nil, fmt.Errorf("chart %s values: %w", chart, err) + } + spec.ValuesContent = string(raw) + } + body, err := yaml.Marshal(chartObject{ + APIVersion: "helm.cattle.io/v1", + Kind: "HelmChart", + Metadata: objectMeta{Name: chart, Namespace: "kube-system"}, + Spec: spec, + }) + if err != nil { + return nil, fmt.Errorf("chart %s: %w", chart, err) + } + return body, nil +} + +func chartFile(names []string, chart string) (string, error) { + version := airgap.ChartVersion(chart) + if version == "" { + return "", fmt.Errorf("chart %s has no pinned version", chart) + } + want := chart + "-" + version + ".tgz" + for _, name := range names { + if name == want { + return name, nil + } + } + return "", fmt.Errorf("chart %s is not embedded", chart) +} + +func traefikValues(srv config.Server) (map[string]any, error) { + repository, tag, digest, err := chartImage(srv.SystemDefaultRegistry, "library/traefik") + if err != nil { + return nil, err + } + registry, name, ok := strings.Cut(repository, "/") + if !ok || registry == "" || name == "" { + return nil, errors.New("pinned image library/traefik has no registry") + } + return map[string]any{ + "image": map[string]any{ + "registry": registry, + "repository": name, + "tag": tag, + "digest": digest, + }, + "ports": map[string]any{ + "web": map[string]any{"exposedPort": 80}, + "websecure": map[string]any{"exposedPort": 443}, + }, + "service": map[string]any{ + "spec": map[string]any{"type": "LoadBalancer"}, + }, + }, nil +} + +func certManagerValues(srv config.Server) (map[string]any, error) { + controller, err := imageValue(srv.SystemDefaultRegistry, "cert-manager-controller") + if err != nil { + return nil, err + } + webhook, err := imageValue(srv.SystemDefaultRegistry, "cert-manager-webhook") + if err != nil { + return nil, err + } + cainjector, err := imageValue(srv.SystemDefaultRegistry, "cert-manager-cainjector") + if err != nil { + return nil, err + } + startup, err := imageValue(srv.SystemDefaultRegistry, "cert-manager-startupapicheck") + if err != nil { + return nil, err + } + solver, err := imageValue(srv.SystemDefaultRegistry, "cert-manager-acmesolver") + if err != nil { + return nil, err + } + return map[string]any{ + "acmesolver": map[string]any{"image": solver}, + "cainjector": map[string]any{"image": cainjector}, + "crds": map[string]any{"enabled": true}, + "image": controller, + "startupapicheck": map[string]any{"image": startup}, + "webhook": map[string]any{"image": webhook}, + }, nil +} + +func imageValue(registry, repo string) (map[string]any, error) { + repository, tag, digest, err := chartImage(registry, repo) + if err != nil { + return nil, err + } + return map[string]any{ + "digest": digest, + "repository": repository, + "tag": tag, + }, nil +} + +// chartImage splits a pinned reference into repository, tag, and digest. +// repository includes the registry. An optional system registry is already applied. +func chartImage(registry, repo string) (string, string, string, error) { + ref, err := imageRef(registry, repo) + if err != nil { + return "", "", "", err + } + name, digest, ok := strings.Cut(ref, "@") + if !ok || !strings.HasPrefix(digest, "sha256:") { + return "", "", "", fmt.Errorf("pinned image %s has no digest", repo) + } + slash := strings.LastIndex(name, "/") + colon := strings.LastIndex(name, ":") + if colon <= slash { + return "", "", "", fmt.Errorf("pinned image %s has no tag", repo) + } + return name[:colon], name[colon+1:], digest, nil +} + +func joinYAML(docs ...[]byte) []byte { + var buf bytes.Buffer + for i, doc := range docs { + if i > 0 { + buf.WriteString("---\n") + } + buf.Write(bytes.TrimSpace(doc)) + buf.WriteByte('\n') + } + return buf.Bytes() +} diff --git a/kube/internal/stage/charts_test.go b/kube/internal/stage/charts_test.go new file mode 100644 index 0000000..98a7175 --- /dev/null +++ b/kube/internal/stage/charts_test.go @@ -0,0 +1,378 @@ +package stage + +import ( + "bytes" + "os" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/charts" + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + "go.yaml.in/yaml/v3" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/klog/v2" +) + +func TestHelmChartsUseLocalURLs(t *testing.T) { + srv := config.Defaults() + srv.SystemDefaultRegistry = "registry.example:5000" + docs, err := helmChartManifests(srv) + if err != nil { + t.Fatal(err) + } + if len(docs) != 3 { + t.Fatalf("charts %d", len(docs)) + } + body := map[string]string{} + for _, doc := range docs { + if !doc.enabled { + t.Fatalf("%s disabled", doc.name) + } + text := string(doc.body) + for _, absent := range []string{"klipper-lb", "datasance", "potctl", "iofogctl"} { + if strings.Contains(text, absent) { + t.Fatalf("%s contains %s", doc.name, absent) + } + } + body[doc.name] = text + } + names, err := charts.Names() + if err != nil { + t.Fatal(err) + } + objs, err := decode([]byte(body["traefik"])) + if err != nil { + t.Fatal(err) + } + if len(objs) != 2 { + t.Fatalf("traefik documents %d", len(objs)) + } + crdChart := find(t, objs, "HelmChart", "traefik-crd") + traefik := find(t, objs, "HelmChart", "traefik") + if crdChart.GetNamespace() != "kube-system" || traefik.GetNamespace() != "kube-system" { + t.Fatal("charts are not in kube-system") + } + assertChartURL(t, nestedString(t, crdChart, "spec", "chart"), names, "traefik-crd") + assertChartURL(t, nestedString(t, traefik, "spec", "chart"), names, "traefik") + var values traefikChartValues + if err := yaml.Unmarshal([]byte(nestedString(t, traefik, "spec", "valuesContent")), &values); err != nil { + t.Fatal(err) + } + if values.Service.Spec.Type != "LoadBalancer" { + t.Fatalf("service %s", values.Service.Spec.Type) + } + if values.Ports.Web.ExposedPort != 80 || values.Ports.Websecure.ExposedPort != 443 { + t.Fatalf("ports %#v", values.Ports) + } + ref, err := imageRef(srv.SystemDefaultRegistry, "library/traefik") + if err != nil { + t.Fatal(err) + } + image := values.Image.Registry + "/" + values.Image.Repository + ":" + values.Image.Tag + "@" + values.Image.Digest + if image != ref { + t.Fatalf("image %s", image) + } + + certObjs, err := decode([]byte(body["cert-manager"])) + if err != nil { + t.Fatal(err) + } + cert := find(t, certObjs, "HelmChart", "cert-manager") + assertChartURL(t, nestedString(t, cert, "spec", "chart"), names, "cert-manager") + if nestedString(t, cert, "spec", "targetNamespace") != "cert-manager" { + t.Fatalf("namespace %#v", cert.Object) + } + var certValues certManagerChartValues + if err := yaml.Unmarshal([]byte(nestedString(t, cert, "spec", "valuesContent")), &certValues); err != nil { + t.Fatal(err) + } + if !certValues.CRDs.Enabled { + t.Fatal("crds are disabled") + } + for _, got := range []struct { + repo string + image chartImageValue + }{ + {"cert-manager-controller", certValues.Image}, + {"cert-manager-webhook", certValues.Webhook.Image}, + {"cert-manager-cainjector", certValues.Cainjector.Image}, + {"cert-manager-startupapicheck", certValues.Startup.Image}, + {"cert-manager-acmesolver", certValues.Solver.Image}, + } { + want, err := imageRef(srv.SystemDefaultRegistry, got.repo) + if err != nil { + t.Fatal(err) + } + if got.image.Repository+":"+got.image.Tag+"@"+got.image.Digest != want { + t.Fatalf("%s image %s", got.repo, got.image.Repository) + } + if !strings.HasPrefix(got.image.Repository, "registry.example:5000/") { + t.Fatalf("%s registry %s", got.repo, got.image.Repository) + } + } +} + +func TestDisableSkipsOnlyThatChart(t *testing.T) { + base := config.Defaults() + base.Disable = []string{"servicelb"} + kept, err := helmChartManifests(base) + if err != nil { + t.Fatal(err) + } + for _, doc := range kept { + if !doc.enabled { + t.Fatalf("%s disabled by servicelb", doc.name) + } + } + for _, name := range []string{"traefik", "gateway-api-crd", "cert-manager"} { + srv := base + srv.Disable = []string{name} + docs, err := helmChartManifests(srv) + if err != nil { + t.Fatal(err) + } + for _, doc := range docs { + if doc.name == name && doc.enabled { + t.Fatalf("%s stayed enabled", name) + } + if doc.name != name && !doc.enabled { + t.Fatalf("disabling %s dropped %s", name, doc.name) + } + } + } + off := base + off.DisableHelmController = true + docs, err := helmChartManifests(off) + if err != nil { + t.Fatal(err) + } + if len(docs) != 0 { + t.Fatalf("charts %d", len(docs)) + } +} + +func TestClusterIssuerRules(t *testing.T) { + var buf bytes.Buffer + klog.LogToStderr(false) + klog.SetOutput(&buf) + t.Cleanup(func() { + klog.Flush() + klog.LogToStderr(true) + klog.SetOutput(os.Stderr) + }) + + empty := config.Defaults() + empty.ClusterIssuerEmail = " " + body, skip, err := clusterIssuer(empty) + if err != nil || skip { + t.Fatalf("skip %v err %v", skip, err) + } + objs, err := decode(body) + if err != nil { + t.Fatal(err) + } + assertSelfSigned(t, objs) + if issuerNamed(objs, "letsencrypt-prod") != nil { + t.Fatal("letsencrypt issuer written without an email") + } + klog.Flush() + if buf.Len() != 0 { + t.Fatalf("empty email logged %q", buf.String()) + } + + buf.Reset() + skipped := empty + skipped.ClusterIssuerEmail = "ops@example.com" + skipped.Disable = []string{"traefik", "cert-manager"} + if err := ApplyIssuer(t.Context(), "", skipped); err != nil { + t.Fatal(err) + } + klog.Flush() + if strings.Count(buf.String(), "letsencrypt cluster issuer was skipped") != 1 { + t.Fatalf("log %q", buf.String()) + } + + buf.Reset() + onlyTraefik := skipped + onlyTraefik.Disable = []string{"traefik"} + body, skip, err = clusterIssuer(onlyTraefik) + if err != nil || !skip { + t.Fatalf("skip %v err %v", skip, err) + } + objs, err = decode(body) + if err != nil { + t.Fatal(err) + } + assertSelfSigned(t, objs) + if issuerNamed(objs, "letsencrypt-prod") != nil { + t.Fatal("letsencrypt issuer written with traefik disabled") + } + + buf.Reset() + helmOff := empty + helmOff.ClusterIssuerEmail = "ops@example.com" + helmOff.DisableHelmController = true + body, skip, err = clusterIssuer(helmOff) + if err != nil || skip || len(bytes.TrimSpace(body)) != 0 { + t.Fatalf("skip %v body %d err %v", skip, len(body), err) + } + if err := ApplyIssuer(t.Context(), "", helmOff); err != nil { + t.Fatal(err) + } + klog.Flush() + if buf.Len() != 0 { + t.Fatalf("helm disable logged %q", buf.String()) + } + + buf.Reset() + loadBalancerOff := empty + loadBalancerOff.ClusterIssuerEmail = "ops@example.com" + loadBalancerOff.Disable = []string{"servicelb"} + body, skip, err = clusterIssuer(loadBalancerOff) + if err != nil { + t.Fatal(err) + } + if skip || len(body) == 0 || buf.Len() != 0 { + t.Fatalf("skip %v body %d log %q", skip, len(body), buf.String()) + } + objs, err = decode(body) + if err != nil { + t.Fatal(err) + } + assertSelfSigned(t, objs) + issuer := find(t, objs, "ClusterIssuer", "letsencrypt-prod") + if issuer.GetAPIVersion() != "cert-manager.io/v1" { + t.Fatalf("version %s", issuer.GetAPIVersion()) + } + if nestedString(t, issuer, "spec", "acme", "email") != "ops@example.com" { + t.Fatalf("email %#v", issuer.Object) + } + if nestedString(t, issuer, "spec", "acme", "server") != "https://acme-v02.api.letsencrypt.org/directory" { + t.Fatalf("server %#v", issuer.Object) + } + if nestedString(t, issuer, "spec", "acme", "privateKeySecretRef", "name") != "letsencrypt-prod-account-key" { + t.Fatalf("key %#v", issuer.Object) + } + solvers, found, err := unstructured.NestedSlice(issuer.Object, "spec", "acme", "solvers") + if err != nil || !found || len(solvers) != 1 { + t.Fatalf("solvers %#v %v", issuer.Object, err) + } + solver, ok := solvers[0].(map[string]any) + if !ok { + t.Fatalf("solver %#v", solvers[0]) + } + class, found, err := unstructured.NestedString(solver, "http01", "ingress", "class") + if err != nil || !found || class != "traefik" { + t.Fatalf("class %s %v", class, err) + } +} + +func TestChartVersionsMatchPins(t *testing.T) { + docs, err := helmChartManifests(config.Defaults()) + if err != nil { + t.Fatal(err) + } + var text string + for _, doc := range docs { + text += string(doc.body) + } + for _, chart := range []string{"traefik", "traefik-crd", "gateway-api-crd", "cert-manager"} { + version := airgap.ChartVersion(chart) + if version == "" || !strings.Contains(text, chart+"-"+version+".tgz") { + t.Fatalf("chart %s version %s", chart, version) + } + } +} + +type chartImageRef struct { + Registry string `yaml:"registry"` + Repository string `yaml:"repository"` + Tag string `yaml:"tag"` + Digest string `yaml:"digest"` +} + +type serviceTypeSpec struct { + Type string `yaml:"type"` +} + +type serviceSpecBody struct { + Spec serviceTypeSpec `yaml:"spec"` +} + +type exposedPort struct { + ExposedPort int `yaml:"exposedPort"` +} + +type traefikPorts struct { + Web exposedPort `yaml:"web"` + Websecure exposedPort `yaml:"websecure"` +} + +type traefikChartValues struct { + Image chartImageRef `yaml:"image"` + Service serviceSpecBody `yaml:"service"` + Ports traefikPorts `yaml:"ports"` +} + +type chartImageValue struct { + Repository string `yaml:"repository"` + Tag string `yaml:"tag"` + Digest string `yaml:"digest"` +} + +type crdToggle struct { + Enabled bool `yaml:"enabled"` +} + +type chartImageHolder struct { + Image chartImageValue `yaml:"image"` +} + +type certManagerChartValues struct { + CRDs crdToggle `yaml:"crds"` + Image chartImageValue `yaml:"image"` + Webhook chartImageHolder `yaml:"webhook"` + Cainjector chartImageHolder `yaml:"cainjector"` + Startup chartImageHolder `yaml:"startupapicheck"` + Solver chartImageHolder `yaml:"acmesolver"` +} + +func assertSelfSigned(t *testing.T, objs []*unstructured.Unstructured) { + t.Helper() + issuer := find(t, objs, "ClusterIssuer", "selfsigned") + if issuer.GetAPIVersion() != "cert-manager.io/v1" { + t.Fatalf("version %s", issuer.GetAPIVersion()) + } + spec, found, err := unstructured.NestedMap(issuer.Object, "spec", "selfSigned") + if err != nil || !found || len(spec) != 0 { + t.Fatalf("selfSigned %#v %v", issuer.Object, err) + } +} + +func issuerNamed(objs []*unstructured.Unstructured, name string) *unstructured.Unstructured { + for _, obj := range objs { + if obj.GetKind() == "ClusterIssuer" && obj.GetName() == name { + return obj + } + } + return nil +} + +func assertChartURL(t *testing.T, got string, names []string, chart string) { + t.Helper() + version := airgap.ChartVersion(chart) + want := "https://kubernetes.default.svc" + charts.Prefix + chart + "-" + version + ".tgz" + if got != want { + t.Fatalf("chart url %s", got) + } + found := false + for _, name := range names { + if name == chart+"-"+version+".tgz" { + found = true + } + } + if !found { + t.Fatalf("embedded charts %v", names) + } +} diff --git a/kube/internal/stage/coredns.yaml b/kube/internal/stage/coredns.yaml new file mode 100644 index 0000000..232c256 --- /dev/null +++ b/kube/internal/stage/coredns.yaml @@ -0,0 +1,172 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: kube-system +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: coredns + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: system:coredns + labels: + kubernetes.io/bootstrapping: rbac-defaults +rules: + - apiGroups: [""] + resources: ["endpoints", "services", "pods", "namespaces"] + verbs: ["list", "watch"] + - apiGroups: ["discovery.k8s.io"] + resources: ["endpointslices"] + verbs: ["list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: system:coredns + annotations: + rbac.authorization.kubernetes.io/autoupdate: "true" + labels: + kubernetes.io/bootstrapping: rbac-defaults +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:coredns +subjects: + - kind: ServiceAccount + name: coredns + namespace: kube-system +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: coredns + namespace: kube-system +data: + Corefile: | + .:53 { + errors + health + ready + kubernetes __CLUSTER_DOMAIN__ in-addr.arpa ip6.arpa { + pods insecure + fallthrough in-addr.arpa ip6.arpa + } + cache 30 + loop + reload + loadbalance + forward . /etc/resolv.conf + } +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: coredns + namespace: kube-system + labels: + k8s-app: kube-dns +spec: + replicas: 1 + revisionHistoryLimit: 0 + strategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 + selector: + matchLabels: + k8s-app: kube-dns + template: + metadata: + labels: + k8s-app: kube-dns + spec: + serviceAccountName: coredns + tolerations: + - key: CriticalAddonsOnly + operator: Exists + - key: node-role.kubernetes.io/control-plane + operator: Exists + effect: NoSchedule + nodeSelector: + kubernetes.io/os: linux + dnsPolicy: Default + containers: + - name: coredns + image: "__COREDNS_IMAGE__" + imagePullPolicy: IfNotPresent + args: ["-conf", "/etc/coredns/Corefile"] + resources: + limits: + memory: 170Mi + requests: + cpu: 100m + memory: 70Mi + volumeMounts: + - name: config-volume + mountPath: /etc/coredns + readOnly: true + ports: + - containerPort: 53 + name: dns + protocol: UDP + - containerPort: 53 + name: dns-tcp + protocol: TCP + securityContext: + allowPrivilegeEscalation: false + capabilities: + add: ["NET_BIND_SERVICE"] + drop: ["ALL"] + readOnlyRootFilesystem: true + livenessProbe: + httpGet: + path: /health + port: 8080 + scheme: HTTP + initialDelaySeconds: 60 + periodSeconds: 10 + timeoutSeconds: 1 + successThreshold: 1 + failureThreshold: 3 + readinessProbe: + httpGet: + path: /ready + port: 8181 + scheme: HTTP + initialDelaySeconds: 0 + periodSeconds: 2 + timeoutSeconds: 1 + successThreshold: 1 + failureThreshold: 3 + volumes: + - name: config-volume + configMap: + name: coredns + items: + - key: Corefile + path: Corefile +--- +apiVersion: v1 +kind: Service +metadata: + name: kube-dns + namespace: kube-system + labels: + k8s-app: kube-dns + kubernetes.io/cluster-service: "true" + kubernetes.io/name: CoreDNS +spec: + selector: + k8s-app: kube-dns + clusterIP: __CLUSTER_DNS__ + ports: + - name: dns + port: 53 + protocol: UDP + - name: dns-tcp + port: 53 + protocol: TCP diff --git a/kube/internal/stage/doc.go b/kube/internal/stage/doc.go new file mode 100644 index 0000000..33a4419 --- /dev/null +++ b/kube/internal/stage/doc.go @@ -0,0 +1,2 @@ +// Package stage applies addon manifests once the API server is ready. +package stage diff --git a/kube/internal/stage/helmchart-crd.yaml b/kube/internal/stage/helmchart-crd.yaml new file mode 100644 index 0000000..2321a0d --- /dev/null +++ b/kube/internal/stage/helmchart-crd.yaml @@ -0,0 +1,864 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.21.0 + name: helmcharts.helm.cattle.io +spec: + group: helm.cattle.io + names: + kind: HelmChart + listKind: HelmChartList + plural: helmcharts + shortNames: + - hc + singular: helmchart + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.repo + name: Repo + type: string + - jsonPath: .spec.chart + name: Chart + type: string + - jsonPath: .spec.version + name: Version + type: string + - jsonPath: .spec.targetNamespace + name: TargetNamespace + type: string + - jsonPath: .spec.bootstrap + name: Bootstrap + type: boolean + - jsonPath: .status.conditions[?(@.type=='Failed')].status + name: Failed + type: string + - jsonPath: .status.jobName + name: Job + priority: 10 + type: string + name: v1 + schema: + openAPIV3Schema: + description: HelmChart represents configuration and state for the deployment + of a Helm chart. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: HelmChartSpec represents the user-configurable details for + installation and upgrade of a Helm chart release. + properties: + authPassCredentials: + description: |- + Pass Basic auth credentials to all domains. + Helm CLI positional argument/flag: `--pass-credentials` + type: boolean + authSecret: + description: Reference to Secret of type kubernetes.io/basic-auth + holding Basic auth credentials for the Chart repo. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + backOffLimit: + description: Specify the number of retries before considering the + helm job failed. + format: int32 + type: integer + bootstrap: + description: Set to True if this chart is needed to bootstrap the + cluster (Cloud Controller Manager, CNI, etc). + type: boolean + chart: + description: |- + Helm Chart name in repository, or complete HTTPS URL to chart archive (.tgz) + Helm CLI positional argument/flag: `CHART` + type: string + chartContent: + description: |- + Base64-encoded chart archive .tgz; overides `.spec.chart` and `.spec.version`. + Helm CLI positional argument/flag: `CHART` + type: string + createNamespace: + description: |- + Create target namespace if not present. + Helm CLI positional argument/flag: `--create-namespace` + type: boolean + dockerRegistrySecret: + description: Reference to Secret of type kubernetes.io/dockerconfigjson + holding Docker auth credentials for the OCI-based registry acting + as the Chart repo. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + driver: + default: secret + description: |- + Helm storage driver to use for this chart's release metadata. + `secret` stores releases in Kubernetes Secrets (default). + `configmap` stores releases in ConfigMaps. + This field is effectively immutable after the first install; changing the storage backend is not a supported migration path. + Helm CLI environment variable: `HELM_DRIVER` + enum: + - secret + - configmap + type: string + x-kubernetes-validations: + - message: driver is immutable after creation + optionalOldSelf: true + rule: '!oldSelf.hasValue() || self == oldSelf.value()' + failurePolicy: + default: reinstall + description: |- + Configures handling of failed chart installation or upgrades. + - `abort` will take no action and leave the chart in a failed state so that the administrator can manually resolve the error. + - `reinstall` will perform a clean uninstall and reinstall of the chart; this is the default behavior. + - `retry` will attempt to retry the install or upgrade whenever chart configuration changes. + enum: + - abort + - reinstall + - retry + type: string + forceConflicts: + description: |- + Set to true if helm should configure server-side apply to force changes when conflicts arise in ownership of managed fields. + Helm CLI positional argument/flag: `--force-conflicts` + type: boolean + helmVersion: + description: DEPRECATED. Helm version to use. Only v3 is currently + supported. + type: string + insecureSkipTLSVerify: + description: |- + Skip TLS certificate checks for the chart download. + Helm CLI positional argument/flag: `--insecure-skip-tls-verify` + type: boolean + jobImage: + description: Specify the image to use for tht helm job pod when installing + or upgrading the helm chart. + type: string + plainHTTP: + description: |- + Use insecure HTTP connections for the chart download. + Helm CLI positional argument/flag: `--plain-http` + type: boolean + podSecurityContext: + description: Custom PodSecurityContext for the helm job pod. + properties: + appArmorProfile: + description: |- + appArmorProfile is the AppArmor options to use by the containers in this pod. + Note that this field cannot be set when spec.os.name is windows. + properties: + localhostProfile: + description: |- + localhostProfile indicates a profile loaded on the node that should be used. + The profile must be preconfigured on the node to work. + Must match the loaded name of the profile. + Must be set if and only if type is "Localhost". + type: string + type: + description: |- + type indicates which kind of AppArmor profile will be applied. + Valid options are: + Localhost - a profile pre-loaded on the node. + RuntimeDefault - the container runtime's default profile. + Unconfined - no AppArmor enforcement. + type: string + required: + - type + type: object + fsGroup: + description: |- + A special supplemental group that applies to all containers in a pod. + Some volume types allow the Kubelet to change the ownership of that volume + to be owned by the pod: + + 1. The owning GID will be the FSGroup + 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) + 3. The permission bits are OR'd with rw-rw---- + + If unset, the Kubelet will not modify the ownership and permissions of any volume. + Note that this field cannot be set when spec.os.name is windows. + format: int64 + type: integer + fsGroupChangePolicy: + description: |- + fsGroupChangePolicy defines behavior of changing ownership and permission of the volume + before being exposed inside Pod. This field will only apply to + volume types which support fsGroup based ownership(and permissions). + It will have no effect on ephemeral volume types such as: secret, configmaps + and emptydir. + Valid values are "OnRootMismatch" and "Always". If not specified, "Always" is used. + Note that this field cannot be set when spec.os.name is windows. + type: string + runAsGroup: + description: |- + The GID to run the entrypoint of the container process. + Uses runtime default if unset. + May also be set in SecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence + for that container. + Note that this field cannot be set when spec.os.name is windows. + format: int64 + type: integer + runAsNonRoot: + description: |- + Indicates that the container must run as a non-root user. + If true, the Kubelet will validate the image at runtime to ensure that it + does not run as UID 0 (root) and fail to start the container if it does. + If unset or false, no such validation will be performed. + May also be set in SecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + type: boolean + runAsUser: + description: |- + The UID to run the entrypoint of the container process. + Defaults to user specified in image metadata if unspecified. + May also be set in SecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence + for that container. + Note that this field cannot be set when spec.os.name is windows. + format: int64 + type: integer + seLinuxChangePolicy: + description: |- + seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. + It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. + Valid values are "MountOption" and "Recursive". + + "Recursive" means relabeling of all files on all Pod volumes by the container runtime. + This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node. + + "MountOption" mounts all eligible Pod volumes with `-o context` mount option. + This requires all Pods that share the same volume to use the same SELinux label. + It is not possible to share the same volume among privileged and unprivileged Pods. + Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes + whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their + CSIDriver instance. Other volumes are always re-labelled recursively. + "MountOption" value is allowed only when SELinuxMount feature gate is enabled. + + If not specified and SELinuxMount feature gate is enabled, "MountOption" is used. + If not specified and SELinuxMount feature gate is disabled, "MountOption" is used for ReadWriteOncePod volumes + and "Recursive" for all other volumes. + + This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers. + + All Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. + Note that this field cannot be set when spec.os.name is windows. + type: string + seLinuxOptions: + description: |- + The SELinux context to be applied to all containers. + If unspecified, the container runtime will allocate a random SELinux context for each + container. May also be set in SecurityContext. If set in + both SecurityContext and PodSecurityContext, the value specified in SecurityContext + takes precedence for that container. + Note that this field cannot be set when spec.os.name is windows. + properties: + level: + description: Level is SELinux level label that applies to + the container. + type: string + role: + description: Role is a SELinux role label that applies to + the container. + type: string + type: + description: Type is a SELinux type label that applies to + the container. + type: string + user: + description: User is a SELinux user label that applies to + the container. + type: string + type: object + seccompProfile: + description: |- + The seccomp options to use by the containers in this pod. + Note that this field cannot be set when spec.os.name is windows. + properties: + localhostProfile: + description: |- + localhostProfile indicates a profile defined in a file on the node should be used. + The profile must be preconfigured on the node to work. + Must be a descending path, relative to the kubelet's configured seccomp profile location. + Must be set if type is "Localhost". Must NOT be set for any other type. + type: string + type: + description: |- + type indicates which kind of seccomp profile will be applied. + Valid options are: + + Localhost - a profile defined in a file on the node should be used. + RuntimeDefault - the container runtime default profile should be used. + Unconfined - no profile should be applied. + type: string + required: + - type + type: object + supplementalGroups: + description: |- + A list of groups applied to the first process run in each container, in + addition to the container's primary GID and fsGroup (if specified). If + the SupplementalGroupsPolicy feature is enabled, the + supplementalGroupsPolicy field determines whether these are in addition + to or instead of any group memberships defined in the container image. + If unspecified, no additional groups are added, though group memberships + defined in the container image may still be used, depending on the + supplementalGroupsPolicy field. + Note that this field cannot be set when spec.os.name is windows. + items: + format: int64 + type: integer + type: array + x-kubernetes-list-type: atomic + supplementalGroupsPolicy: + description: |- + Defines how supplemental groups of the first container processes are calculated. + Valid values are "Merge" and "Strict". If not specified, "Merge" is used. + (Alpha) Using the field requires the SupplementalGroupsPolicy feature gate to be enabled + and the container runtime must implement support for this feature. + Note that this field cannot be set when spec.os.name is windows. + type: string + sysctls: + description: |- + Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported + sysctls (by the container runtime) might fail to launch. + Note that this field cannot be set when spec.os.name is windows. + items: + description: Sysctl defines a kernel parameter to be set + properties: + name: + description: Name of a property to set + type: string + value: + description: Value of a property to set + type: string + required: + - name + - value + type: object + type: array + x-kubernetes-list-type: atomic + windowsOptions: + description: |- + The Windows specific settings applied to all containers. + If unspecified, the options within a container's SecurityContext will be used. + If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. + Note that this field cannot be set when spec.os.name is linux. + properties: + gmsaCredentialSpec: + description: |- + GMSACredentialSpec is where the GMSA admission webhook + (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the + GMSA credential spec named by the GMSACredentialSpecName field. + type: string + gmsaCredentialSpecName: + description: GMSACredentialSpecName is the name of the GMSA + credential spec to use. + type: string + hostProcess: + description: |- + HostProcess determines if a container should be run as a 'Host Process' container. + All of a Pod's containers must have the same effective HostProcess value + (it is not allowed to have a mix of HostProcess containers and non-HostProcess containers). + In addition, if HostProcess is true then HostNetwork must also be set to true. + type: boolean + runAsUserName: + description: |- + The UserName in Windows to run the entrypoint of the container process. + Defaults to the user specified in image metadata if unspecified. + May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + type: string + type: object + type: object + repo: + description: |- + Helm Chart repository URL. + Helm CLI positional argument/flag: `--repo` + type: string + repoCA: + description: |- + Verify certificates of HTTPS-enabled servers using this CA bundle. Should be a string containing one or more PEM-encoded CA Certificates. + Helm CLI positional argument/flag: `--ca-file` + type: string + repoCAConfigMap: + description: |- + Reference to a ConfigMap containing CA Certificates to be be trusted by Helm. Can be used along with or instead of `.spec.repoCA` + Helm CLI positional argument/flag: `--ca-file` + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + securityContext: + description: custom SecurityContext for the helm job pod. + properties: + allowPrivilegeEscalation: + description: |- + AllowPrivilegeEscalation controls whether a process can gain more + privileges than its parent process. This bool directly controls if + the no_new_privs flag will be set on the container process. + AllowPrivilegeEscalation is true always when the container is: + 1) run as Privileged + 2) has CAP_SYS_ADMIN + Note that this field cannot be set when spec.os.name is windows. + type: boolean + appArmorProfile: + description: |- + appArmorProfile is the AppArmor options to use by this container. If set, this profile + overrides the pod's appArmorProfile. + Note that this field cannot be set when spec.os.name is windows. + properties: + localhostProfile: + description: |- + localhostProfile indicates a profile loaded on the node that should be used. + The profile must be preconfigured on the node to work. + Must match the loaded name of the profile. + Must be set if and only if type is "Localhost". + type: string + type: + description: |- + type indicates which kind of AppArmor profile will be applied. + Valid options are: + Localhost - a profile pre-loaded on the node. + RuntimeDefault - the container runtime's default profile. + Unconfined - no AppArmor enforcement. + type: string + required: + - type + type: object + capabilities: + description: |- + The capabilities to add/drop when running containers. + Defaults to the default set of capabilities granted by the container runtime. + Note that this field cannot be set when spec.os.name is windows. + properties: + add: + description: Added capabilities + items: + description: Capability represent POSIX capabilities type + type: string + type: array + x-kubernetes-list-type: atomic + drop: + description: Removed capabilities + items: + description: Capability represent POSIX capabilities type + type: string + type: array + x-kubernetes-list-type: atomic + type: object + privileged: + description: |- + Run container in privileged mode. + Processes in privileged containers are essentially equivalent to root on the host. + Defaults to false. + Note that this field cannot be set when spec.os.name is windows. + type: boolean + procMount: + description: |- + procMount denotes the type of proc mount to use for the containers. + The default value is Default which uses the container runtime defaults for + readonly paths and masked paths. + This requires the ProcMountType feature flag to be enabled. + Note that this field cannot be set when spec.os.name is windows. + type: string + readOnlyRootFilesystem: + description: |- + Whether this container has a read-only root filesystem. + Default is false. + Note that this field cannot be set when spec.os.name is windows. + type: boolean + runAsGroup: + description: |- + The GID to run the entrypoint of the container process. + Uses runtime default if unset. + May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + Note that this field cannot be set when spec.os.name is windows. + format: int64 + type: integer + runAsNonRoot: + description: |- + Indicates that the container must run as a non-root user. + If true, the Kubelet will validate the image at runtime to ensure that it + does not run as UID 0 (root) and fail to start the container if it does. + If unset or false, no such validation will be performed. + May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + type: boolean + runAsUser: + description: |- + The UID to run the entrypoint of the container process. + Defaults to user specified in image metadata if unspecified. + May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + Note that this field cannot be set when spec.os.name is windows. + format: int64 + type: integer + seLinuxOptions: + description: |- + The SELinux context to be applied to the container. + If unspecified, the container runtime will allocate a random SELinux context for each + container. May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + Note that this field cannot be set when spec.os.name is windows. + properties: + level: + description: Level is SELinux level label that applies to + the container. + type: string + role: + description: Role is a SELinux role label that applies to + the container. + type: string + type: + description: Type is a SELinux type label that applies to + the container. + type: string + user: + description: User is a SELinux user label that applies to + the container. + type: string + type: object + seccompProfile: + description: |- + The seccomp options to use by this container. If seccomp options are + provided at both the pod & container level, the container options + override the pod options. + Note that this field cannot be set when spec.os.name is windows. + properties: + localhostProfile: + description: |- + localhostProfile indicates a profile defined in a file on the node should be used. + The profile must be preconfigured on the node to work. + Must be a descending path, relative to the kubelet's configured seccomp profile location. + Must be set if type is "Localhost". Must NOT be set for any other type. + type: string + type: + description: |- + type indicates which kind of seccomp profile will be applied. + Valid options are: + + Localhost - a profile defined in a file on the node should be used. + RuntimeDefault - the container runtime default profile should be used. + Unconfined - no profile should be applied. + type: string + required: + - type + type: object + windowsOptions: + description: |- + The Windows specific settings applied to all containers. + If unspecified, the options from the PodSecurityContext will be used. + If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. + Note that this field cannot be set when spec.os.name is linux. + properties: + gmsaCredentialSpec: + description: |- + GMSACredentialSpec is where the GMSA admission webhook + (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the + GMSA credential spec named by the GMSACredentialSpecName field. + type: string + gmsaCredentialSpecName: + description: GMSACredentialSpecName is the name of the GMSA + credential spec to use. + type: string + hostProcess: + description: |- + HostProcess determines if a container should be run as a 'Host Process' container. + All of a Pod's containers must have the same effective HostProcess value + (it is not allowed to have a mix of HostProcess containers and non-HostProcess containers). + In addition, if HostProcess is true then HostNetwork must also be set to true. + type: boolean + runAsUserName: + description: |- + The UserName in Windows to run the entrypoint of the container process. + Defaults to the user specified in image metadata if unspecified. + May also be set in PodSecurityContext. If set in both SecurityContext and + PodSecurityContext, the value specified in SecurityContext takes precedence. + type: string + type: object + type: object + serverSide: + description: |- + Set to true if helm should enable server-side apply when updating objects. Defaults to `true` for install, and `auto` for upgrade. + - `true` enables server-side apply. + - `false` disables server-side apply. + - `auto` enables server-side apply if the chart was installed with server-side apply enabled. + Helm CLI positional argument/flag: `--server-side` + enum: + - "true" + - "false" + - auto + type: string + set: + additionalProperties: + anyOf: + - type: integer + - type: string + x-kubernetes-int-or-string: true + description: |- + Override simple Chart values. These take precedence over options set via values or valuesContent. + Helm CLI positional argument/flag: `--set`, `--set-string` + type: object + takeOwnership: + description: |- + Set to True if helm should take ownership of existing resources when installing/upgrading the chart. + Helm CLI positional argument/flag: `--take-ownership` + type: boolean + targetNamespace: + description: |- + Helm Chart target namespace. + Helm CLI positional argument/flag: `--namespace` + type: string + timeout: + description: |- + Timeout for Helm operations. + Helm CLI positional argument/flag: `--timeout` + type: string + values: + description: |- + Override complex Chart values via structured YAML. Takes precedence over options set via valuesContent. + Helm CLI positional argument/flag: `--values` + x-kubernetes-preserve-unknown-fields: true + valuesContent: + description: |- + Override complex Chart values via inline YAML content. + Helm CLI positional argument/flag: `--values` + type: string + valuesSecrets: + description: |- + Override complex Chart values via references to external Secrets. + Helm CLI positional argument/flag: `--values` + items: + description: SecretSpec describes a key in a secret to load chart + values from. + properties: + ignoreUpdates: + description: |- + Ignore changes to the secret, and mark the secret as optional. + By default, the secret must exist, and changes to the secret will trigger an upgrade of the chart to apply the updated values. + If `ignoreUpdates` is true, the secret is optional, and changes to the secret will not trigger an upgrade of the chart. + type: boolean + keys: + description: Keys to read values content from. If no keys are + specified, the secret is not used. + items: + type: string + type: array + name: + description: Name of the secret. Must be in the same namespace + as the HelmChart resource. + type: string + type: object + type: array + version: + description: |- + Helm Chart version. Only used when installing from repository; ignored when .spec.chart or .spec.chartContent is used to install a specific chart archive. + Helm CLI positional argument/flag: `--version` + type: string + type: object + status: + description: HelmChartStatus represents the resulting state from processing + HelmChart events + properties: + conditions: + description: |- + `JobCreated` indicates that a job has been created to install or upgrade the chart. + `Failed` indicates that the helm job has failed and the failure policy is set to `abort`. + items: + properties: + message: + description: Human readable message indicating details about + last transition. + type: string + reason: + description: (brief) reason for the condition's last transition. + type: string + status: + description: Status of the condition, one of True, False, Unknown. + type: string + type: + description: Type of job condition. + type: string + required: + - status + - type + type: object + type: array + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + jobName: + description: The name of the job created to install or upgrade the + chart. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.21.0 + name: helmchartconfigs.helm.cattle.io +spec: + group: helm.cattle.io + names: + kind: HelmChartConfig + listKind: HelmChartConfigList + plural: helmchartconfigs + shortNames: + - hcc + singular: helmchartconfig + scope: Namespaced + versions: + - name: v1 + schema: + openAPIV3Schema: + description: |- + HelmChartConfig represents additional configuration for the installation of Helm chart release. + This resource is intended for use when additional configuration needs to be passed to a HelmChart + that is managed by an external system. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + HelmChartConfigSpec represents additional user-configurable details of an installed and configured Helm chart release. + These fields are merged with or override the corresponding fields on the related HelmChart resource. + properties: + failurePolicy: + default: reinstall + description: |- + Configures handling of failed chart installation or upgrades. + - `abort` will take no action and leave the chart in a failed state so that the administrator can manually resolve the error. + - `reinstall` will perform a clean uninstall and reinstall of the chart; this is the default behavior. + - `retry` will attempt to retry the install or upgrade whenever chart configuration changes. + enum: + - abort + - reinstall + - retry + type: string + forceConflicts: + description: |- + Set to true if helm should configure server-side apply to force changes when conflicts arise in ownership of managed fields. + Helm CLI positional argument/flag: `--force-conflicts` + type: boolean + serverSide: + description: |- + Set to true if helm should enable server-side apply when updating objects. Defaults to `true` for install, and `auto` for upgrade. + - `true` enables server-side apply. + - `false` disables server-side apply. + - `auto` enables server-side apply if the chart was installed with server-side apply enabled. + Helm CLI positional argument/flag: `--server-side` + enum: + - "true" + - "false" + - auto + type: string + values: + description: |- + Override complex Chart values via structured YAML. Takes precedence over options set via valuesContent. + Helm CLI positional argument/flag: `--values` + x-kubernetes-preserve-unknown-fields: true + valuesContent: + description: |- + Override complex Chart values via inline YAML content. + Helm CLI positional argument/flag: `--values` + type: string + valuesSecrets: + description: |- + Override complex Chart values via references to external Secrets. + Helm CLI positional argument/flag: `--values` + items: + description: SecretSpec describes a key in a secret to load chart + values from. + properties: + ignoreUpdates: + description: |- + Ignore changes to the secret, and mark the secret as optional. + By default, the secret must exist, and changes to the secret will trigger an upgrade of the chart to apply the updated values. + If `ignoreUpdates` is true, the secret is optional, and changes to the secret will not trigger an upgrade of the chart. + type: boolean + keys: + description: Keys to read values content from. If no keys are + specified, the secret is not used. + items: + type: string + type: array + name: + description: Name of the secret. Must be in the same namespace + as the HelmChart resource. + type: string + type: object + type: array + type: object + type: object + served: true + storage: true diff --git a/kube/internal/stage/images.go b/kube/internal/stage/images.go new file mode 100644 index 0000000..9ea0ac9 --- /dev/null +++ b/kube/internal/stage/images.go @@ -0,0 +1,32 @@ +package stage + +import ( + "fmt" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +// imageRef is the pinned reference for repo, prefixed when registry is set. +// repo is the repository path without a registry, such as coredns/coredns. +func imageRef(registry, repo string) (string, error) { + var match string + for _, ref := range airgap.Images() { + name, _, _ := strings.Cut(ref, "@") + got, _, ok := strings.Cut(name, ":") + if !ok { + continue + } + if got != repo && !strings.HasSuffix(got, "/"+repo) { + continue + } + if match != "" && match != ref { + return "", fmt.Errorf("more than one pinned image matches %s", repo) + } + match = ref + } + if match == "" { + return "", fmt.Errorf("pinned image %s is not on the list", repo) + } + return airgap.Resolve(registry, match), nil +} diff --git a/kube/internal/stage/issuer.go b/kube/internal/stage/issuer.go new file mode 100644 index 0000000..5fbf4a9 --- /dev/null +++ b/kube/internal/stage/issuer.go @@ -0,0 +1,157 @@ +package stage + +import ( + "bytes" + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "go.yaml.in/yaml/v3" + "k8s.io/klog/v2" +) + +// ApplyIssuer writes the selfsigned ClusterIssuer whenever cert-manager is +// staged. It also writes letsencrypt-prod when an email is configured and +// traefik is staged. It retries until cert-manager serves the ClusterIssuer +// CRD. An empty email writes no letsencrypt-prod. When the email is set and +// traefik or cert-manager is disabled, letsencrypt-prod is not written and +// one line is logged. +func ApplyIssuer(ctx context.Context, kubeconfig string, srv config.Server) error { + body, skip, err := clusterIssuer(srv) + if err != nil { + return err + } + if skip { + klog.Info("letsencrypt cluster issuer was skipped because traefik or cert-manager is disabled") + } + if len(bytes.TrimSpace(body)) == 0 { + return nil + } + if kubeconfig == "" { + return errors.New("kubeconfig is empty") + } + client, err := newApplier(kubeconfig) + if err != nil { + return err + } + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + var last error + for { + client.cache.Invalidate() + client.mapper.Reset() + last = client.sync(ctx, body, true) + if last == nil { + return nil + } + if isFatal(last) { + return last + } + select { + case <-ctx.Done(): + return fmt.Errorf("cluster issuer was not applied: %w", ctx.Err()) + case <-ticker.C: + } + } +} + +func clusterIssuer(srv config.Server) ([]byte, bool, error) { + email := strings.TrimSpace(srv.ClusterIssuerEmail) + certOff := addonOff(srv.Disable, "cert-manager") + traefikOff := disabled(srv.Disable, "traefik") + skip := email != "" && (certOff || traefikOff) + if srv.DisableHelmController || certOff { + return nil, skip, nil + } + selfSigned, err := yaml.Marshal(selfSignedDoc()) + if err != nil { + return nil, false, err + } + docs := [][]byte{selfSigned} + if email != "" && !traefikOff { + letsEncrypt, err := yaml.Marshal(issuerDoc(email)) + if err != nil { + return nil, false, err + } + docs = append(docs, letsEncrypt) + } + return joinYAML(docs...), skip, nil +} + +type selfSignedIssuer struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata issuerMeta `yaml:"metadata"` + Spec selfSignedSpec `yaml:"spec"` +} + +type emptyObject struct{} + +type selfSignedSpec struct { + SelfSigned emptyObject `yaml:"selfSigned"` +} + +func selfSignedDoc() selfSignedIssuer { + return selfSignedIssuer{ + APIVersion: "cert-manager.io/v1", + Kind: "ClusterIssuer", + Metadata: issuerMeta{Name: "selfsigned"}, + } +} + +type issuerObject struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata issuerMeta `yaml:"metadata"` + Spec issuerSpecBody `yaml:"spec"` +} + +type issuerMeta struct { + Name string `yaml:"name"` +} + +type issuerSpecBody struct { + ACME issuerACME `yaml:"acme"` +} + +type issuerACME struct { + Server string `yaml:"server"` + Email string `yaml:"email"` + PrivateKeySecretRef issuerSecretRef `yaml:"privateKeySecretRef"` + Solvers []issuerHTTPSolver `yaml:"solvers"` +} + +type issuerSecretRef struct { + Name string `yaml:"name"` +} + +type issuerHTTPSolver struct { + HTTP01 issuerHTTP01 `yaml:"http01"` +} + +type issuerHTTP01 struct { + Ingress issuerIngress `yaml:"ingress"` +} + +type issuerIngress struct { + Class string `yaml:"class"` +} + +func issuerDoc(email string) issuerObject { + solver := issuerHTTPSolver{} + solver.HTTP01.Ingress.Class = "traefik" + return issuerObject{ + APIVersion: "cert-manager.io/v1", + Kind: "ClusterIssuer", + Metadata: issuerMeta{Name: "letsencrypt-prod"}, + Spec: issuerSpecBody{ACME: issuerACME{ + Server: "https://acme-v02.api.letsencrypt.org/directory", + Email: email, + PrivateKeySecretRef: issuerSecretRef{Name: "letsencrypt-prod-account-key"}, + Solvers: []issuerHTTPSolver{solver}, + }}, + } +} diff --git a/kube/internal/stage/local-path.yaml b/kube/internal/stage/local-path.yaml new file mode 100644 index 0000000..0545833 --- /dev/null +++ b/kube/internal/stage/local-path.yaml @@ -0,0 +1,128 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: kube-system +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: local-path-provisioner-service-account + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: local-path-provisioner +rules: + - apiGroups: [""] + resources: ["nodes", "persistentvolumeclaims", "configmaps", "pods/log"] + verbs: ["get", "list", "watch"] + - apiGroups: [""] + resources: ["endpoints", "persistentvolumes", "pods"] + verbs: ["*"] + - apiGroups: [""] + resources: ["events"] + verbs: ["create", "patch"] + - apiGroups: ["storage.k8s.io"] + resources: ["storageclasses"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: local-path-provisioner +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: local-path-provisioner +subjects: + - kind: ServiceAccount + name: local-path-provisioner-service-account + namespace: kube-system +--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: local-path-config + namespace: kube-system +data: + config.json: |- + {"nodePathMap":[{"node":"DEFAULT_PATH_FOR_NON_LISTED_NODES","paths":[__STORAGE_PATH_JSON__]}]} + setup: |- + #!/bin/sh + set -eu + mkdir -m 0777 -p "${VOL_DIR}" + chmod 700 "${VOL_DIR}/.." + teardown: |- + #!/bin/sh + set -eu + rm -rf "${VOL_DIR}" + helperPod.yaml: |- + apiVersion: v1 + kind: Pod + metadata: + name: helper-pod + spec: + containers: + - name: helper-pod + image: "__BUSYBOX_IMAGE__" + imagePullPolicy: IfNotPresent +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: local-path-provisioner + namespace: kube-system +spec: + replicas: 1 + revisionHistoryLimit: 0 + selector: + matchLabels: + app: local-path-provisioner + template: + metadata: + labels: + app: local-path-provisioner + spec: + serviceAccountName: local-path-provisioner-service-account + tolerations: + - key: CriticalAddonsOnly + operator: Exists + - key: node-role.kubernetes.io/control-plane + operator: Exists + effect: NoSchedule + nodeSelector: + kubernetes.io/os: linux + containers: + - name: local-path-provisioner + image: "__LOCAL_PATH_IMAGE__" + imagePullPolicy: IfNotPresent + command: + - local-path-provisioner + - start + - --config + - /etc/config/config.json + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: CONFIG_MOUNT_PATH + value: /etc/config/ + volumeMounts: + - name: config-volume + mountPath: /etc/config/ + volumes: + - name: config-volume + configMap: + name: local-path-config +--- +apiVersion: storage.k8s.io/v1 +kind: StorageClass +metadata: + name: local-path + annotations: + storageclass.kubernetes.io/is-default-class: "true" +provisioner: rancher.io/local-path +volumeBindingMode: WaitForFirstConsumer +reclaimPolicy: Delete diff --git a/kube/internal/stage/metrics-server.yaml b/kube/internal/stage/metrics-server.yaml new file mode 100644 index 0000000..0075cd9 --- /dev/null +++ b/kube/internal/stage/metrics-server.yaml @@ -0,0 +1,176 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: kube-system +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: metrics-server + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: system:metrics-server +rules: + - apiGroups: [""] + resources: ["nodes/metrics"] + verbs: ["get"] + - apiGroups: [""] + resources: ["pods", "nodes"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: system:metrics-server +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:metrics-server +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: system:aggregated-metrics-reader + labels: + rbac.authorization.k8s.io/aggregate-to-view: "true" + rbac.authorization.k8s.io/aggregate-to-edit: "true" + rbac.authorization.k8s.io/aggregate-to-admin: "true" +rules: + - apiGroups: ["metrics.k8s.io"] + resources: ["pods", "nodes"] + verbs: ["get", "list", "watch"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: metrics-server:system:auth-delegator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:auth-delegator +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: metrics-server-auth-reader + namespace: kube-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: extension-apiserver-authentication-reader +subjects: + - kind: ServiceAccount + name: metrics-server + namespace: kube-system +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: metrics-server + namespace: kube-system + labels: + k8s-app: metrics-server +spec: + replicas: 1 + revisionHistoryLimit: 0 + selector: + matchLabels: + k8s-app: metrics-server + template: + metadata: + labels: + k8s-app: metrics-server + spec: + serviceAccountName: metrics-server + tolerations: + - key: CriticalAddonsOnly + operator: Exists + - key: node-role.kubernetes.io/control-plane + operator: Exists + effect: NoSchedule + nodeSelector: + kubernetes.io/os: linux + volumes: + - name: tmp-dir + emptyDir: {} + containers: + - name: metrics-server + image: "__METRICS_SERVER_IMAGE__" + imagePullPolicy: IfNotPresent + args: + - --cert-dir=/tmp + - --secure-port=10250 + - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname + - --kubelet-use-node-status-port + - --metric-resolution=15s + ports: + - name: https + containerPort: 10250 + protocol: TCP + readinessProbe: + httpGet: + path: /readyz + port: https + scheme: HTTPS + periodSeconds: 10 + livenessProbe: + httpGet: + path: /livez + port: https + scheme: HTTPS + periodSeconds: 10 + securityContext: + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 1000 + allowPrivilegeEscalation: false + resources: + requests: + cpu: 100m + memory: 70Mi + volumeMounts: + - name: tmp-dir + mountPath: /tmp +--- +apiVersion: v1 +kind: Service +metadata: + name: metrics-server + namespace: kube-system + labels: + k8s-app: metrics-server + kubernetes.io/name: metrics-server +spec: + selector: + k8s-app: metrics-server + ports: + - name: https + port: 443 + protocol: TCP + targetPort: https +--- +apiVersion: apiregistration.k8s.io/v1 +kind: APIService +metadata: + name: v1beta1.metrics.k8s.io +spec: + group: metrics.k8s.io + version: v1beta1 + insecureSkipTLSVerify: true + groupPriorityMinimum: 100 + versionPriority: 100 + service: + name: metrics-server + namespace: kube-system + port: 443 diff --git a/kube/internal/stage/render.go b/kube/internal/stage/render.go new file mode 100644 index 0000000..ae7ceb6 --- /dev/null +++ b/kube/internal/stage/render.go @@ -0,0 +1,119 @@ +package stage + +import ( + "embed" + "encoding/json" + "fmt" + "net" + "runtime" + "strings" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" +) + +//go:embed coredns.yaml local-path.yaml metrics-server.yaml helmchart-crd.yaml +var files embed.FS + +type manifest struct { + name string + enabled bool + body []byte +} + +func addonManifests(srv config.Server) ([]manifest, error) { + dns := srv.ClusterDNS + if dns == "" { + dns = config.DefaultClusterDNS + } + if net.ParseIP(dns) == nil { + return nil, fmt.Errorf("cluster dns %q is not an IP", dns) + } + domain := srv.ClusterDomain + if domain == "" { + domain = config.DefaultClusterDomain + } + if strings.ContainsAny(domain, " \t\r\n\"'{}") { + return nil, fmt.Errorf("cluster domain %q cannot be used for cluster dns", domain) + } + storage := srv.DefaultLocalStoragePath + if storage == "" { + storage = config.DefaultLocalStoragePath + } + pathJSON, err := json.Marshal(storage) + if err != nil { + return nil, fmt.Errorf("local storage path: %w", err) + } + corednsImage, err := imageRef(srv.SystemDefaultRegistry, "coredns/coredns") + if err != nil { + return nil, err + } + localPathImage, err := imageRef(srv.SystemDefaultRegistry, "rancher/local-path-provisioner") + if err != nil { + return nil, err + } + busyboxImage, err := imageRef(srv.SystemDefaultRegistry, "library/busybox") + if err != nil { + return nil, err + } + metricsImage, err := imageRef(srv.SystemDefaultRegistry, "metrics-server/metrics-server") + if err != nil { + return nil, err + } + replacer := strings.NewReplacer( + "__CLUSTER_DNS__", dns, + "__CLUSTER_DOMAIN__", domain, + "__STORAGE_PATH_JSON__", string(pathJSON), + "__COREDNS_IMAGE__", corednsImage, + "__LOCAL_PATH_IMAGE__", localPathImage, + "__BUSYBOX_IMAGE__", busyboxImage, + "__METRICS_SERVER_IMAGE__", metricsImage, + ) + out := make([]manifest, 0, len(addonFiles)) + for _, file := range addonFiles { + body, err := files.ReadFile(file.name) + if err != nil { + return nil, fmt.Errorf("read addon %s: %w", file.addon, err) + } + rendered := []byte(replacer.Replace(string(body))) + if strings.Contains(string(rendered), "__") { + return nil, fmt.Errorf("addon %s has an unreplaced value", file.addon) + } + out = append(out, manifest{ + name: file.addon, + enabled: !addonOff(srv.Disable, file.addon), + body: rendered, + }) + } + return out, nil +} + +type addonFile struct { + addon string + name string +} + +var addonFiles = []addonFile{ + {addon: "coredns", name: "coredns.yaml"}, + {addon: "local-storage", name: "local-path.yaml"}, + {addon: "metrics-server", name: "metrics-server.yaml"}, +} + +// stageArch selects addons that are not published for one architecture. +// riscv64 does not stage metrics-server or cert-manager. +var stageArch = runtime.GOARCH + +func disabled(names []string, name string) bool { + for _, item := range names { + if item == name { + return true + } + } + return false +} + +func addonOff(names []string, name string) bool { + if disabled(names, name) { + return true + } + return stageArch == "riscv64" && (name == "metrics-server" || name == "cert-manager") +} diff --git a/kube/internal/stage/render_test.go b/kube/internal/stage/render_test.go new file mode 100644 index 0000000..2b5b372 --- /dev/null +++ b/kube/internal/stage/render_test.go @@ -0,0 +1,295 @@ +package stage + +import ( + "encoding/json" + "os" + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +func TestMain(m *testing.M) { + stageArch = "amd64" + os.Exit(m.Run()) +} + +func TestManifestsUseClusterNetworkAndPinnedImages(t *testing.T) { + srv := config.Defaults() + srv.ClusterDNS = "10.50.0.25" + srv.ClusterDomain = "example.test" + srv.DefaultLocalStoragePath = "/var/lib/edgelet-kube/volumes" + srv.SystemDefaultRegistry = "registry.example:5000" + docs, err := addonManifests(srv) + if err != nil { + t.Fatal(err) + } + if len(docs) != 3 { + t.Fatalf("addons %d", len(docs)) + } + body := map[string]string{} + for _, doc := range docs { + if !doc.enabled { + t.Fatalf("%s disabled", doc.name) + } + text := string(doc.body) + if strings.Contains(text, "__") { + t.Fatalf("%s has an unreplaced value", doc.name) + } + for _, absent := range []string{"traefik", "cert-manager", "klipper", "datasance", "taints:"} { + if strings.Contains(strings.ToLower(text), absent) { + t.Fatalf("%s contains %s", doc.name, absent) + } + } + body[doc.name] = text + } + for _, repo := range []string{"coredns/coredns", "rancher/local-path-provisioner", "library/busybox", "metrics-server/metrics-server"} { + ref, err := imageRef(srv.SystemDefaultRegistry, repo) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(body["coredns"]+body["local-storage"]+body["metrics-server"], ref) { + t.Fatalf("missing pinned image %s", ref) + } + if !strings.HasPrefix(ref, "registry.example:5000/") { + t.Fatalf("image %s", ref) + } + } + objs, err := decode([]byte(body["coredns"])) + if err != nil { + t.Fatal(err) + } + corefile := nestedString(t, find(t, objs, "ConfigMap", "coredns"), "data", "Corefile") + if !strings.Contains(corefile, "example.test") { + t.Fatalf("corefile %s", corefile) + } + clusterIP := nestedString(t, find(t, objs, "Service", "kube-dns"), "spec", "clusterIP") + if clusterIP != "10.50.0.25" { + t.Fatalf("cluster dns %s", clusterIP) + } + local, err := decode([]byte(body["local-storage"])) + if err != nil { + t.Fatal(err) + } + account := find(t, local, "ServiceAccount", "local-path-provisioner-service-account") + if account.GetNamespace() != "kube-system" { + t.Fatalf("service account %#v", account.Object) + } + deploy := find(t, local, "Deployment", "local-path-provisioner") + if nestedString(t, deploy, "spec", "template", "spec", "serviceAccountName") != account.GetName() { + t.Fatalf("provisioner account %#v", deploy.Object) + } + class := find(t, local, "StorageClass", "local-path") + if nestedString(t, class, "metadata", "annotations", "storageclass.kubernetes.io/is-default-class") != "true" { + t.Fatalf("storage class %#v", class.Object) + } + if nestedString(t, class, "provisioner") != "rancher.io/local-path" { + t.Fatalf("provisioner %#v", class.Object) + } + raw := nestedString(t, find(t, local, "ConfigMap", "local-path-config"), "data", "config.json") + var cfg storageConfig + if err := json.Unmarshal([]byte(raw), &cfg); err != nil { + t.Fatal(err) + } + if len(cfg.NodePathMap) != 1 || len(cfg.NodePathMap[0].Paths) != 1 || cfg.NodePathMap[0].Paths[0] != srv.DefaultLocalStoragePath { + t.Fatalf("storage path %#v", cfg) + } + metrics, err := decode([]byte(body["metrics-server"])) + if err != nil { + t.Fatal(err) + } + api := find(t, metrics, "APIService", "v1beta1.metrics.k8s.io") + if nestedString(t, api, "spec", "group") != "metrics.k8s.io" || nestedString(t, api, "spec", "version") != "v1beta1" { + t.Fatalf("metrics api %#v", api.Object) + } +} + +func TestRISCVSkipsMetricsAndCertManager(t *testing.T) { + prev := stageArch + stageArch = "riscv64" + t.Cleanup(func() { stageArch = prev }) + + srv := config.Defaults() + docs, err := addonManifests(srv) + if err != nil { + t.Fatal(err) + } + for _, doc := range docs { + on := doc.name != "metrics-server" + if doc.enabled != on { + t.Fatalf("%s enabled %v", doc.name, doc.enabled) + } + } + charts, err := helmChartManifests(srv) + if err != nil { + t.Fatal(err) + } + for _, doc := range charts { + on := doc.name != "cert-manager" + if doc.enabled != on { + t.Fatalf("%s enabled %v", doc.name, doc.enabled) + } + } + body, skip, err := clusterIssuer(srv) + if err != nil { + t.Fatal(err) + } + if skip || len(strings.TrimSpace(string(body))) != 0 { + t.Fatalf("issuer %q skip %v", body, skip) + } + srv.ClusterIssuerEmail = "ops@example.com" + body, skip, err = clusterIssuer(srv) + if err != nil { + t.Fatal(err) + } + if !skip || len(strings.TrimSpace(string(body))) != 0 { + t.Fatalf("issuer %q skip %v", body, skip) + } +} + +func TestDisableDropsOnlyThatAddon(t *testing.T) { + base := config.Defaults() + base.DisableHelmController = true + base.Disable = []string{"traefik", "cert-manager", "servicelb"} + kept, err := addonManifests(base) + if err != nil { + t.Fatal(err) + } + for _, doc := range kept { + if !doc.enabled { + t.Fatalf("%s disabled by an unrelated flag", doc.name) + } + } + for _, name := range []string{"coredns", "local-storage", "metrics-server"} { + srv := base + srv.Disable = []string{name} + docs, err := addonManifests(srv) + if err != nil { + t.Fatal(err) + } + for _, doc := range docs { + if doc.name == name && doc.enabled { + t.Fatalf("%s stayed enabled", name) + } + if doc.name != name && !doc.enabled { + t.Fatalf("disabling %s dropped %s", name, doc.name) + } + if len(doc.body) == 0 { + t.Fatalf("%s has an empty manifest", doc.name) + } + } + } +} + +func TestHelmChartCRDPrecedesChartObjects(t *testing.T) { + srv := config.Defaults() + crd, err := HelmChartCRD(srv) + if err != nil { + t.Fatal(err) + } + manifests, err := addonManifests(srv) + if err != nil { + t.Fatal(err) + } + extra := []byte("apiVersion: helm.cattle.io/v1\nkind: HelmChart\nmetadata:\n name: sample\n namespace: kube-system\nspec:\n chart: https://kubernetes.default/static/charts/sample.tgz\n") + var sawCRD bool + var sawChart bool + charts, err := helmChartManifests(srv) + if err != nil { + t.Fatal(err) + } + for _, body := range enabledBodies(manifests, crd, charts, extra) { + objs, err := decode(body) + if err != nil { + t.Fatal(err) + } + for _, obj := range objs { + switch { + case obj.GetKind() == "HelmChart": + if !sawCRD { + t.Fatal("HelmChart was applied before its CRD") + } + sawChart = true + case obj.GetKind() == "CustomResourceDefinition" && obj.GetName() == "helmcharts.helm.cattle.io": + if sawChart { + t.Fatal("HelmChart CRD followed a HelmChart") + } + if obj.GetAPIVersion() != "apiextensions.k8s.io/v1" { + t.Fatalf("crd version %s", obj.GetAPIVersion()) + } + sawCRD = true + } + } + } + if !sawCRD || !sawChart { + t.Fatalf("crd %v chart %v", sawCRD, sawChart) + } + disabled := srv + disabled.DisableHelmController = true + crd, err = HelmChartCRD(disabled) + if err != nil { + t.Fatal(err) + } + if len(crd) != 0 { + t.Fatal("helm chart API was embedded while the controller is disabled") + } + charts, err = helmChartManifests(disabled) + if err != nil { + t.Fatal(err) + } + if len(charts) != 0 { + t.Fatal("disabled controller still stages charts") + } + for _, body := range enabledBodies(manifests, crd, charts, nil) { + if strings.Contains(string(body), "helm.cattle.io") { + t.Fatal("disabled controller still stages the helm chart API") + } + } +} + +func TestIPv6ClusterDNS(t *testing.T) { + srv := config.Defaults() + srv.ClusterDNS = "2001:db8::10" + docs, err := addonManifests(srv) + if err != nil { + t.Fatal(err) + } + var coredns string + for _, doc := range docs { + if doc.name == "coredns" { + coredns = string(doc.body) + } + } + if !strings.Contains(coredns, "2001:db8::10") { + t.Fatal("cluster dns was not rendered") + } +} + +type storagePath struct { + Paths []string `json:"paths"` +} + +type storageConfig struct { + NodePathMap []storagePath `json:"nodePathMap"` +} + +func find(t *testing.T, objs []*unstructured.Unstructured, kind, name string) *unstructured.Unstructured { + t.Helper() + for _, obj := range objs { + if obj.GetKind() == kind && obj.GetName() == name { + return obj + } + } + t.Fatalf("missing %s %s", kind, name) + return nil +} + +func nestedString(t *testing.T, obj *unstructured.Unstructured, fields ...string) string { + t.Helper() + value, found, err := unstructured.NestedString(obj.Object, fields...) + if err != nil || !found { + t.Fatalf("%s %v: %v", obj.GetName(), fields, err) + } + return value +} diff --git a/kube/internal/stage/runtimes.go b/kube/internal/stage/runtimes.go new file mode 100644 index 0000000..ec7fe28 --- /dev/null +++ b/kube/internal/stage/runtimes.go @@ -0,0 +1,124 @@ +package stage + +import ( + "fmt" + "slices" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "github.com/eclipse-iofog/edgelet-kube/internal/containerd" + "go.yaml.in/yaml/v3" +) + +const runtimeAddon = "runtimes" + +type runtimeClassDoc struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata runtimeClassMeta `yaml:"metadata"` + Handler string `yaml:"handler"` +} + +type runtimeClassMeta struct { + Name string `yaml:"name"` +} + +// runtimeManifests stages one RuntimeClass for each CRI handler this node +// registers. crun is always registered. A catalog handler is registered only +// when its binary is on PATH. Handlers that are not registered are deleted +// so a pod cannot name a runtime this node does not have. Disabling the +// addon deletes every class in the catalog, including crun. Pods that omit +// runtimeClassName keep using the default handler. +func runtimeManifests(srv config.Server) ([]manifest, error) { + return runtimeClassManifests(!disabled(srv.Disable, runtimeAddon), containerd.RegisteredRuntimeHandlers(), containerd.KnownRuntimeHandlers()) +} + +func runtimeClassManifests(enabled bool, registered, known []string) ([]manifest, error) { + reg := handlerSet(registered) + all := handlerSet(known) + for name := range reg { + all[name] = struct{}{} + } + var applyNames, removeNames []string + if enabled { + applyNames = sortedKeys(reg) + for _, name := range sortedKeys(all) { + if _, ok := reg[name]; !ok { + removeNames = append(removeNames, name) + } + } + } else { + removeNames = sortedKeys(all) + } + var out []manifest + if len(applyNames) > 0 { + body, err := runtimeClassYAML(applyNames) + if err != nil { + return nil, err + } + out = append(out, manifest{name: runtimeAddon, enabled: true, body: body}) + } + if len(removeNames) > 0 { + body, err := runtimeClassYAML(removeNames) + if err != nil { + return nil, err + } + out = append(out, manifest{name: runtimeAddon, enabled: false, body: body}) + } + return out, nil +} + +func runtimeClassYAML(handlers []string) ([]byte, error) { + docs := make([][]byte, 0, len(handlers)) + for _, name := range handlers { + if !validRuntimeHandler(name) { + return nil, fmt.Errorf("runtime handler %q is not a RuntimeClass name", name) + } + body, err := yaml.Marshal(runtimeClassDoc{ + APIVersion: "node.k8s.io/v1", + Kind: "RuntimeClass", + Metadata: runtimeClassMeta{Name: name}, + Handler: name, + }) + if err != nil { + return nil, fmt.Errorf("runtime class %s: %w", name, err) + } + docs = append(docs, body) + } + return joinYAML(docs...), nil +} + +func validRuntimeHandler(name string) bool { + if name == "" || len(name) > 63 { + return false + } + for i := 0; i < len(name); i++ { + c := name[i] + switch { + case c >= 'a' && c <= 'z', c >= '0' && c <= '9': + case c == '-' && i > 0 && i < len(name)-1: + default: + return false + } + } + return true +} + +func handlerSet(names []string) map[string]struct{} { + out := make(map[string]struct{}, len(names)) + for _, name := range names { + if name == "" { + continue + } + out[name] = struct{}{} + } + return out +} + +func sortedKeys(handlers map[string]struct{}) []string { + out := make([]string, 0, len(handlers)) + for name := range handlers { + out = append(out, name) + } + slices.Sort(out) + return out +} diff --git a/kube/internal/stage/runtimes_test.go b/kube/internal/stage/runtimes_test.go new file mode 100644 index 0000000..a95dabd --- /dev/null +++ b/kube/internal/stage/runtimes_test.go @@ -0,0 +1,106 @@ +package stage + +import ( + "strings" + "testing" + + "github.com/eclipse-iofog/edgelet-kube/internal/config" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +func TestRuntimeClassesFollowRegisteredHandlers(t *testing.T) { + registered := []string{"crun", "nvidia", "edgelet-wasmtime", "nvidia-cdi"} + known := []string{"crun", "nvidia", "edgelet-wasmtime", "nvidia-cdi", "wasmer", "runc", "spin"} + docs, err := runtimeClassManifests(true, registered, known) + if err != nil { + t.Fatal(err) + } + if len(docs) != 2 { + t.Fatalf("manifests %d", len(docs)) + } + var applied, removed string + for _, doc := range docs { + if doc.name != runtimeAddon { + t.Fatalf("addon %s", doc.name) + } + if doc.enabled { + applied = string(doc.body) + continue + } + removed = string(doc.body) + } + objs, err := decode([]byte(applied)) + if err != nil { + t.Fatal(err) + } + if len(objs) != len(registered) { + t.Fatalf("applied %#v", objs) + } + for _, name := range registered { + obj := find(t, objs, "RuntimeClass", name) + if obj.GetAPIVersion() != "node.k8s.io/v1" { + t.Fatalf("%s version %s", name, obj.GetAPIVersion()) + } + if nestedString(t, obj, "handler") != name { + t.Fatalf("%s handler %#v", name, obj.Object) + } + if _, found, err := unstructured.NestedFieldNoCopy(obj.Object, "scheduling"); err != nil || found { + t.Fatalf("%s sets scheduling", name) + } + } + for _, absent := range []string{"wasmer", "runc", "spin"} { + if strings.Contains(applied, "name: "+absent) { + t.Fatalf("applied missing handler %s", absent) + } + if !strings.Contains(removed, "name: "+absent) { + t.Fatalf("removed body missing %s", absent) + } + } +} + +func TestDisableRuntimesDeletesEveryClass(t *testing.T) { + docs, err := runtimeClassManifests(false, []string{"crun", "nvidia"}, []string{"crun", "nvidia", "wasmer"}) + if err != nil { + t.Fatal(err) + } + if len(docs) != 1 || docs[0].enabled { + t.Fatalf("manifests %#v", docs) + } + objs, err := decode(docs[0].body) + if err != nil { + t.Fatal(err) + } + got := map[string]bool{} + for _, obj := range objs { + got[obj.GetName()] = true + } + for _, name := range []string{"crun", "nvidia", "wasmer"} { + if !got[name] { + t.Fatalf("missing %s in %#v", name, got) + } + } +} + +func TestOtherDisableLeavesRuntimeClasses(t *testing.T) { + srv := config.Defaults() + srv.Disable = []string{"traefik", "coredns"} + docs, err := runtimeManifests(srv) + if err != nil { + t.Fatal(err) + } + var enabled bool + for _, doc := range docs { + if doc.enabled { + enabled = true + } + } + if !enabled { + t.Fatal("an unrelated disable dropped the runtime classes") + } +} + +func TestRuntimeClassRejectsBadHandler(t *testing.T) { + if _, err := runtimeClassManifests(true, []string{"NVIDIA"}, []string{"NVIDIA"}); err == nil { + t.Fatal("expected an invalid handler to fail") + } +} diff --git a/kube/internal/version/version.go b/kube/internal/version/version.go new file mode 100644 index 0000000..a4d582b --- /dev/null +++ b/kube/internal/version/version.go @@ -0,0 +1,65 @@ +// Package version sets the Kubernetes version reported by this binary. +package version + +import ( + "strings" + "sync/atomic" + _ "unsafe" // go:linkname + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + _ "k8s.io/client-go/pkg/version" // go:linkname client gitVersion + baseversion "k8s.io/component-base/version" +) + +//go:linkname dynamicGitVersion k8s.io/component-base/version.dynamicGitVersion +var dynamicGitVersion atomic.Value + +//go:linkname gitVersion k8s.io/component-base/version.gitVersion +var gitVersion string + +//go:linkname gitMajor k8s.io/component-base/version.gitMajor +var gitMajor string + +//go:linkname gitMinor k8s.io/component-base/version.gitMinor +var gitMinor string + +//go:linkname clientGitVersion k8s.io/client-go/pkg/version.gitVersion +var clientGitVersion string + +//go:linkname clientGitMajor k8s.io/client-go/pkg/version.gitMajor +var clientGitMajor string + +//go:linkname clientGitMinor k8s.io/client-go/pkg/version.gitMinor +var clientGitMinor string + +func init() { + Pin() +} + +// Pin sets component-base gitVersion from the pinned Kubernetes patch. +func Pin() { + pinned := airgap.KubernetesVersion() + if pinned == "" { + panic("kubernetes version is not set") + } + major, minor := majorMinor(pinned) + dynamicGitVersion.Store(pinned) + gitVersion = pinned + gitMajor = major + gitMinor = minor + clientGitVersion = pinned + clientGitMajor = major + clientGitMinor = minor +} + +// GitVersion is the Kubernetes patch reported by component-base. +func GitVersion() string { + return baseversion.Get().GitVersion +} + +func majorMinor(pinned string) (string, string) { + rest := strings.TrimPrefix(pinned, "v") + major, rest, _ := strings.Cut(rest, ".") + minor, _, _ := strings.Cut(rest, ".") + return major, minor +} diff --git a/kube/internal/version/version_test.go b/kube/internal/version/version_test.go new file mode 100644 index 0000000..4c2271f --- /dev/null +++ b/kube/internal/version/version_test.go @@ -0,0 +1,28 @@ +package version + +import ( + "testing" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" + clientversion "k8s.io/client-go/pkg/version" + baseversion "k8s.io/component-base/version" +) + +func TestGitVersionMatchesPin(t *testing.T) { + want := airgap.KubernetesVersion() + if got := GitVersion(); got != want { + t.Fatalf("component-base gitVersion %s, pin %s", got, want) + } + if got := baseversion.Get().GitVersion; got != want { + t.Fatalf("Get().GitVersion %s", got) + } + if got := baseversion.Get().Major; got != "1" { + t.Fatalf("major %s", got) + } + if got := baseversion.Get().Minor; got != "36" { + t.Fatalf("minor %s", got) + } + if got := clientversion.Get().GitVersion; got != want { + t.Fatalf("client gitVersion %s", got) + } +} diff --git a/kube/link.go b/kube/link.go new file mode 100644 index 0000000..0315da2 --- /dev/null +++ b/kube/link.go @@ -0,0 +1,19 @@ +package edgeletkube + +import ( + "github.com/eclipse-iofog/edgelet/pkg/data" + "github.com/eclipse-iofog/edgelet/pkg/datadir" + "github.com/eclipse-iofog/edgelet/pkg/flock" +) + +// Bundle extract, the data directory, and the file lock come from the root module. +var ( + resolveDataDir = datadir.Resolve + bundleNames = data.AssetNames + acquireLock = flock.Acquire +) + +// Linked reports that those packages are part of this module. +func Linked() bool { + return resolveDataDir != nil && bundleNames != nil && acquireLock != nil +} diff --git a/kube/packaging/systemd/edgelet-kube.service b/kube/packaging/systemd/edgelet-kube.service new file mode 100644 index 0000000..18a3ced --- /dev/null +++ b/kube/packaging/systemd/edgelet-kube.service @@ -0,0 +1,33 @@ +[Unit] +Description=Edgelet Kubernetes +Documentation=https://github.com/eclipse-iofog/edgelet +Wants=network-online.target +After=network-online.target +StartLimitIntervalSec=0 + +[Service] +Type=simple +# A restart signals the server process. The server stops its containerd child. +# Shims and pods keep running. The new process reuses containerd state, +# SQLite, and the TLS directory. +KillMode=process +Delegate=yes +User=root +LimitNOFILE=1048576 +LimitNPROC=infinity +LimitCORE=infinity +TasksMax=infinity +TimeoutStartSec=0 +Restart=always +RestartSec=5s +# Loads br_netfilter and sets net.ipv4.ip_forward=1 and +# net.bridge.bridge-nf-call-iptables=1 when protect-kernel-defaults is false. +# When that setting is true, the program does not change sysctls. +ExecStartPre=/usr/libexec/edgelet-kube/prepare-kernel +ExecStart=/usr/local/bin/edgelet-kube server +StandardOutput=journal +StandardError=journal +SyslogIdentifier=edgelet-kube + +[Install] +WantedBy=multi-user.target diff --git a/kube/packaging/systemd/prepare-kernel.sh b/kube/packaging/systemd/prepare-kernel.sh new file mode 100755 index 0000000..7a2040b --- /dev/null +++ b/kube/packaging/systemd/prepare-kernel.sh @@ -0,0 +1,72 @@ +#!/bin/sh +# Load br_netfilter and set forwarding sysctls unless protect-kernel-defaults is true. +# A missing config file uses the default, which is false, and is not created. +set -eu + +config=/etc/edgelet-kube/config.yaml +if [ -n "${EDGELET_KUBE_CONFIG_FILE:-}" ]; then + config=$EDGELET_KUBE_CONFIG_FILE +fi + +read_protect_value() { + awk ' + /^[ \t]*#/ { next } + /^protect-kernel-defaults:[ \t]*/ { + line = $0 + sub(/\r$/, "", line) + sub(/^protect-kernel-defaults:[ \t]*/, "", line) + sub(/[ \t]+#.*/, "", line) + gsub(/^[ \t]+|[ \t]+$/, "", line) + found = line + } + END { if (found != "") print found } + ' "$1" +} + +value= +if [ -f "$config" ]; then + got=$(read_protect_value "$config") + if [ -n "$got" ]; then + value=$got + fi +fi + +if [ -d "$config.d" ]; then + LC_ALL=C + export LC_ALL + for file in "$config.d"/*.yaml; do + if [ -f "$file" ]; then + got=$(read_protect_value "$file") + if [ -n "$got" ]; then + value=$got + fi + fi + done +fi + +protected=0 +token=$(printf '%s' "$value" | tr -d '\r' | tr '[:upper:]' '[:lower:]') +case $token in + true) protected=1 ;; +esac + +# The environment replaces the file, and only the exact value true protects. +if [ -n "${EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS:-}" ]; then + protected=0 + if [ "$EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS" = "true" ]; then + protected=1 + fi +fi + +if [ "$protected" -eq 1 ]; then + exit 0 +fi + +if ! command -v modprobe >/dev/null 2>&1 || ! command -v sysctl >/dev/null 2>&1; then + PATH="/sbin:/usr/sbin:${PATH:-/usr/bin:/bin}" + export PATH +fi + +modprobe br_netfilter +sysctl -w net.ipv4.ip_forward=1 +sysctl -w net.bridge.bridge-nf-call-iptables=1 diff --git a/kube/scripts/airgap/archive.go b/kube/scripts/airgap/archive.go new file mode 100644 index 0000000..419c401 --- /dev/null +++ b/kube/scripts/airgap/archive.go @@ -0,0 +1,339 @@ +package airgap + +import ( + "archive/tar" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/klauspost/compress/zstd" +) + +const ( + // AssetAMD64 is the airgap archive published beside the amd64 binary. + AssetAMD64 = "edgelet-kube-airgap-images-amd64.tar.zst" + + // imageNameAnnotation is the image name recorded on an exported OCI index. + imageNameAnnotation = "io.containerd.image.name" + + mediaTypeIndex = "application/vnd.oci.image.index.v1+json" + mediaTypeManifest = "application/vnd.oci.image.manifest.v1+json" + layoutVersion = "1.0.0" + jsonLimit = 20 << 20 +) + +// WriteTar writes an OCI image archive whose index lists refs, in order. +// A containerd export records the same names on its index. +func WriteTar(w io.Writer, refs []string) error { + if len(refs) == 0 { + return errors.New("archive has no images") + } + index, err := indexBytes(refs) + if err != nil { + return err + } + layout, err := json.Marshal(map[string]string{"imageLayoutVersion": layoutVersion}) + if err != nil { + return fmt.Errorf("encode layout: %w", err) + } + tw := tar.NewWriter(w) + mod := time.Unix(0, 0) + if err := writeMember(tw, "oci-layout", layout, mod); err != nil { + return err + } + if err := writeMember(tw, "index.json", index, mod); err != nil { + return err + } + if err := tw.Close(); err != nil { + return fmt.Errorf("close archive: %w", err) + } + return nil +} + +// Compress writes src to dst as a zstd archive. +// dst is replaced only after the frame is complete. +func Compress(dst string, src io.Reader) error { + dir := filepath.Dir(dst) + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create archive directory: %w", err) + } + tmp, err := os.CreateTemp(dir, ".airgap-*.partial") + if err != nil { + return fmt.Errorf("create archive: %w", err) + } + tmpName := tmp.Name() + success := false + defer func() { + if !success { + _ = os.Remove(tmpName) + } + }() + zw, err := zstd.NewWriter(tmp, + zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(16)), + zstd.WithWindowSize(1<<25), + ) + if err != nil { + _ = tmp.Close() + return fmt.Errorf("zstd writer: %w", err) + } + _, copyErr := io.Copy(zw, src) + closeErr := zw.Close() + fileErr := tmp.Close() + if copyErr != nil { + return fmt.Errorf("compress archive: %w", copyErr) + } + if closeErr != nil { + return fmt.Errorf("compress archive: %w", closeErr) + } + if fileErr != nil { + return fmt.Errorf("compress archive: %w", fileErr) + } + if err := os.Chmod(tmpName, 0o644); err != nil { + return fmt.Errorf("chmod archive: %w", err) + } + if err := os.Rename(tmpName, dst); err != nil { + return fmt.Errorf("write archive: %w", err) + } + success = true + return nil +} + +// ListFile returns the image names stored in an OCI or Docker archive. +// The archive may be a tar, gzip tar, or zstd tar. Names come from the +// OCI index when it records them, so a digested pin-list reference is kept. +func ListFile(file string) ([]string, error) { + reader, err := openArchive(file) + if err != nil { + return nil, err + } + defer func() { + _ = reader.Close() + }() + names, err := List(reader) + if err != nil { + return nil, fmt.Errorf("list %s: %w", file, err) + } + return names, nil +} + +// List reads image names from an uncompressed OCI or Docker tar. +func List(r io.Reader) ([]string, error) { + tr := tar.NewReader(r) + var indexNames []string + var repoTags []string + sawIndex := false + for { + hdr, err := tr.Next() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, fmt.Errorf("read archive: %w", err) + } + if hdr.Typeflag != tar.TypeReg && hdr.Typeflag != tar.TypeRegA { + continue + } + switch path.Clean(hdr.Name) { + case "index.json": + sawIndex = true + indexNames, err = namesFromIndex(tr) + case "manifest.json": + repoTags, err = namesFromDocker(tr) + default: + _, err = io.Copy(io.Discard, tr) + } + if err != nil { + return nil, err + } + } + if sawIndex && len(indexNames) > 0 { + return indexNames, nil + } + if len(repoTags) > 0 { + return repoTags, nil + } + return nil, errors.New("archive contains no images") +} + +func indexBytes(refs []string) ([]byte, error) { + manifests := make([]map[string]any, 0, len(refs)) + for _, ref := range refs { + ref = strings.TrimSpace(ref) + if ref == "" { + return nil, errors.New("archive image name is empty") + } + sum := sha256.Sum256([]byte(ref)) + manifests = append(manifests, map[string]any{ + "mediaType": mediaTypeManifest, + "digest": "sha256:" + hex.EncodeToString(sum[:]), + "size": 0, + "annotations": map[string]string{ + imageNameAnnotation: ref, + }, + }) + } + body, err := json.Marshal(map[string]any{ + "schemaVersion": 2, + "mediaType": mediaTypeIndex, + "manifests": manifests, + }) + if err != nil { + return nil, fmt.Errorf("encode index: %w", err) + } + return body, nil +} + +func writeMember(tw *tar.Writer, name string, body []byte, mod time.Time) error { + hdr := &tar.Header{ + Name: name, + Mode: 0o644, + Size: int64(len(body)), + ModTime: mod, + Typeflag: tar.TypeReg, + } + if err := tw.WriteHeader(hdr); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + if _, err := tw.Write(body); err != nil { + return fmt.Errorf("write %s: %w", name, err) + } + return nil +} + +type indexManifest struct { + Annotations map[string]string `json:"annotations"` +} + +func namesFromIndex(r io.Reader) ([]string, error) { + var index struct { + Manifests []indexManifest `json:"manifests"` + } + if err := decodeJSON(r, &index); err != nil { + return nil, fmt.Errorf("read index: %w", err) + } + var names []string + seen := map[string]struct{}{} + for _, manifest := range index.Manifests { + name := strings.TrimSpace(manifest.Annotations[imageNameAnnotation]) + if name == "" { + continue + } + if _, ok := seen[name]; ok { + continue + } + seen[name] = struct{}{} + names = append(names, name) + } + return names, nil +} + +func namesFromDocker(r io.Reader) ([]string, error) { + var manifests []struct { + RepoTags []string `json:"RepoTags"` + } + if err := decodeJSON(r, &manifests); err != nil { + return nil, fmt.Errorf("read manifest: %w", err) + } + var names []string + seen := map[string]struct{}{} + for _, manifest := range manifests { + for _, name := range manifest.RepoTags { + name = strings.TrimSpace(name) + if name == "" { + continue + } + if _, ok := seen[name]; ok { + continue + } + seen[name] = struct{}{} + names = append(names, name) + } + } + return names, nil +} + +func decodeJSON(r io.Reader, dest any) error { + body, err := io.ReadAll(io.LimitReader(r, jsonLimit+1)) + if err != nil { + return err + } + if len(body) > jsonLimit { + _, _ = io.Copy(io.Discard, r) + return fmt.Errorf("json exceeds %d bytes", jsonLimit) + } + if len(body) == 0 { + return errors.New("json is empty") + } + return json.Unmarshal(body, dest) +} + +func openArchive(file string) (io.ReadCloser, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + var magic [4]byte + n, err := io.ReadFull(f, magic[:]) + if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { + _ = f.Close() + return nil, err + } + if _, err := f.Seek(0, io.SeekStart); err != nil { + _ = f.Close() + return nil, err + } + switch { + case n >= 4 && magic[0] == 0x28 && magic[1] == 0xB5 && magic[2] == 0x2F && magic[3] == 0xFD: + dec, err := zstd.NewReader(f) + if err != nil { + _ = f.Close() + return nil, fmt.Errorf("open %s: %w", file, err) + } + return &zstdReadCloser{dec: dec, file: f}, nil + case n >= 2 && magic[0] == 0x1f && magic[1] == 0x8b: + dec, err := gzip.NewReader(f) + if err != nil { + _ = f.Close() + return nil, fmt.Errorf("open %s: %w", file, err) + } + return &gzipReadCloser{Reader: dec, file: f}, nil + default: + return f, nil + } +} + +type zstdReadCloser struct { + dec *zstd.Decoder + file *os.File +} + +func (z *zstdReadCloser) Read(p []byte) (int, error) { + return z.dec.Read(p) +} + +func (z *zstdReadCloser) Close() error { + z.dec.Close() + return z.file.Close() +} + +type gzipReadCloser struct { + *gzip.Reader + file *os.File +} + +func (g *gzipReadCloser) Close() error { + err := g.Reader.Close() + if closeErr := g.file.Close(); err == nil { + err = closeErr + } + return err +} diff --git a/kube/scripts/airgap/archive_test.go b/kube/scripts/airgap/archive_test.go new file mode 100644 index 0000000..d37afd1 --- /dev/null +++ b/kube/scripts/airgap/archive_test.go @@ -0,0 +1,94 @@ +package airgap + +import ( + "archive/tar" + "bytes" + "slices" + "testing" + "time" +) + +func TestListMatchesPinList(t *testing.T) { + var raw bytes.Buffer + if err := WriteTar(&raw, Images()); err != nil { + t.Fatal(err) + } + plain, err := List(bytes.NewReader(raw.Bytes())) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(plain, Images()) { + t.Fatalf("tar %v", plain) + } + + path := t.TempDir() + "/" + AssetAMD64 + if err := Compress(path, bytes.NewReader(raw.Bytes())); err != nil { + t.Fatal(err) + } + got, err := ListFile(path) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(got, Images()) || len(got) != 12 { + t.Fatalf("archive %v", got) + } +} + +func TestListKeepsIndexNames(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + mod := time.Unix(0, 0) + index := []byte(`{"schemaVersion":2,"manifests":[{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","size":1,"annotations":{"io.containerd.image.name":"docker.io/portainer/pause:latest@sha256:df6d2fb5cff97c4070a12953a34a56422879f1e02b43400f1caf1cbd530458b1","org.opencontainers.image.ref.name":"latest"}}]}`) + manifest := []byte(`[{"Config":"blobs/sha256/abc","RepoTags":["pause:old"],"Layers":[]}]`) + for _, member := range []struct { + name string + body []byte + }{ + {"oci-layout", []byte(`{"imageLayoutVersion":"1.0.0"}`)}, + {"index.json", index}, + {"manifest.json", manifest}, + } { + hdr := &tar.Header{Name: member.name, Mode: 0o644, Size: int64(len(member.body)), ModTime: mod, Typeflag: tar.TypeReg} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(member.body); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + got, err := List(&buf) + if err != nil { + t.Fatal(err) + } + want := []string{"docker.io/portainer/pause:latest@sha256:df6d2fb5cff97c4070a12953a34a56422879f1e02b43400f1caf1cbd530458b1"} + if !slices.Equal(got, want) { + t.Fatalf("names %v", got) + } +} + +func TestListReadsDockerRepoTags(t *testing.T) { + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + body := []byte(`[{"Config":"blobs/sha256/abc","RepoTags":["example.com/one:1","example.com/two:2"],"Layers":[]}]`) + hdr := &tar.Header{Name: "manifest.json", Mode: 0o644, Size: int64(len(body)), ModTime: time.Unix(0, 0), Typeflag: tar.TypeReg} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(body); err != nil { + t.Fatal(err) + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + got, err := List(&buf) + if err != nil { + t.Fatal(err) + } + want := []string{"example.com/one:1", "example.com/two:2"} + if !slices.Equal(got, want) { + t.Fatalf("names %v", got) + } +} diff --git a/kube/scripts/airgap/image-list.txt b/kube/scripts/airgap/image-list.txt new file mode 100644 index 0000000..86064b4 --- /dev/null +++ b/kube/scripts/airgap/image-list.txt @@ -0,0 +1,12 @@ +docker.io/portainer/pause:latest@sha256:df6d2fb5cff97c4070a12953a34a56422879f1e02b43400f1caf1cbd530458b1 +registry.k8s.io/coredns/coredns:v1.15.0@sha256:0a9d8c8ddf34347eb59aad9a8784f0710de88d6d112726d11d271f9bc6daca26 +docker.io/rancher/local-path-provisioner:v0.0.37@sha256:e757967a5ec338f6a9b371c5a9688bedaa8c3578ea3dd4db329ea0084be0a86f +docker.io/library/busybox:1.37.0@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec +registry.k8s.io/metrics-server/metrics-server:v0.9.1@sha256:9b0ba1926e1d3089673f45461c3c1416109dea33b3ba3434048defd380df329b +docker.io/library/traefik:v3.7.17@sha256:f4bb143d1135a579b630ed491e17ec50f6f7c9c6a30585ff3d385471d2a86f5a +docker.io/rancher/klipper-helm:v0.14.0-build20261106@sha256:e2289066485f0bd74730401d3fbd91f6918c5e5bd100943aa743b6f39dfc3019 +quay.io/jetstack/cert-manager-controller:v1.21.3@sha256:9f4f96a33c7774cef24466fcd85031997531a03a8d117f151126baa8d1290dcc +quay.io/jetstack/cert-manager-webhook:v1.21.3@sha256:055ac8e9de6a0ba6763794838fe38944acc650f68ebe1b01dd8be079e580f458 +quay.io/jetstack/cert-manager-cainjector:v1.21.3@sha256:083d0e906f8eb44e255fe4ff817ae54e49f9ed82e22f1011bb4e9e4f4b8a641f +quay.io/jetstack/cert-manager-startupapicheck:v1.21.3@sha256:1c519d4afca1413d1e4ccd78bdc756184418ab55a34569a3b3de39d32f9974e1 +quay.io/jetstack/cert-manager-acmesolver:v1.21.3@sha256:c8c1225bb2fe8ab37a330b77f0d8c2ee6a41210fcb54fc07ca606ab9a022b8b7 diff --git a/kube/scripts/airgap/list.go b/kube/scripts/airgap/list.go new file mode 100644 index 0000000..8bf1f49 --- /dev/null +++ b/kube/scripts/airgap/list.go @@ -0,0 +1,60 @@ +// Package airgap is the pinned image list shared by online pull and the airgap archive. +package airgap + +import ( + "bufio" + _ "embed" + "strings" +) + +//go:embed image-list.txt +var imageList string + +// Images returns the pinned image references, one per line. +// amd64, arm64, and arm package and pull this list. +func Images() []string { + return parseList(imageList) +} + +// ImagesFor returns the images packaged and pulled for arch. +// riscv64 omits metrics-server and the cert-manager images. +func ImagesFor(arch string) []string { + images := Images() + if arch != "riscv64" { + return images + } + out := make([]string, 0, len(images)) + for _, ref := range images { + if omittedOnRISCV(ref) { + continue + } + out = append(out, ref) + } + return out +} + +func parseList(body string) []string { + var out []string + scanner := bufio.NewScanner(strings.NewReader(body)) + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + out = append(out, line) + } + return out +} + +func omittedOnRISCV(ref string) bool { + name, _, _ := strings.Cut(ref, "@") + repo, _, _ := strings.Cut(name, ":") + switch { + case repo == "metrics-server/metrics-server", strings.HasSuffix(repo, "/metrics-server/metrics-server"): + return true + case strings.HasPrefix(repo, "cert-manager-"), strings.Contains(repo, "/cert-manager-"): + return true + default: + return false + } +} diff --git a/kube/scripts/airgap/list_test.go b/kube/scripts/airgap/list_test.go new file mode 100644 index 0000000..e7da193 --- /dev/null +++ b/kube/scripts/airgap/list_test.go @@ -0,0 +1,39 @@ +package airgap + +import ( + "slices" + "strings" + "testing" +) + +func TestImagesForRISCVOmitsUnpublishedAddons(t *testing.T) { + if len(Images()) != 12 { + t.Fatalf("pin list %d", len(Images())) + } + for _, arch := range []string{"amd64", "arm64", "arm"} { + if !slices.Equal(ImagesFor(arch), Images()) { + t.Fatalf("%s list changed", arch) + } + } + got := ImagesFor("riscv64") + if len(got) != 6 { + t.Fatalf("riscv64 list %d: %v", len(got), got) + } + if !strings.HasPrefix(got[0], "docker.io/portainer/pause:latest@sha256:df6d2fb5") { + t.Fatalf("pause %s", got[0]) + } + for _, ref := range got { + if strings.Contains(ref, "metrics-server") || strings.Contains(ref, "cert-manager") { + t.Fatalf("riscv64 list contains %s", ref) + } + } + var omitted int + for _, ref := range Images() { + if !slices.Contains(got, ref) { + omitted++ + } + } + if omitted != 6 { + t.Fatalf("omitted %d", omitted) + } +} diff --git a/kube/scripts/airgap/package_test.go b/kube/scripts/airgap/package_test.go new file mode 100644 index 0000000..ac91faf --- /dev/null +++ b/kube/scripts/airgap/package_test.go @@ -0,0 +1,185 @@ +package airgap + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestPackageScriptWritesPinList(t *testing.T) { + for _, arch := range []string{"amd64", "arm64", "arm", "riscv64"} { + t.Run(arch, func(t *testing.T) { + packageScriptWritesPinList(t, arch) + }) + } +} + +func packageScriptWritesPinList(t *testing.T, arch string) { + t.Helper() + root := kubeRoot(t) + dir := t.TempDir() + tarPath := filepath.Join(dir, "images.tar") + wantImages := ImagesFor(arch) + var raw bytes.Buffer + if err := WriteTar(&raw, wantImages); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(tarPath, raw.Bytes(), 0o644); err != nil { + t.Fatal(err) + } + logPath := filepath.Join(dir, "ctr.log") + ctrPath := filepath.Join(dir, "ctr") + script := `#!/bin/sh +set -eu +printf '%s\n' "$*" >> "$CTR_LOG" +if [ "$1" = "namespaces" ]; then + exit 0 +fi +if [ "$4" = "pull" ]; then + exit 0 +fi +if [ "$4" = "export" ]; then + cp "$CTR_TAR" "$6" + exit 0 +fi +echo "unexpected: $*" >&2 +exit 1 +` + if err := os.WriteFile(ctrPath, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + out := filepath.Join(dir, "edgelet-kube-airgap-images-"+arch+".tar.zst") + cmd := exec.Command("bash", filepath.Join(root, "scripts", "package-airgap")) + cmd.Dir = root + cmd.Env = append(os.Environ(), + "ARCH="+arch, + "OUT="+out, + "CTR="+ctrPath, + "CTR_LOG="+logPath, + "CTR_TAR="+tarPath, + "GOWORK=off", + ) + output, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("package-airgap: %v\n%s", err, output) + } + names, err := ListFile(out) + if err != nil { + t.Fatal(err) + } + if !slices.Equal(names, wantImages) { + t.Fatalf("archive %v", names) + } + log, err := os.ReadFile(logPath) + if err != nil { + t.Fatal(err) + } + assertCtrExportsPinList(t, string(log), arch) +} + +func TestPackageScriptRefusesOtherArch(t *testing.T) { + root := kubeRoot(t) + cmd := exec.Command("bash", filepath.Join(root, "scripts", "package-airgap")) + cmd.Dir = root + cmd.Env = append(os.Environ(), "ARCH=ppc64le", "GOWORK=off") + output, err := cmd.CombinedOutput() + if err == nil { + t.Fatal("unsupported architecture was built") + } + if !strings.Contains(string(output), "unsupported architecture") { + t.Fatalf("output %s", output) + } +} + +func TestPackageScriptSkipsRuntimeEmbed(t *testing.T) { + root := kubeRoot(t) + out := filepath.Join(root, "cmd", "edgelet-kube", "embed", AssetAMD64) + t.Cleanup(func() { + _ = os.Remove(out) + }) + cmd := exec.Command("bash", filepath.Join(root, "scripts", "package-airgap")) + cmd.Dir = root + cmd.Env = append(os.Environ(), "ARCH=amd64", "OUT="+out, "GOWORK=off") + output, err := cmd.CombinedOutput() + if err == nil { + t.Fatal("archive was written into the runtime") + } + if !strings.Contains(string(output), "beside the binary") { + t.Fatalf("output %s", output) + } + if _, err := os.Stat(out); !os.IsNotExist(err) { + t.Fatal(err) + } +} + +func TestRuntimeBuildOmitsAirgapAsset(t *testing.T) { + root := kubeRoot(t) + for _, rel := range []string{ + "scripts/build.sh", + "scripts/pack/main.go", + "scripts/bundle-stage.sh", + "cmd/edgelet-kube/embed.go", + "cmd/edgelet-kube/extract.go", + "internal/bundle/archive.go", + } { + body, err := os.ReadFile(filepath.Join(root, rel)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(body), AssetAMD64) { + t.Fatalf("%s links the airgap archive", rel) + } + } + matches, err := filepath.Glob(filepath.Join(root, "cmd", "edgelet-kube", "embed", "*airgap*")) + if err != nil { + t.Fatal(err) + } + if len(matches) != 0 { + t.Fatal(matches) + } +} + +func assertCtrExportsPinList(t *testing.T, log, arch string) { + t.Helper() + platform := "--platform=linux/" + arch + if arch == "arm" { + platform = "--platform=linux/arm/v7" + } + var pulled []string + var exported []string + for _, line := range strings.Split(strings.TrimSpace(log), "\n") { + fields := strings.Fields(line) + switch { + case len(fields) >= 4 && fields[0] == "-n" && fields[1] == "k8s.io" && fields[2] == "images" && fields[3] == "pull": + if fields[4] != platform { + t.Fatalf("pull %s", line) + } + pulled = append(pulled, fields[len(fields)-1]) + case len(fields) >= 6 && fields[0] == "-n" && fields[1] == "k8s.io" && fields[2] == "images" && fields[3] == "export": + if fields[4] != platform { + t.Fatalf("export %s", line) + } + exported = fields[6:] + } + } + want := ImagesFor(arch) + if !slices.Equal(pulled, want) { + t.Fatalf("pulled %v", pulled) + } + if !slices.Equal(exported, want) { + t.Fatalf("exported %v", exported) + } +} + +func kubeRoot(t *testing.T) string { + t.Helper() + root, err := filepath.Abs(filepath.Join("..", "..")) + if err != nil { + t.Fatal(err) + } + return root +} diff --git a/kube/scripts/airgap/pins.go b/kube/scripts/airgap/pins.go new file mode 100644 index 0000000..6f0f9cc --- /dev/null +++ b/kube/scripts/airgap/pins.go @@ -0,0 +1,32 @@ +package airgap + +import ( + "bufio" + _ "embed" + "strings" +) + +//go:embed pins.txt +var pinFile string + +// KubernetesVersion is the Kubernetes patch this binary reports. +func KubernetesVersion() string { + return pin("kubernetes") +} + +// ChartVersion is the pinned chart version for name. +// name is traefik, traefik-crd, gateway-api-crd, or cert-manager. +func ChartVersion(name string) string { + return pin(name) +} + +func pin(name string) string { + scanner := bufio.NewScanner(strings.NewReader(pinFile)) + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) == 2 && fields[0] == name { + return fields[1] + } + } + return "" +} diff --git a/kube/scripts/airgap/pins.txt b/kube/scripts/airgap/pins.txt new file mode 100644 index 0000000..39b8e84 --- /dev/null +++ b/kube/scripts/airgap/pins.txt @@ -0,0 +1,6 @@ +kubernetes v1.37.2 +cri-api k8s.io/cri-api v0.37.2 +traefik 41.6.101+up41.6.1 +traefik-crd 41.6.101+up41.6.1 +gateway-api-crd 1.6.301 +cert-manager v1.21.3 diff --git a/kube/scripts/airgap/pins_test.go b/kube/scripts/airgap/pins_test.go new file mode 100644 index 0000000..8c5ef5a --- /dev/null +++ b/kube/scripts/airgap/pins_test.go @@ -0,0 +1,25 @@ +package airgap + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestKubernetesVersion(t *testing.T) { + if got := KubernetesVersion(); got != "v1.37.2" { + t.Fatalf("kubernetes version %q", got) + } +} + +func TestModuleMatchesKubernetesVersion(t *testing.T) { + body, err := os.ReadFile(filepath.Join(kubeRoot(t), "go.mod")) + if err != nil { + t.Fatal(err) + } + want := "k8s.io/kubernetes " + KubernetesVersion() + if !strings.Contains(string(body), want) { + t.Fatalf("go.mod does not require %s", want) + } +} diff --git a/kube/scripts/airgap/prefix.go b/kube/scripts/airgap/prefix.go new file mode 100644 index 0000000..d8c9005 --- /dev/null +++ b/kube/scripts/airgap/prefix.go @@ -0,0 +1,73 @@ +package airgap + +import "strings" + +// Resolve returns the image name kubelet and the staged manifests use. +// An empty registry leaves ref unchanged. A ref that is not on the pin list +// is returned unchanged, including an image an operator created. +func Resolve(registry, ref string) string { + registry = cleanRegistry(registry) + ref = strings.TrimSpace(ref) + if registry == "" || !listed(ref) || strings.HasPrefix(ref, registry+"/") { + return ref + } + return registry + "/" + ref +} + +// Names returns the pin list as kubelet and the staged manifests use it. +func Names(registry string) []string { + images := Images() + out := make([]string, len(images)) + for i, image := range images { + out[i] = Resolve(registry, image) + } + return out +} + +// PrefixedNames are the extra names an imported pin-list image is tagged with. +// The tag without a digest is included so kubelet can use the pause name. +// An empty registry, or a ref that is not on the pin list, returns nil. +func PrefixedNames(registry, ref string) []string { + registry = cleanRegistry(registry) + ref = strings.TrimSpace(ref) + if registry == "" || !listed(ref) { + return nil + } + var out []string + add := func(name string) { + if name == "" || name == ref { + return + } + for _, existing := range out { + if existing == name { + return + } + } + out = append(out, name) + } + add(Resolve(registry, ref)) + add(Resolve(registry, referenceName(ref))) + return out +} + +func cleanRegistry(registry string) string { + return strings.Trim(strings.TrimSpace(registry), "/") +} + +func listed(ref string) bool { + name := referenceName(ref) + if name == "" { + return false + } + for _, image := range Images() { + if referenceName(image) == name { + return true + } + } + return false +} + +func referenceName(ref string) string { + name, _, _ := strings.Cut(strings.TrimSpace(ref), "@") + return name +} diff --git a/kube/scripts/airgap/zstdcmd/main.go b/kube/scripts/airgap/zstdcmd/main.go new file mode 100644 index 0000000..e27815e --- /dev/null +++ b/kube/scripts/airgap/zstdcmd/main.go @@ -0,0 +1,56 @@ +// Command zstdcmd compresses an image tar, or prints the names stored in one. +package main + +import ( + "errors" + "flag" + "fmt" + "os" + + "github.com/eclipse-iofog/edgelet-kube/scripts/airgap" +) + +func main() { + list := flag.String("list", "", "archive whose image names are printed") + in := flag.String("in", "", "tar to compress") + out := flag.String("out", "", "zstd archive to write") + images := flag.String("images", "", "print the pin list for this architecture") + flag.Parse() + if err := run(*list, *in, *out, *images); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "airgap: %v\n", err) + os.Exit(1) + } +} + +func run(list, in, out, arch string) error { + if arch != "" { + if list != "" || in != "" || out != "" { + return errors.New("images is exclusive") + } + for _, ref := range airgap.ImagesFor(arch) { + fmt.Println(ref) + } + return nil + } + if list != "" { + names, err := airgap.ListFile(list) + if err != nil { + return err + } + for _, name := range names { + fmt.Println(name) + } + return nil + } + if in == "" || out == "" { + return errors.New("in and out are required") + } + file, err := os.Open(in) + if err != nil { + return err + } + defer func() { + _ = file.Close() + }() + return airgap.Compress(out, file) +} diff --git a/kube/scripts/build.sh b/kube/scripts/build.sh new file mode 100755 index 0000000..6e8b95e --- /dev/null +++ b/kube/scripts/build.sh @@ -0,0 +1,131 @@ +#!/bin/bash +# Build the thin edgelet-kube binary and the fat runtime it extracts. +# Thin is CGO_ENABLED=0. Fat is CGO_ENABLED=1. +# The zstd bundle holds the fat runtime and the aux binaries. It holds no OCI image. +# The airgap image archive is published beside this binary. It is not embedded here. +# On macOS the Linux binaries are built inside the embed image, which has the C toolchain. +set -euo pipefail + +cd "$(dirname "$0")/.." +export GOWORK=off + +if [ "$(uname -s)" = Darwin ]; then + case "$(uname -m)" in + arm64|aarch64) arch=arm64 ;; + *) arch=amd64 ;; + esac + for arg in "$@"; do + case "$arg" in + --arch=*) arch="${arg#*=}" ;; + *) + echo "unknown argument: $arg" >&2 + exit 2 + ;; + esac + done + case "$arch" in + amd64|arm64|arm|riscv64) ;; + *) + echo "unsupported architecture: $arch" >&2 + exit 2 + ;; + esac + repo="$(cd .. && pwd)" + uid="$(id -u)" + gid="$(id -g)" + echo "building linux/${arch} inside the embed image" + # arm and riscv64 cross-compile in the host image. amd64 and arm64 run as that platform. + if [ "$arch" = amd64 ] || [ "$arch" = arm64 ]; then + docker build --platform "linux/${arch}" -f "${repo}/build/Dockerfile.embedded" -t edgelet-embed-ci "${repo}" + docker run --platform "linux/${arch}" --rm \ + -v "${repo}:/src" -w /src \ + -e GOWORK=off -e ARCH="${arch}" \ + edgelet-embed-ci \ + bash kube/scripts/build.sh + docker run --platform "linux/${arch}" --rm \ + -v "${repo}:/src" -w /src \ + edgelet-embed-ci \ + chown -R "${uid}:${gid}" kube/build kube/cmd/edgelet-kube/embed + else + docker build -f "${repo}/build/Dockerfile.embedded" -t edgelet-embed-ci "${repo}" + docker run --rm \ + -v "${repo}:/src" -w /src \ + -e GOWORK=off -e ARCH="${arch}" \ + edgelet-embed-ci \ + bash kube/scripts/build.sh + docker run --rm \ + -v "${repo}:/src" -w /src \ + edgelet-embed-ci \ + chown -R "${uid}:${gid}" kube/build kube/cmd/edgelet-kube/embed + fi + exit 0 +fi + +cc_for_arch() { + host=$(uname -m) + case "$1" in + amd64) + if [ "$host" = x86_64 ]; then + echo "${CC:-gcc}" + else + echo "${CC:-x86_64-linux-gnu-gcc}" + fi + ;; + arm64) + if [ "$host" = aarch64 ] || [ "$host" = arm64 ]; then + echo "${CC:-gcc}" + else + echo "${CC:-aarch64-linux-gnu-gcc}" + fi + ;; + arm) echo "${CC:-arm-linux-gnueabihf-gcc}" ;; + riscv64) echo "${CC:-riscv64-linux-gnu-gcc}" ;; + *) + echo "unsupported architecture: $1" >&2 + return 1 + ;; + esac +} + +arch="${ARCH:-amd64}" +case "$arch" in +amd64|arm64|arm|riscv64) ;; +*) + echo "unsupported architecture: $arch" >&2 + exit 2 + ;; +esac +root="$(cd .. && pwd)" + +bash scripts/bundle-stage.sh ensure "$root" "$arch" + +mkdir -p build +k8s_version=$(awk '$1 == "kubernetes" { print $2; exit }' scripts/airgap/pins.txt) +k8s_rest=${k8s_version#v} +k8s_major=${k8s_rest%%.*} +k8s_minor=${k8s_rest#*.} +k8s_minor=${k8s_minor%%.*} +# -s -w omit the symbol table and DWARF info. The fat runtime is stripped +# before it is packed, so the thin binary does not carry them either. +version_ldflags="-X k8s.io/component-base/version.gitVersion=${k8s_version} -X k8s.io/component-base/version.gitMajor=${k8s_major} -X k8s.io/component-base/version.gitMinor=${k8s_minor} -X k8s.io/client-go/pkg/version.gitVersion=${k8s_version} -X k8s.io/client-go/pkg/version.gitMajor=${k8s_major} -X k8s.io/client-go/pkg/version.gitMinor=${k8s_minor}" +ldflags="-s -w ${version_ldflags}" +# Fat tags match the embed runtime. The thin launcher only drops CLI docs. +fat_tags="netcgo osusergo urfave_cli_no_docs sqlite_omit_load_extension apparmor seccomp" +thin_tags="urfave_cli_no_docs" +goarm="" +if [ "$arch" = arm ]; then + goarm="${GOARM:-7}" +fi +goarm_env=() +if [ -n "$goarm" ]; then + goarm_env=(GOARM="$goarm") +fi +cc=$(cc_for_arch "$arch") || exit 1 +CGO_ENABLED=1 GOOS=linux GOARCH="$arch" "${goarm_env[@]}" CC="$cc" \ + go build -trimpath -tags "${fat_tags}" -ldflags "${ldflags}" -o build/edgelet-kube-server ./cmd/edgelet-kube-server + +stage="$(mktemp -d)" +trap 'rm -rf "$stage"' EXIT +bash scripts/bundle-stage.sh assemble "$stage" "$root" build/edgelet-kube-server +env -u GOOS -u GOARCH go run ./scripts/pack -stage "$stage" -out cmd/edgelet-kube/embed +CGO_ENABLED=0 GOOS=linux GOARCH="$arch" "${goarm_env[@]}" go build -trimpath -tags "${thin_tags}" -ldflags "-s -w" -o build/edgelet-kube ./cmd/edgelet-kube diff --git a/kube/scripts/bundle-stage.sh b/kube/scripts/bundle-stage.sh new file mode 100644 index 0000000..6fac2d4 --- /dev/null +++ b/kube/scripts/bundle-stage.sh @@ -0,0 +1,186 @@ +#!/bin/bash +# Assemble bin/ for the zstd bundle from the fat runtime and the agent aux build. +# Usage: bundle-stage.sh ensure +# bundle-stage.sh assemble +set -euo pipefail + +usage() { + echo "usage: bundle-stage.sh ensure " >&2 + echo " bundle-stage.sh assemble " >&2 + exit 2 +} + +elf_machine() { + od -An -t u2 -j 18 -N 2 "$1" | awk '{print $1}' +} + +want_machine() { + case "$1" in + amd64) echo 62 ;; + arm64) echo 183 ;; + arm) echo 40 ;; + riscv64) echo 243 ;; + *) + echo "unsupported architecture: $1" >&2 + return 1 + ;; + esac +} + +matches_arch() { + local path="$1" + local machine="$2" + local got + [ -f "$path" ] && [ ! -L "$path" ] || return 1 + got=$(elf_machine "$path") || return 1 + [ "$got" = "$machine" ] +} + +link_is() { + [ -L "$1" ] && [ "$(readlink "$1")" = "$2" ] +} + +bins_ready() { + local machine="$1" + local bin="$2" + local name + for name in containerd-shim-runc-v2 crun cni; do + matches_arch "$bin/$name" "$machine" || return 1 + done + for name in bridge host-local loopback portmap; do + link_is "$bin/$name" cni || return 1 + done +} + +aux_ready() { + local machine="$1" + local staged="$2" + local name + matches_arch "$staged/ip" "$machine" || return 1 + matches_arch "$staged/busybox" "$machine" || return 1 + matches_arch "$staged/aux/xtables-nft-multi" "$machine" || return 1 + for name in iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore; do + link_is "$staged/aux/$name" xtables-nft-multi || return 1 + done + link_is "$staged/modprobe" busybox || return 1 +} + +align_iptables_nft() { + local aux="$1/aux" + local name + [ -f "$aux/xtables-nft-multi" ] || return 1 + for name in iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore; do + rm -f "$aux/$name" + ln -s xtables-nft-multi "$aux/$name" + done +} + +deps_present() { + local pc + command -v gcc >/dev/null 2>&1 || return 1 + command -v autoconf >/dev/null 2>&1 || return 1 + for pc in libseccomp libsystemd json-c; do + pkg-config --exists "$pc" 2>/dev/null || return 1 + done +} + +install_build_deps() { + local root="$1" + local arch="$2" + if deps_present; then + return 0 + fi + if [ "$(id -u)" -eq 0 ]; then + TARGETARCH="$arch" bash "$root/scripts/install-embed-build-deps" + return 0 + fi + if command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1; then + sudo -n TARGETARCH="$arch" bash "$root/scripts/install-embed-build-deps" + return 0 + fi + echo "linux/$arch aux build needs gcc, autoconf, libseccomp, libsystemd, and json-c" >&2 + exit 1 +} + +ensure_aux() { + local root="$1" + local arch="$2" + local machine bin staged + machine=$(want_machine "$arch") + bin="$root/build/bin" + staged="$root/build/stage/bin" + if ! bins_ready "$machine" "$bin"; then + if [ "$(uname -s)" != "Linux" ]; then + echo "linux/$arch shim, crun, and cni are not in $bin" >&2 + echo "The agent builds crun on Linux. Build those binaries for linux/$arch, then run this again." >&2 + exit 1 + fi + install_build_deps "$root" "$arch" + env -u GOOS -u GOARCH ARCH="$arch" bash "$root/scripts/download" + if ! env -u GOOS -u GOARCH ARCH="$arch" bash "$root/scripts/build-embedded"; then + if ! bins_ready "$machine" "$bin"; then + echo "agent source-build did not produce linux/$arch shim, crun, and cni" >&2 + exit 1 + fi + echo "shim, crun, and cni are ready; the image pull is not part of this bundle" >&2 + fi + if ! bins_ready "$machine" "$bin"; then + echo "agent source-build did not produce linux/$arch shim, crun, and cni" >&2 + exit 1 + fi + fi + if ! aux_ready "$machine" "$staged"; then + mkdir -p "$staged" + env -u GOOS -u GOARCH ARCH="$arch" bash "$root/scripts/download-root" + env -u GOOS -u GOARCH ARCH="$arch" bash "$root/scripts/stage-root-aux" + # The agent stage points iptables at xtables-legacy-multi and leaves + # iptables-save and iptables-restore on xtables-nft-multi. kube-proxy + # uses all three, so this bundle keeps the k3s-root nft links. + align_iptables_nft "$staged" || true + if ! aux_ready "$machine" "$staged"; then + echo "agent source-build did not produce linux/$arch ip, busybox, and xtables-nft" >&2 + exit 1 + fi + fi +} + +assemble_stage() { + local dest="$1" + local root="$2" + local fat="$3" + local bin staged name + if [ ! -s "$fat" ]; then + echo "fat runtime is missing" >&2 + exit 1 + fi + bin="$root/build/bin" + staged="$root/build/stage/bin" + mkdir -p "$dest/bin" + cp "$fat" "$dest/bin/edgelet-kube" + chmod 755 "$dest/bin/edgelet-kube" + cp -a "$bin/containerd-shim-runc-v2" "$bin/crun" "$bin/cni" "$dest/bin/" + for name in bridge host-local loopback portmap; do + ln -s cni "$dest/bin/$name" + done + cp -a "$staged/aux" "$dest/bin/aux" + cp -a "$staged/ip" "$staged/busybox" "$dest/bin/" + ln -s busybox "$dest/bin/modprobe" +} + +if [ "$#" -lt 1 ]; then + usage +fi + +case "$1" in +ensure) + [ "$#" -eq 3 ] || usage + ensure_aux "$2" "$3" + ;; +assemble) + [ "$#" -eq 4 ] || usage + assemble_stage "$2" "$3" "$4" + ;; +*) + usage + ;; +esac diff --git a/kube/scripts/conformance.sh b/kube/scripts/conformance.sh new file mode 100755 index 0000000..de6db4c --- /dev/null +++ b/kube/scripts/conformance.sh @@ -0,0 +1,229 @@ +#!/usr/bin/env bash +# Install one linux/amd64 node from the release binary and the matching +# airgap archive, then run sonobuoy in certified-conformance mode. +# The default addons stay installed. A second node is not added. +# +# Usage: +# sudo ./conformance.sh \ +# --binary=dist/edgelet-kube-linux-amd64 \ +# --images=dist/edgelet-kube-airgap-images-amd64.tar.zst +# +# CONFORMANCE_TIMEOUT_MINUTES is the job time limit in minutes (default 240). +# The sonobuoy run stops 45 minutes before that limit so install and +# retrieval finish inside it. RELEASE_NAME, when it is a release tag, +# must name the same Kubernetes patch the binary reports. + +set -euo pipefail + +SCRIPT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd) +KUBECONFIG_PATH=/etc/edgelet-kube/edgelet-kube.yaml +IMAGES_DIR=/var/lib/edgelet-kube/agent/images +BINARY_NAME=edgelet-kube-linux-amd64 +IMAGES_NAME=edgelet-kube-airgap-images-amd64.tar.zst +KUBECTL=/usr/local/bin/kubectl +SONOBUOY_VERSION=0.57.5 +SONOBUOY_SUM=7c5c2250e5103c98f4dad2bcab86baf954e319c57c419c113f28f5060e62f129 + +die() { + echo "ERROR: $1" >&2 + exit 1 +} + +binary= +images= +for arg in "$@"; do + case $arg in + --binary=*) + binary=${arg#*=} + ;; + --images=*) + images=${arg#*=} + ;; + --help|-h) + sed -n '2,12p' "$0" + exit 0 + ;; + *) + die "unknown option: $arg" + ;; + esac +done + +[ -n "$binary" ] || die "--binary is required" +[ -n "$images" ] || die "--images is required" +[ -f "$binary" ] || die "release binary not found: $binary" +[ -f "$images" ] || die "airgap archive not found: $images" +[ "$(basename "$binary")" = "$BINARY_NAME" ] || die "binary must be named $BINARY_NAME" +[ "$(basename "$images")" = "$IMAGES_NAME" ] || die "airgap archive must be named $IMAGES_NAME" +[ "$(uname -m)" = x86_64 ] || die "the conformance node is linux/amd64" + +if [ "${SONOBUOY_MODE:-certified-conformance}" != certified-conformance ]; then + die "mode must be certified-conformance" +fi + +minutes=${CONFORMANCE_TIMEOUT_MINUTES:-240} +case $minutes in +''|*[!0-9]*) die "CONFORMANCE_TIMEOUT_MINUTES must be a number of minutes" ;; +esac +# Minutes kept for install and for retrieving results. +reserve_minutes=45 +if [ "$minutes" -le "$reserve_minutes" ]; then + die "CONFORMANCE_TIMEOUT_MINUTES must be greater than ${reserve_minutes}" +fi +wait_minutes=$((minutes - reserve_minutes)) +timeout_seconds=$((wait_minutes * 60)) + +pin=$(awk '$1 == "kubernetes" { print $2; exit }' "$SCRIPT_DIR/airgap/pins.txt") +[ -n "$pin" ] || die "kubernetes patch is not set" +release_name=${RELEASE_NAME:-} +case $release_name in +edgelet-kube-v*+edgelet*) + named=${release_name#edgelet-kube-} + named=${named%%+*} + named=${named%%-*} + [ "$named" = "$pin" ] || die "patch ${named} in ${release_name} is not ${pin}" + ;; +esac + +command -v go >/dev/null 2>&1 || die "go is required to read the binary version" +command -v curl >/dev/null 2>&1 || die "curl is required" +command -v file >/dev/null 2>&1 || die "file is required" +file -b "$binary" | grep -q 'ELF 64-bit LSB executable, x86-64' || die "binary is not a linux/amd64 executable" + +if [ "$(id -u)" -ne 0 ]; then + exec sudo --preserve-env=CONFORMANCE_TIMEOUT_MINUTES,SONOBUOY_MODE,RELEASE_NAME,CONFORMANCE_RESULTS,PATH \ + env PATH="$PATH" bash "$0" "$@" +fi + +refuse_disabled_addon() { + local file=$1 + awk ' + /^[[:space:]]*#/ { next } + /^[[:space:]]*disable\+?:/ { on = 1 } + on && /^[^[:space:]#]/ && !/^[[:space:]]*disable\+?:/ { on = 0 } + on && /traefik|cert-manager|metrics-server|local-storage|local-path/ { found = 1 } + END { exit found ? 0 : 1 } + ' "$file" +} + +shopt -s nullglob +for config in /etc/edgelet-kube/config.yaml /etc/edgelet-kube/config.yaml.d/*.yaml; do + if [ -f "$config" ] && refuse_disabled_addon "$config"; then + die "default addons are turned off in ${config}" + fi +done +shopt -u nullglob + +if swapon --show 2>/dev/null | grep -q .; then + swapoff -a +fi + +echo "Installing ${IMAGES_NAME}" +mkdir -p "$IMAGES_DIR" +install -m 0644 "$images" "${IMAGES_DIR}/${IMAGES_NAME}" + +echo "Installing ${BINARY_NAME}" +bash "$SCRIPT_DIR/install.sh" --bin-path="$binary" + +export KUBECONFIG=$KUBECONFIG_PATH + +wait_until() { + local label=$1 timeout=$2 + shift 2 + local elapsed=0 + while true; do + if "$@"; then + return 0 + fi + if [ "$elapsed" -ge "$timeout" ]; then + echo "ERROR: timed out waiting for ${label}" >&2 + return 1 + fi + sleep 5 + elapsed=$((elapsed + 5)) + done +} + +node_ready() { + [ -f "$KUBECONFIG_PATH" ] || return 1 + local nodes count ready + nodes=$("$KUBECTL" get nodes --no-headers 2>/dev/null || true) + count=$(printf '%s\n' "$nodes" | awk 'NF { c++ } END { print c+0 }') + ready=$(printf '%s\n' "$nodes" | awk '$2 == "Ready" { c++ } END { print c+0 }') + if [ "$count" -gt 1 ]; then + die "conformance target is one node" + fi + [ "$count" -eq 1 ] && [ "$ready" -eq 1 ] +} + +echo "Waiting for the node" +wait_until "the node" 1200 node_ready + +deploy_ready() { + local ns=$1 name=$2 ready want + "$KUBECTL" -n "$ns" get deploy "$name" >/dev/null 2>&1 || return 1 + ready=$("$KUBECTL" -n "$ns" get deploy "$name" -o jsonpath='{.status.readyReplicas}') + want=$("$KUBECTL" -n "$ns" get deploy "$name" -o jsonpath='{.spec.replicas}') + [ -n "$ready" ] && [ "$ready" = "$want" ] && [ "$ready" != 0 ] +} + +wait_deploy() { + local ns=$1 name=$2 + echo "Waiting for deployment ${ns}/${name}" + if ! wait_until "deployment ${ns}/${name}" 900 deploy_ready "$ns" "$name"; then + "$KUBECTL" get deploy -A -o wide || true + exit 1 + fi +} + +wait_deploy kube-system coredns +wait_deploy kube-system traefik +wait_deploy kube-system metrics-server +wait_deploy kube-system local-path-provisioner +wait_deploy cert-manager cert-manager + +count=$("$KUBECTL" get nodes --no-headers | awk 'NF { c++ } END { print c+0 }') +[ "$count" -eq 1 ] || die "conformance target is one node" + +got=$("$KUBECTL" version -o jsonpath='{.serverVersion.gitVersion}') +[ "$got" = "$pin" ] || die "gitVersion ${got} is not ${pin}" +if [ -n "$release_name" ] && [ "$got" = "$release_name" ]; then + die "gitVersion is the release name" +fi + +fat=$(find /var/lib/edgelet-kube/data -type f -path '*/bin/edgelet-kube' -print -quit) +[ -n "$fat" ] || die "fat runtime was not extracted" +info=$(go version -m "$fat") +count=$(printf '%s\n' "$info" | grep -o -F "version.gitVersion=${pin}" | wc -l | tr -d ' ' || true) +[ "$count" -ge 2 ] || die "binary gitVersion is not ${pin}" +if [ -n "$release_name" ] && printf '%s\n' "$info" | grep -F -q "gitVersion=${release_name}"; then + die "release name was stamped as gitVersion" +fi + +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +archive="sonobuoy_${SONOBUOY_VERSION}_linux_amd64.tar.gz" +curl -fsSL -o "$tmp/$archive" \ + "https://github.com/vmware-tanzu/sonobuoy/releases/download/v${SONOBUOY_VERSION}/${archive}" +echo "${SONOBUOY_SUM} ${tmp}/${archive}" | sha256sum -c - +tar -C "$tmp" -xzf "$tmp/$archive" sonobuoy +install -m 0755 "$tmp/sonobuoy" /usr/local/bin/sonobuoy + +results=${CONFORMANCE_RESULTS:-/var/tmp/sonobuoy-results.tar.gz} +mkdir -p "$(dirname "$results")" +echo "Running sonobuoy --mode certified-conformance (wait ${wait_minutes}m, job limit ${minutes}m)" +status=0 +/usr/local/bin/sonobuoy run \ + --mode=certified-conformance \ + --kubeconfig="$KUBECONFIG_PATH" \ + --kubernetes-version="$pin" \ + --timeout="$timeout_seconds" \ + --wait="$wait_minutes" \ + --wait-output=progress || status=$? + +if /usr/local/bin/sonobuoy retrieve --kubeconfig="$KUBECONFIG_PATH" --filename "$results"; then + /usr/local/bin/sonobuoy results "$results" || status=$? +else + status=1 +fi +exit "$status" diff --git a/kube/scripts/install.sh b/kube/scripts/install.sh new file mode 100755 index 0000000..39d0cb7 --- /dev/null +++ b/kube/scripts/install.sh @@ -0,0 +1,111 @@ +#!/bin/sh +# Install the thin edgelet-kube binary, the kubectl, ctr, and crictl links, +# and edgelet-kube.service, then start it. +# A second run replaces the binary and restarts the unit. +# /var/lib/edgelet-kube/db/state.db, /var/lib/edgelet-kube/server/tls/, +# and /var/lib/edgelet-kube/server/cred/encryption-config.json are kept. +# A missing /etc/edgelet-kube/config.yaml is left missing. The node is not enrolled. +# +# Usage: +# sudo ./install.sh +# sudo ./install.sh --bin-path=build/edgelet-kube +# +# The thin binary defaults to ../build/edgelet-kube beside this script. +# kubectl, ctr, and crictl are symlinks to that binary. argv0 selects the command. +# +# Optional path overrides: +# EDGELET_KUBE_BIN_DIR destination for the thin binary (default /usr/local/bin) +# EDGELET_KUBE_UNIT_DIR systemd unit directory (default /etc/systemd/system) +# EDGELET_KUBE_LIBEXEC_DIR directory for prepare-kernel (default /usr/libexec/edgelet-kube) +# EDGELET_KUBE_SYSTEMCTL systemctl program (default systemctl) + +set -eu + +die() { + echo "ERROR: $1" >&2 + exit 1 +} + +usage() { + cat <&2 + exit 1 +} + +need() { + if ! grep -q "$1" "$2"; then + fail "missing [$1] in $2" + fi +} + +mode_of() { + if [ "$(uname -s)" = "Darwin" ]; then + stat -f '%Lp' "$1" + else + stat -c '%a' "$1" + fi +} + +if grep -n 'edgelet\.service' \ + scripts/install.sh \ + packaging/systemd/edgelet-kube.service \ + packaging/systemd/prepare-kernel.sh +then + fail "agent unit name appears in the install files" +fi + +if grep -n 'rm ' scripts/install.sh; then + fail "install script removes files" +fi +if grep -n -E 'ota|drain' scripts/install.sh packaging/systemd/edgelet-kube.service; then + fail "agent upgrade path is referenced" +fi + +unit=packaging/systemd/edgelet-kube.service +need '^ExecStart=/usr/local/bin/edgelet-kube server$' "$unit" +need '^KillMode=process$' "$unit" +need '^Delegate=yes$' "$unit" +need '^Restart=always$' "$unit" +need '^RestartSec=5s$' "$unit" +need '^ExecStartPre=/usr/libexec/edgelet-kube/prepare-kernel$' "$unit" + +if grep -q 'DelegateSubgroup' "$unit"; then + fail "unit delegates a subgroup" +fi + +helper=packaging/systemd/prepare-kernel.sh +need 'modprobe br_netfilter' "$helper" +need 'sysctl -w net.ipv4.ip_forward=1' "$helper" +need 'sysctl -w net.bridge.bridge-nf-call-iptables=1' "$helper" +need '/etc/edgelet-kube/config.yaml' "$helper" + +work=$(mktemp -d) +cleanup() { + if [ -f "$work/pids" ]; then + while read -r pid; do + kill "$pid" 2>/dev/null || true + done <"$work/pids" + fi + rm -rf "$work" +} +trap cleanup EXIT +unset EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS || true +unset EDGELET_KUBE_CONFIG_FILE || true + +config_real=/etc/edgelet-kube/config.yaml +if [ -e "$config_real" ]; then + cksum "$config_real" >"$work/config-before" +fi + +mkdir -p "$work/units" +printf '%s\n' '[Unit]' 'Description=agent' >"$work/units/edgelet.service" +cksum "$work/units/edgelet.service" >"$work/agent-before" + +# The installed file stands in for the thin binary and execs the fat runtime +# with the same argv, so the invoked path stays argv0. +command -v cc >/dev/null 2>&1 || fail "cc is required" +cat >"$work/thin.c" <<'EOF' +#include +#include +#include + +int main(int argc, char **argv) { + char *fat = getenv("EDGELET_KUBE_FAT"); + if (fat == NULL || fat[0] == '\0') { + fprintf(stderr, "missing fat runtime\n"); + return 1; + } + execv(fat, argv); + perror("exec fat runtime"); + return 127; +} +EOF +cat >"$work/fat.c" <<'EOF' +#include + +int main(int argc, char **argv) { + int i; + printf("fat-elf\n"); + for (i = 0; i < argc; i++) { + printf("%s\n", argv[i]); + } + return 0; +} +EOF +cc -o "$work/thin" "$work/thin.c" +cc -o "$work/fat" "$work/fat.c" +chmod 0755 "$work/thin" "$work/fat" + +cat >"$work/systemctl" <> "$work/systemctl.log" +EOF +chmod 0755 "$work/systemctl" + +EDGELET_KUBE_BIN_DIR="$work/bin" \ +EDGELET_KUBE_UNIT_DIR="$work/units" \ +EDGELET_KUBE_LIBEXEC_DIR="$work/libexec" \ +EDGELET_KUBE_SYSTEMCTL="$work/systemctl" \ + sh scripts/install.sh --bin-path="$work/thin" + +cmp -s "$work/thin" "$work/bin/edgelet-kube" || fail "installed binary differs" +[ ! -L "$work/bin/edgelet-kube" ] || fail "installed binary is a symlink" +for name in kubectl ctr crictl; do + link=$work/bin/$name + [ -L "$link" ] || fail "$name is not a symlink" + [ "$(readlink "$link")" = "$work/bin/edgelet-kube" ] || fail "$name does not point at the thin binary" +done +grep -a -q 'fat-elf' "$work/fat" || fail "fat runtime missing marker" +if grep -a -q 'fat-elf' "$work/bin/edgelet-kube"; then + fail "thin binary contains the fat marker" +fi +run_client() { + name=$1 + shift + EDGELET_KUBE_FAT="$work/fat" \ + "$work/bin/$name" "$@" >"$work/client.out" || fail "$name failed" + printf '%s\n' fat-elf "$work/bin/$name" "$@" >"$work/client.want" + cmp -s "$work/client.want" "$work/client.out" || { + echo "$name output:" >&2 + cat "$work/client.out" >&2 + fail "$name did not reach the fat runtime" + } +} +run_client kubectl version +run_client ctr version +cmp -s "$unit" "$work/units/edgelet-kube.service" || fail "installed unit differs" +cmp -s "$helper" "$work/libexec/prepare-kernel" || fail "installed kernel program differs" +[ "$(mode_of "$work/bin/edgelet-kube")" = "755" ] || fail "binary mode" +[ "$(mode_of "$work/libexec/prepare-kernel")" = "755" ] || fail "kernel program mode" +[ "$(mode_of "$work/units/edgelet-kube.service")" = "644" ] || fail "unit mode" + +cksum "$work/units/edgelet.service" >"$work/agent-after" +cmp -s "$work/agent-before" "$work/agent-after" || fail "agent unit was changed" + +printf '%s\n' \ + 'daemon-reload' \ + 'enable edgelet-kube.service' \ + 'start edgelet-kube.service' >"$work/systemctl.want" +cmp -s "$work/systemctl.want" "$work/systemctl.log" || { + echo "systemctl log:" >&2 + cat "$work/systemctl.log" >&2 + fail "systemctl calls" +} + +if [ -e "$config_real" ]; then + cksum "$config_real" >"$work/config-after" + cmp -s "$work/config-before" "$work/config-after" || fail "config file changed" +else + [ ! -e "$config_real" ] || fail "config file was created" +fi +[ ! -e "$work/etc/edgelet-kube/config.yaml" ] || fail "sandbox config was created" + +help_text=$(sh scripts/install.sh --help) +if printf '%s\n' "$help_text" | grep -q 'edgelet\.service'; then + fail "help mentions the agent unit" +fi + +if sh scripts/install.sh --bin-path= >/dev/null 2>&1; then + fail "empty --bin-path succeeded" +fi +if sh scripts/install.sh --bin-path="$work/missing-binary" >/dev/null 2>&1; then + fail "missing binary succeeded" +fi + +stubs=$work/stubs +mkdir -p "$stubs" +cat >"$stubs/modprobe" <> "\$LOG" +EOF +cat >"$stubs/sysctl" <> "\$LOG" +EOF +chmod 0755 "$stubs/modprobe" "$stubs/sysctl" + +# ExecStartPre runs to completion, then the server process starts. +run_pre_then_server() { + log=$1 + shift + : >"$log" + LOG="$log" PATH="$stubs:$PATH" env "$@" "$work/libexec/prepare-kernel" + printf '%s\n' server >>"$log" +} + +expect_sysctls() { + log=$1 + printf '%s\n' \ + 'modprobe br_netfilter' \ + 'sysctl -w net.ipv4.ip_forward=1' \ + 'sysctl -w net.bridge.bridge-nf-call-iptables=1' \ + server >"$work/expect-sysctls" + cmp -s "$work/expect-sysctls" "$log" || { + echo "kernel log:" >&2 + cat "$log" >&2 + fail "sysctls were not set before the server" + } +} + +expect_untouched() { + log=$1 + printf '%s\n' server >"$work/expect-untouched" + cmp -s "$work/expect-untouched" "$log" || { + echo "kernel log:" >&2 + cat "$log" >&2 + fail "sysctls were written" + } +} + +missing=$work/missing-config.yaml +run_pre_then_server "$work/log-missing" EDGELET_KUBE_CONFIG_FILE="$missing" +expect_sysctls "$work/log-missing" +[ ! -e "$missing" ] || fail "missing config was created" + +printf '%s\n' 'protect-kernel-defaults: false' >"$work/false.yaml" +run_pre_then_server "$work/log-false" EDGELET_KUBE_CONFIG_FILE="$work/false.yaml" +expect_sysctls "$work/log-false" + +printf '%s\n' '# protect-kernel-defaults: true' 'debug: false' >"$work/comment.yaml" +run_pre_then_server "$work/log-comment" EDGELET_KUBE_CONFIG_FILE="$work/comment.yaml" +expect_sysctls "$work/log-comment" + +printf '%s\n' 'protect-kernel-defaults: false # apply' >"$work/false-comment.yaml" +run_pre_then_server "$work/log-false-comment" EDGELET_KUBE_CONFIG_FILE="$work/false-comment.yaml" +expect_sysctls "$work/log-false-comment" + +for spelling in true True TRUE; do + printf '%s\n' "protect-kernel-defaults: $spelling" >"$work/true.yaml" + run_pre_then_server "$work/log-true" EDGELET_KUBE_CONFIG_FILE="$work/true.yaml" + expect_untouched "$work/log-true" +done + +printf '%s\n' 'protect-kernel-defaults: "true"' >"$work/quoted.yaml" +run_pre_then_server "$work/log-quoted" EDGELET_KUBE_CONFIG_FILE="$work/quoted.yaml" +expect_sysctls "$work/log-quoted" + +rm -rf "$work/drop.yaml.d" +mkdir -p "$work/drop.yaml.d" +printf '%s\n' 'protect-kernel-defaults: true' >"$work/drop.yaml" +printf '%s\n' 'protect-kernel-defaults: false' >"$work/drop.yaml.d/10-off.yaml" +printf '%s\n' 'protect-kernel-defaults: true' >"$work/drop.yaml.d/notes.txt" +printf '%s\n' 'protect-kernel-defaults: true' >"$work/drop.yaml.d/skip.yml" +run_pre_then_server "$work/log-drop-off" EDGELET_KUBE_CONFIG_FILE="$work/drop.yaml" +expect_sysctls "$work/log-drop-off" + +rm -rf "$work/drop.yaml.d" +mkdir -p "$work/drop.yaml.d" +printf '%s\n' 'protect-kernel-defaults: false' >"$work/drop.yaml" +printf '%s\n' 'protect-kernel-defaults: false' >"$work/drop.yaml.d/10-off.yaml" +printf '%s\n' 'protect-kernel-defaults: true' >"$work/drop.yaml.d/20-on.yaml" +run_pre_then_server "$work/log-drop-on" EDGELET_KUBE_CONFIG_FILE="$work/drop.yaml" +expect_untouched "$work/log-drop-on" + +rm -rf "$work/drop.yaml.d" +mkdir -p "$work/drop.yaml.d" +rm -f "$work/drop.yaml" +printf '%s\n' 'protect-kernel-defaults: true' >"$work/drop.yaml.d/10.yaml" +run_pre_then_server "$work/log-drop-only" EDGELET_KUBE_CONFIG_FILE="$work/drop.yaml" +expect_untouched "$work/log-drop-only" + +printf '%s\n' 'protect-kernel-defaults: false' >"$work/false.yaml" +run_pre_then_server "$work/log-env-true" \ + EDGELET_KUBE_CONFIG_FILE="$work/false.yaml" \ + EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS=true +expect_untouched "$work/log-env-true" + +printf '%s\n' 'protect-kernel-defaults: true' >"$work/true.yaml" +run_pre_then_server "$work/log-env-false" \ + EDGELET_KUBE_CONFIG_FILE="$work/true.yaml" \ + EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS=false +expect_sysctls "$work/log-env-false" + +run_pre_then_server "$work/log-env-empty" \ + EDGELET_KUBE_CONFIG_FILE="$work/true.yaml" \ + EDGELET_KUBE_PROTECT_KERNEL_DEFAULTS= +expect_untouched "$work/log-env-empty" + +# A second install replaces the binary and restarts the unit. +# SQLite, the CA, and the encryption file stay. The unit stop signals the +# server process, which stops its containerd child. The shim keeps running. +state=$work/state +run=$work/run +mkdir -p "$state/db" "$state/server/tls" "$state/server/cred" "$run" +printf '%s\n' 'sqlite-ready' >"$state/db/state.db" +printf '%s\n' 'ca-material' >"$state/server/tls/ca.crt" +printf '%s\n' 'serving-material' >"$state/server/tls/serving.crt" +printf '%s\n' 'client-admin-material' >"$state/server/tls/client-admin.crt" +printf '%s\n' 'aescbc-key' >"$state/server/cred/encryption-config.json" +cksum "$state/db/state.db" "$state/server/tls/ca.crt" \ + "$state/server/tls/serving.crt" "$state/server/tls/client-admin.crt" \ + "$state/server/cred/encryption-config.json" >"$work/kept.before" + +cat >"$work/old-server.sh" <<'EOF' +#!/bin/sh +set -eu +run=$1 +echo $$ > "$run/server.pid" +sleep 3600 >/dev/null 2>&1 & +echo $! > "$run/containerd.pid" +child=$! +trap 'kill "$child" 2>/dev/null || true; exit 0' TERM +nohup sleep 3600 >/dev/null 2>&1 & +echo $! > "$run/shim.pid" +while kill -0 "$child" 2>/dev/null; do + sleep 1 +done +EOF +chmod 0755 "$work/old-server.sh" +sh "$work/old-server.sh" "$run" & +echo $! >>"$work/pids" +i=0 +while [ ! -s "$run/shim.pid" ]; do + i=$((i + 1)) + if [ "$i" -gt 50 ]; then + fail "running node did not record its shim" + fi + sleep 0.1 +done +shim=$(cat "$run/shim.pid") +old_containerd=$(cat "$run/containerd.pid") +echo "$shim" >>"$work/pids" +echo "$old_containerd" >>"$work/pids" +kill -0 "$shim" || fail "shim is not running" +kill -0 "$old_containerd" || fail "containerd child is not running" + +cat >"$work/new-bin" <<'EOF' +#!/bin/sh +set -eu +if [ "${1:-}" != "server" ]; then + printf '%s\n' "client" "$@" + exit 0 +fi +state=${EDGELET_KUBE_STATE_DIR:?} +run=${EDGELET_KUBE_RUN_DIR:?} +[ -f "$state/db/state.db" ] +[ -f "$state/server/tls/ca.crt" ] +enc=$state/server/cred/encryption-config.json +if [ -e "$enc" ] && [ ! -f "$enc" ]; then + echo "encryption config is not a file" >&2 + exit 1 +fi +disabled= +if [ -f "$state/config.yaml" ]; then + disabled=$(awk ' + /^disable:[ \t]+[^ \t]/ { print $2 } + /^disable:[ \t]*$/ { on = 1; next } + on && /^[^ \t-]/ { on = 0 } + on && /^[ \t]*-[ \t]*/ { + name = $0 + sub(/^[ \t]*-[ \t]*/, "", name) + print name + } + ' "$state/config.yaml") +fi +{ + echo Ready + for addon in coredns local-path metrics-server traefik cert-manager; do + skip=0 + for name in $disabled; do + if [ "$name" = "$addon" ]; then + skip=1 + fi + done + if [ "$skip" -eq 0 ]; then + echo "$addon" + fi + done +} >"$run/node.status" +echo $$ >"$run/server.pid" +sleep 3600 >/dev/null 2>&1 & +echo $! >"$run/containerd.pid" +child=$! +trap 'kill "$child" 2>/dev/null || true; exit 0' TERM +while kill -0 "$child" 2>/dev/null; do + sleep 1 +done +EOF +chmod 0755 "$work/new-bin" + +cat >"$work/systemctl-upgrade" <> "$work/upgrade-systemctl.log" +if [ "\$1" != "restart" ]; then + exit 0 +fi +mode=\$(awk -F= '/^KillMode=/ { print \$2 }' "$work/units/edgelet-kube.service") +server=\$(cat "$run/server.pid") +if [ "\$mode" = "process" ]; then + kill -TERM "\$server" +else + kill -TERM "\$server" \$(cat "$run/containerd.pid") \$(cat "$run/shim.pid") +fi +i=0 +while kill -0 "\$server" 2>/dev/null; do + i=\$((i + 1)) + if [ "\$i" -gt 50 ]; then + echo "server did not stop" >&2 + exit 1 + fi + sleep 0.1 +done +EDGELET_KUBE_STATE_DIR="$state" EDGELET_KUBE_RUN_DIR="$run" \\ + "$work/bin/edgelet-kube" server >> "$run/server.log" 2>&1 & +echo \$! >> "$work/pids" +EOF +chmod 0755 "$work/systemctl-upgrade" + +wait_status() { + i=0 + while [ ! -s "$run/node.status" ]; do + i=$((i + 1)) + if [ "$i" -gt 50 ]; then + echo "server log:" >&2 + cat "$run/server.log" >&2 || true + fail "node did not report status" + fi + sleep 0.1 + done +} + +: >"$work/upgrade-systemctl.log" +rm -f "$run/node.status" +EDGELET_KUBE_BIN_DIR="$work/bin" \ +EDGELET_KUBE_UNIT_DIR="$work/units" \ +EDGELET_KUBE_LIBEXEC_DIR="$work/libexec" \ +EDGELET_KUBE_SYSTEMCTL="$work/systemctl-upgrade" \ + sh scripts/install.sh --bin-path="$work/new-bin" +cmp -s "$work/new-bin" "$work/bin/edgelet-kube" || fail "upgrade did not replace the binary" +cksum "$state/db/state.db" "$state/server/tls/ca.crt" \ + "$state/server/tls/serving.crt" "$state/server/tls/client-admin.crt" \ + "$state/server/cred/encryption-config.json" >"$work/kept.after" +cmp -s "$work/kept.before" "$work/kept.after" || fail "database, CA, or encryption config changed" +kill -0 "$shim" || fail "unit stop killed the shim" +if kill -0 "$old_containerd" 2>/dev/null; then + fail "containerd child survived the server stop" +fi +printf '%s\n' \ + 'daemon-reload' \ + 'enable edgelet-kube.service' \ + 'restart edgelet-kube.service' >"$work/upgrade-systemctl.want" +cmp -s "$work/upgrade-systemctl.want" "$work/upgrade-systemctl.log" || { + echo "upgrade systemctl log:" >&2 + cat "$work/upgrade-systemctl.log" >&2 + fail "second install did not restart the unit" +} +wait_status +printf '%s\n' Ready coredns local-path metrics-server traefik cert-manager >"$work/ready.want" +cmp -s "$work/ready.want" "$run/node.status" || { + echo "node status:" >&2 + cat "$run/node.status" >&2 + fail "node is not Ready with the default addons" +} + +# A later run still keeps the database and the CA when encryption is off, +# and a disable flag that is already set stays in effect. +rm -f "$state/server/cred/encryption-config.json" +cksum "$state/db/state.db" "$state/server/tls/ca.crt" \ + "$state/server/tls/serving.crt" "$state/server/tls/client-admin.crt" >"$work/kept-plain.before" +printf '%s\n' 'disable:' ' - metrics-server' >"$state/config.yaml" +: >"$work/upgrade-systemctl.log" +rm -f "$run/node.status" +EDGELET_KUBE_BIN_DIR="$work/bin" \ +EDGELET_KUBE_UNIT_DIR="$work/units" \ +EDGELET_KUBE_LIBEXEC_DIR="$work/libexec" \ +EDGELET_KUBE_SYSTEMCTL="$work/systemctl-upgrade" \ + sh scripts/install.sh --bin-path="$work/new-bin" +[ ! -e "$state/server/cred/encryption-config.json" ] || fail "encryption config was created" +cksum "$state/db/state.db" "$state/server/tls/ca.crt" \ + "$state/server/tls/serving.crt" "$state/server/tls/client-admin.crt" >"$work/kept-plain.after" +cmp -s "$work/kept-plain.before" "$work/kept-plain.after" || fail "database or CA changed" +kill -0 "$shim" || fail "unit stop killed the shim" +wait_status +printf '%s\n' Ready coredns local-path traefik cert-manager >"$work/ready-disabled.want" +cmp -s "$work/ready-disabled.want" "$run/node.status" || { + echo "node status:" >&2 + cat "$run/node.status" >&2 + fail "disabled addon was restored" +} + +echo "ok" diff --git a/kube/scripts/pack/main.go b/kube/scripts/pack/main.go new file mode 100644 index 0000000..f73541b --- /dev/null +++ b/kube/scripts/pack/main.go @@ -0,0 +1,55 @@ +// Package main writes the zstd bundle the thin binary embeds. +// The bundle contains the fat runtime and the aux binaries. It contains no OCI image. +package main + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + + "github.com/eclipse-iofog/edgelet-kube/internal/bundle" +) + +func main() { + stage := flag.String("stage", "", "directory whose bin tree is packed") + out := flag.String("out", "", "directory for the zstd bundle") + flag.Parse() + if err := pack(*stage, *out); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "pack: %v\n", err) + os.Exit(1) + } +} + +func pack(stage, out string) error { + if stage == "" || out == "" { + return errors.New("stage and out are required") + } + packed, err := bundle.Pack(stage) + if err != nil { + return err + } + sum := sha256.Sum256(packed) + name := hex.EncodeToString(sum[:]) + ".tar.zst" + if err := os.MkdirAll(out, 0o755); err != nil { + return fmt.Errorf("mkdir bundle dir: %w", err) + } + old, err := filepath.Glob(filepath.Join(out, "*.tar.zst")) + if err != nil { + return fmt.Errorf("list bundles: %w", err) + } + for _, path := range old { + if err := os.Remove(path); err != nil { + return fmt.Errorf("remove %s: %w", path, err) + } + } + dest := filepath.Join(out, name) + if err := os.WriteFile(dest, packed, 0o644); err != nil { + return fmt.Errorf("write bundle: %w", err) + } + fmt.Println(dest) + return nil +} diff --git a/kube/scripts/package-airgap b/kube/scripts/package-airgap new file mode 100755 index 0000000..52af463 --- /dev/null +++ b/kube/scripts/package-airgap @@ -0,0 +1,73 @@ +#!/bin/bash +# Export the pinned image list as edgelet-kube-airgap-images-.tar.zst. +# The archive is published beside the binary. It is not part of the runtime. +set -euo pipefail + +cd "$(dirname "$0")/.." +export GOWORK=off + +arch="${ARCH:-amd64}" +case "$arch" in +amd64) platform=linux/amd64 ;; +arm64) platform=linux/arm64 ;; +arm) platform=linux/arm/v7 ;; +riscv64) platform=linux/riscv64 ;; +*) + echo "package-airgap: unsupported architecture: $arch" >&2 + exit 1 + ;; +esac + +asset="edgelet-kube-airgap-images-${arch}.tar.zst" +out="${OUT:-build/${asset}}" +if [ "$(basename "$out")" != "$asset" ]; then + echo "package-airgap: asset must be ${asset}" >&2 + exit 1 +fi + +out_abs="$out" +case "$out_abs" in +/*) ;; +*) out_abs="$(pwd)/$out_abs" ;; +esac +embed="$(pwd)/cmd/edgelet-kube/embed/" +case "$out_abs" in +"$embed"*) + echo "package-airgap: the archive is published beside the binary" >&2 + exit 1 + ;; +esac + +ctr="${CTR:-ctr}" +images=() +while IFS= read -r line || [ -n "$line" ]; do + [ -z "$line" ] && continue + images+=("$line") +done < <(go run ./scripts/airgap/zstdcmd -images "$arch") +expect=12 +if [ "$arch" = riscv64 ]; then + expect=6 +fi +if [ "${#images[@]}" -ne "$expect" ]; then + echo "package-airgap: the pin list has ${#images[@]} images" >&2 + exit 1 +fi + +mkdir -p "$(dirname "$out")" +"$ctr" namespaces create k8s.io >/dev/null 2>&1 || true +platform_flag="--platform=${platform}" +for image in "${images[@]}"; do + "$ctr" -n k8s.io images pull "$platform_flag" "$image" +done + +tmp="$(mktemp)" +trap 'rm -f "$tmp"' EXIT +"$ctr" -n k8s.io images export "$platform_flag" "$tmp" "${images[@]}" +go run ./scripts/airgap/zstdcmd -in "$tmp" -out "$out" + +listed="$(go run ./scripts/airgap/zstdcmd -list "$out")" +want="$(printf '%s\n' "${images[@]}")" +if [ "$listed" != "$want" ]; then + echo "package-airgap: archive image names do not match the pin list" >&2 + exit 1 +fi diff --git a/kube/scripts/quality-linux.sh b/kube/scripts/quality-linux.sh new file mode 100755 index 0000000..8df88c7 --- /dev/null +++ b/kube/scripts/quality-linux.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# Vet and lint the kube module. +# On macOS the checks run in the Go Linux image. On Linux they run on the host. +set -euo pipefail + +KUBE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +ROOT="$(cd "${KUBE}/.." && pwd)" + +GO_IMAGE="${GO_IMAGE:-golang:1.26.11}" +GOLANGCI_LINT_VERSION="${GOLANGCI_LINT_VERSION:-v2.12.2}" + +run_checks() { + cd "${KUBE}" + export GOWORK=off + local arch ver golangci + arch="$(go env GOARCH)" + ver="${GOLANGCI_LINT_VERSION#v}" + echo "=== quality-linux-kube (linux/${arch}) ===" + go version + go mod download + + echo "=== go vet ===" + go vet ./... + + dest="$(mktemp -d)" + trap 'rm -rf "${dest}"' EXIT + curl -sSfL "https://github.com/golangci/golangci-lint/releases/download/${GOLANGCI_LINT_VERSION}/golangci-lint-${ver}-linux-${arch}.tar.gz" \ + | tar xz -C "${dest}" + golangci="${dest}/golangci-lint-${ver}-linux-${arch}/golangci-lint" + + echo "=== golangci-lint ===" + "${golangci}" run --config .golangci.yaml --timeout=10m0s + echo "quality-linux-kube (linux/${arch}): vet and lint passed" +} + +case "$(uname -s)" in +Darwin) + if [ -z "${GOARCH:-}" ]; then + GOARCH="$(go env GOARCH)" + fi + modcache="${QUALITY_MODCACHE:-${HOME}/.cache/edgelet-kube/mod}" + buildcache="${QUALITY_GOCACHE:-${HOME}/.cache/edgelet-kube/build}" + mkdir -p "${modcache}" "${buildcache}" + docker run --rm --platform "linux/${GOARCH}" \ + -e GOWORK=off \ + -e GOLANGCI_LINT_VERSION="${GOLANGCI_LINT_VERSION}" \ + -v "${ROOT}:/src" -w /src/kube \ + -v "${modcache}:/go/pkg/mod" \ + -v "${buildcache}:/root/.cache/go-build" \ + "${GO_IMAGE}" \ + bash /src/kube/scripts/quality-linux.sh + ;; +Linux) + run_checks + ;; +*) + echo "quality-linux-kube supports macOS and Linux" >&2 + exit 1 + ;; +esac diff --git a/kube/scripts/smoke.sh b/kube/scripts/smoke.sh new file mode 100644 index 0000000..2de7543 --- /dev/null +++ b/kube/scripts/smoke.sh @@ -0,0 +1,128 @@ +#!/bin/bash +# Run the thin binary on linux/amd64: server exits 0, port 6443 stays closed, +# and kubectl, ctr, and crictl reach the fat runtime. +set -euo pipefail + +cd "$(dirname "$0")/.." + +if [ "$(uname -s)" != "Linux" ] || [ "$(uname -m)" != "x86_64" ]; then + echo "this check runs on linux/amd64" >&2 + exit 1 +fi + +thin="build/edgelet-kube" +fat="build/edgelet-kube-server" +if [ ! -x "$thin" ] || [ ! -x "$fat" ]; then + echo "run scripts/build.sh first" >&2 + exit 1 +fi + +go version -m "$fat" | grep -q 'CGO_ENABLED=1' +go version -m "$thin" | grep -q 'CGO_ENABLED=0' + +listen_6443() { + awk 'NR > 1 && $4 == "0A" && $2 ~ /:192B$/' /proc/net/tcp /proc/net/tcp6 2>/dev/null || true +} + +data=$(mktemp -d) +trap 'rm -rf "$data"' EXIT + +out="$data/server.out" +if ! timeout 15s "$thin" server --data-dir "$data/work" >"$out"; then + echo "server failed" >&2 + cat "$out" >&2 + exit 1 +fi +grep -q 'edgelet-kube runtime server' "$out" +if listen_6443 | grep -q .; then + echo "port 6443 is listening" >&2 + listen_6443 >&2 + exit 1 +fi + +mapfile -t extracted < <(find "$data/work/data" -type f -name edgelet-kube) +if [ "${#extracted[@]}" -ne 1 ]; then + echo "expected one extracted runtime, found ${#extracted[@]}" >&2 + exit 1 +fi +cmp -s "$fat" "${extracted[0]}" +[ -x "${extracted[0]}" ] + +bindir=$(dirname "${extracted[0]}") +root=$(dirname "$bindir") +echo "bundle members:" +( + cd "$root" + find . -print | sed 's|^\./||' | LC_ALL=C sort +) +require_file() { + if [ ! -f "$1" ] || [ -L "$1" ]; then + echo "missing $1" >&2 + exit 1 + fi +} +require_link() { + if [ ! -L "$1" ]; then + echo "missing link $1" >&2 + exit 1 + fi + got=$(readlink "$1") + if [ "$got" != "$2" ]; then + echo "$1 -> $got, want $2" >&2 + exit 1 + fi +} +require_file "$bindir/edgelet-kube" +require_file "$bindir/containerd-shim-runc-v2" +require_file "$bindir/crun" +require_file "$bindir/cni" +require_file "$bindir/ip" +require_file "$bindir/busybox" +require_file "$bindir/aux/xtables-nft-multi" +for name in iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore; do + require_link "$bindir/aux/$name" xtables-nft-multi +done +require_link "$bindir/modprobe" busybox +for name in bridge host-local loopback portmap; do + require_link "$bindir/$name" cni +done +mapfile -t top < <(find "$bindir" -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort) +want_top="aux bridge busybox cni containerd-shim-runc-v2 crun edgelet-kube host-local ip loopback modprobe portmap" +got_top="${top[*]}" +if [ "$got_top" != "$want_top" ]; then + echo "bin members: $got_top" >&2 + exit 1 +fi +if find "$root" \( -name 'pause.tar' -o -name 'pause.tar.gz' -o -name 'oci-layout' -o -name 'index.json' -o -name 'manifest.json' -o -path '*/images/*' -o -path '*/blobs/*' -o -name 'flannel' \) | grep -q .; then + echo "bundle contains an OCI image or flannel" >&2 + find "$root" \( -name 'pause.tar' -o -name 'pause.tar.gz' -o -name 'oci-layout' -o -name 'index.json' -o -name 'manifest.json' -o -path '*/images/*' -o -path '*/blobs/*' -o -name 'flannel' \) >&2 + exit 1 +fi + +k8s_version=$(awk '$1 == "kubernetes" { print $2; exit }' scripts/airgap/pins.txt) +kubectl_link="$data/kubectl" +ln -s "$(pwd)/$thin" "$kubectl_link" +got=$(timeout 30s "$kubectl_link" --data-dir "$data/work" version --client) +printf '%s\n' "$got" | grep -q "$k8s_version" +sub=$(timeout 30s "$thin" kubectl version --client --data-dir "$data/work") +printf '%s\n' "$sub" | grep -q "$k8s_version" + +for name in ctr crictl; do + link="$data/$name" + ln -s "$(pwd)/$thin" "$link" + got=$(timeout 15s "$link" --data-dir "$data/work") + printf '%s\n' "$got" | grep -q "edgelet-kube runtime $name" + sub=$(timeout 15s "$thin" "$name" --data-dir "$data/work") + printf '%s\n' "$sub" | grep -q "edgelet-kube runtime $name" +done + +empty="$data/empty" +mkdir -p "$empty" +if "$thin" --data-dir "$empty" >"$empty/out" 2>"$empty/err"; then + echo "missing command should fail" >&2 + exit 1 +fi +if [ -d "$empty/data" ]; then + echo "a usage error extracted a bundle" >&2 + exit 1 +fi diff --git a/licensegen/go.mod b/licensegen/go.mod index bc87c0c..74b8dcd 100644 --- a/licensegen/go.mod +++ b/licensegen/go.mod @@ -1,3 +1,3 @@ module github.com/eclipse-iofog/edgelet/licensegen -go 1.26.10 +go 1.26.11 diff --git a/licensegen/pins_test.go b/licensegen/pins_test.go index cbda27c..bbbb0d6 100644 --- a/licensegen/pins_test.go +++ b/licensegen/pins_test.go @@ -12,7 +12,7 @@ func TestParsePins(t *testing.T) { if err != nil { t.Fatal(err) } - if pins.Go != "1.26.10" || pins.Crun != "1.28" || pins.CNI != "v1.9.1-k3s1" { + if pins.Go != "1.26.11" || pins.Crun != "1.30.1" || pins.CNI != "v1.9.1-k3s1" { t.Fatalf("unexpected pins: %+v", pins) } if pins.PauseRepo != "portainer/pause" { diff --git a/sbom.cdx.json b/sbom.cdx.json index 8c80e84..ed2fb81 100644 --- a/sbom.cdx.json +++ b/sbom.cdx.json @@ -2,7 +2,7 @@ "bomFormat": "CycloneDX", "components": [ { - "bom-ref": "pkg:generic/go@1.26.10", + "bom-ref": "pkg:generic/go@1.26.11", "description": "Toolchain pin from scripts/version.sh. The SBOM does not record the patch level of the machine that generated it.", "licenses": [ { @@ -10,18 +10,18 @@ } ], "name": "Go", - "purl": "pkg:generic/go@1.26.10", + "purl": "pkg:generic/go@1.26.11", "scope": "required", "type": "library", - "version": "1.26.10" + "version": "1.26.11" }, { - "bom-ref": "pkg:generic/k3s-root@v0.15.0?arch=amd64", + "bom-ref": "pkg:generic/k3s-root@v0.15.4?arch=amd64", "description": "Upstream tarball pin. The embed stages bin/busybox, bin/ip, and bin/aux from this archive. The hash is of the tarball, not of the staged subset. The k3s-root source repository at this tag is Apache-2.0 (https://github.com/k3s-io/k3s-root). That license covers the build scripts and Buildroot config. It does not license the programs inside the tarball. Those programs are the contained GPL components.", "hashes": [ { "alg": "SHA-256", - "content": "20066815d9941185fce3934cc3bae2fa3e2dbb46ca7e63462efb2ea59f1b15c4" + "content": "658581f9dba924b24dcca14fcbb7237d69c9d3cd56995558d56efcd522263ea9" } ], "licenses": [ @@ -41,21 +41,21 @@ }, { "name": "edgelet:download", - "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.0/k3s-root-amd64.tar" + "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.4/k3s-root-amd64.tar" } ], - "purl": "pkg:generic/k3s-root@v0.15.0?arch=amd64", + "purl": "pkg:generic/k3s-root@v0.15.4?arch=amd64", "scope": "required", "type": "file", - "version": "v0.15.0" + "version": "v0.15.4" }, { - "bom-ref": "pkg:generic/k3s-root@v0.15.0?arch=arm", + "bom-ref": "pkg:generic/k3s-root@v0.15.4?arch=arm", "description": "Upstream tarball pin. The embed stages bin/busybox, bin/ip, and bin/aux from this archive. The hash is of the tarball, not of the staged subset. The k3s-root source repository at this tag is Apache-2.0 (https://github.com/k3s-io/k3s-root). That license covers the build scripts and Buildroot config. It does not license the programs inside the tarball. Those programs are the contained GPL components.", "hashes": [ { "alg": "SHA-256", - "content": "2e43dac7750da52a756a9d4e8598d6e89937d565582660b26ca124bd9c8dbfaa" + "content": "2a09ec8b4ab7a7fd41f9caa0b04a15cc631c2682f27f6f3605a77684717f3ac4" } ], "licenses": [ @@ -75,21 +75,21 @@ }, { "name": "edgelet:download", - "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.0/k3s-root-arm.tar" + "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.4/k3s-root-arm.tar" } ], - "purl": "pkg:generic/k3s-root@v0.15.0?arch=arm", + "purl": "pkg:generic/k3s-root@v0.15.4?arch=arm", "scope": "required", "type": "file", - "version": "v0.15.0" + "version": "v0.15.4" }, { - "bom-ref": "pkg:generic/k3s-root@v0.15.0?arch=arm64", + "bom-ref": "pkg:generic/k3s-root@v0.15.4?arch=arm64", "description": "Upstream tarball pin. The embed stages bin/busybox, bin/ip, and bin/aux from this archive. The hash is of the tarball, not of the staged subset. The k3s-root source repository at this tag is Apache-2.0 (https://github.com/k3s-io/k3s-root). That license covers the build scripts and Buildroot config. It does not license the programs inside the tarball. Those programs are the contained GPL components.", "hashes": [ { "alg": "SHA-256", - "content": "4bdfc715dc8b5e2c4956f8686b895a56386f4cc6468215dcd22130a680650577" + "content": "80b65fd619c8534a5cfe09310217a588e7cbb43f2f95b5f3dedcf2b39495dafc" } ], "licenses": [ @@ -109,21 +109,21 @@ }, { "name": "edgelet:download", - "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.0/k3s-root-arm64.tar" + "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.4/k3s-root-arm64.tar" } ], - "purl": "pkg:generic/k3s-root@v0.15.0?arch=arm64", + "purl": "pkg:generic/k3s-root@v0.15.4?arch=arm64", "scope": "required", "type": "file", - "version": "v0.15.0" + "version": "v0.15.4" }, { - "bom-ref": "pkg:generic/k3s-root@v0.15.0?arch=riscv64", + "bom-ref": "pkg:generic/k3s-root@v0.15.4?arch=riscv64", "description": "Upstream tarball pin. The embed stages bin/busybox, bin/ip, and bin/aux from this archive. The hash is of the tarball, not of the staged subset. The k3s-root source repository at this tag is Apache-2.0 (https://github.com/k3s-io/k3s-root). That license covers the build scripts and Buildroot config. It does not license the programs inside the tarball. Those programs are the contained GPL components.", "hashes": [ { "alg": "SHA-256", - "content": "0e79998acaa156059ba1ff676a4e5f290069e25f799de43ee016a0e780f9d4d3" + "content": "fd5e0b38c0e13fba14ff45df2c0cb89fc8ae8b1c6f5a7480fd24f1d2b644b29e" } ], "licenses": [ @@ -143,13 +143,13 @@ }, { "name": "edgelet:download", - "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.0/k3s-root-riscv64.tar" + "value": "https://github.com/k3s-io/k3s-root/releases/download/v0.15.4/k3s-root-riscv64.tar" } ], - "purl": "pkg:generic/k3s-root@v0.15.0?arch=riscv64", + "purl": "pkg:generic/k3s-root@v0.15.4?arch=riscv64", "scope": "required", "type": "file", - "version": "v0.15.0" + "version": "v0.15.4" }, { "bom-ref": "pkg:generic/sqlite@3.53.4", @@ -176,7 +176,7 @@ "version": "3.53.4" }, { - "bom-ref": "pkg:github/containers/crun@1.28", + "bom-ref": "pkg:github/containers/crun@1.30.1", "description": "Source of the static crun ELF in the embed bundle.", "licenses": [ { @@ -191,13 +191,13 @@ }, { "name": "edgelet:source", - "value": "https://github.com/containers/crun/tree/1.28" + "value": "https://github.com/containers/crun/tree/1.30.1" } ], - "purl": "pkg:github/containers/crun@1.28", + "purl": "pkg:github/containers/crun@1.30.1", "scope": "required", "type": "application", - "version": "1.28" + "version": "1.30.1" }, { "bom-ref": "pkg:github/rancher/plugins@v1.9.1-k3s1", @@ -695,7 +695,7 @@ "version": "v0.1.0" }, { - "bom-ref": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.4", + "bom-ref": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.5", "licenses": [ { "expression": "Apache-2.0" @@ -708,10 +708,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.4", + "purl": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.5", "scope": "required", "type": "library", - "version": "v1.0.0-rc.4" + "version": "v1.0.0-rc.5" }, { "bom-ref": "pkg:golang/github.com/containerd/plugin@v1.1.0", @@ -1113,7 +1113,7 @@ "version": "v1.10.1" }, { - "bom-ref": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.0", + "bom-ref": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.1", "licenses": [ { "expression": "MIT" @@ -1126,10 +1126,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.0", + "purl": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.1", "scope": "required", "type": "library", - "version": "v2.9.0" + "version": "v2.9.1" }, { "bom-ref": "pkg:golang/github.com/go-jose/go-jose/v4@v4.1.6", @@ -1360,7 +1360,7 @@ "version": "v0.12.0" }, { - "bom-ref": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2", + "bom-ref": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1", "licenses": [ { "expression": "Apache-2.0" @@ -1377,13 +1377,13 @@ "value": "github.com/containerd/containerd/v2" } ], - "purl": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2", + "purl": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1", "scope": "required", "type": "library", - "version": "v2.3.2-k3s2" + "version": "v2.3.7-k3s1" }, { - "bom-ref": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2#cmd/containerd-shim-runc-v2", + "bom-ref": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1#cmd/containerd-shim-runc-v2", "description": "Separate ELF built from the same containerd module that is linked into the fat runtime. It is not a second copy of that module's version.", "licenses": [ { @@ -1397,13 +1397,13 @@ "value": "linux" } ], - "purl": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2#cmd/containerd-shim-runc-v2", + "purl": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1#cmd/containerd-shim-runc-v2", "scope": "required", "type": "application", - "version": "v2.3.2-k3s2" + "version": "v2.3.7-k3s1" }, { - "bom-ref": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.36.2-k3s2", + "bom-ref": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.37.2-k3s1", "licenses": [ { "expression": "Apache-2.0" @@ -1420,10 +1420,10 @@ "value": "k8s.io/cri-api" } ], - "purl": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.36.2-k3s2", + "purl": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.37.2-k3s1", "scope": "required", "type": "library", - "version": "v1.36.2-k3s2" + "version": "v1.37.2-k3s1" }, { "bom-ref": "pkg:golang/github.com/klauspost/compress@v1.20.3", @@ -1977,7 +1977,7 @@ "version": "v1.9.5" }, { - "bom-ref": "pkg:golang/github.com/prometheus/client_golang@v1.23.2", + "bom-ref": "pkg:golang/github.com/prometheus/client_golang@v1.24.0", "licenses": [ { "expression": "Apache-2.0" @@ -1990,10 +1990,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/github.com/prometheus/client_golang@v1.23.2", + "purl": "pkg:golang/github.com/prometheus/client_golang@v1.24.0", "scope": "required", "type": "library", - "version": "v1.23.2" + "version": "v1.24.0" }, { "bom-ref": "pkg:golang/github.com/prometheus/client_model@v0.6.2", @@ -2015,7 +2015,7 @@ "version": "v0.6.2" }, { - "bom-ref": "pkg:golang/github.com/prometheus/common@v0.67.5", + "bom-ref": "pkg:golang/github.com/prometheus/common@v0.70.0", "licenses": [ { "expression": "Apache-2.0" @@ -2028,13 +2028,13 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/github.com/prometheus/common@v0.67.5", + "purl": "pkg:golang/github.com/prometheus/common@v0.70.0", "scope": "required", "type": "library", - "version": "v0.67.5" + "version": "v0.70.0" }, { - "bom-ref": "pkg:golang/github.com/prometheus/procfs@v0.19.2", + "bom-ref": "pkg:golang/github.com/prometheus/procfs@v0.21.1", "licenses": [ { "expression": "Apache-2.0" @@ -2047,10 +2047,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/github.com/prometheus/procfs@v0.19.2", + "purl": "pkg:golang/github.com/prometheus/procfs@v0.21.1", "scope": "required", "type": "library", - "version": "v0.19.2" + "version": "v0.21.1" }, { "bom-ref": "pkg:golang/github.com/remyoudompheng/bigfft@v0.0.0-20230129092748-24d4a6f8daec", @@ -2566,7 +2566,7 @@ "version": "v1.44.0" }, { - "bom-ref": "pkg:golang/go.yaml.in/yaml/v2@v2.4.3", + "bom-ref": "pkg:golang/go.yaml.in/yaml/v2@v2.4.4", "licenses": [ { "expression": "Apache-2.0" @@ -2579,10 +2579,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/go.yaml.in/yaml/v2@v2.4.3", + "purl": "pkg:golang/go.yaml.in/yaml/v2@v2.4.4", "scope": "required", "type": "library", - "version": "v2.4.3" + "version": "v2.4.4" }, { "bom-ref": "pkg:golang/go.yaml.in/yaml/v3@v3.0.5", @@ -2870,7 +2870,7 @@ "version": "v3.0.1" }, { - "bom-ref": "pkg:golang/k8s.io/apimachinery@v0.36.2", + "bom-ref": "pkg:golang/k8s.io/apimachinery@v0.37.1", "licenses": [ { "expression": "Apache-2.0" @@ -2883,13 +2883,13 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/k8s.io/apimachinery@v0.36.2", + "purl": "pkg:golang/k8s.io/apimachinery@v0.37.1", "scope": "required", "type": "library", - "version": "v0.36.2" + "version": "v0.37.1" }, { - "bom-ref": "pkg:golang/k8s.io/client-go@v0.36.2", + "bom-ref": "pkg:golang/k8s.io/client-go@v0.37.1", "licenses": [ { "expression": "Apache-2.0" @@ -2902,13 +2902,13 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/k8s.io/client-go@v0.36.2", + "purl": "pkg:golang/k8s.io/client-go@v0.37.1", "scope": "required", "type": "library", - "version": "v0.36.2" + "version": "v0.37.1" }, { - "bom-ref": "pkg:golang/k8s.io/cri-streaming@v0.36.2", + "bom-ref": "pkg:golang/k8s.io/cri-streaming@v0.37.1", "licenses": [ { "expression": "Apache-2.0" @@ -2921,10 +2921,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/k8s.io/cri-streaming@v0.36.2", + "purl": "pkg:golang/k8s.io/cri-streaming@v0.37.1", "scope": "required", "type": "library", - "version": "v0.36.2" + "version": "v0.37.1" }, { "bom-ref": "pkg:golang/k8s.io/klog/v2@v2.140.0", @@ -2946,7 +2946,7 @@ "version": "v2.140.0" }, { - "bom-ref": "pkg:golang/k8s.io/streaming@v0.36.2", + "bom-ref": "pkg:golang/k8s.io/streaming@v0.37.1", "licenses": [ { "expression": "Apache-2.0" @@ -2959,13 +2959,13 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/k8s.io/streaming@v0.36.2", + "purl": "pkg:golang/k8s.io/streaming@v0.37.1", "scope": "required", "type": "library", - "version": "v0.36.2" + "version": "v0.37.1" }, { - "bom-ref": "pkg:golang/k8s.io/utils@v0.0.0-20260319190234-28399d86e0b5", + "bom-ref": "pkg:golang/k8s.io/utils@v0.0.0-20260626114624-be93311217bd", "licenses": [ { "expression": "Apache-2.0" @@ -2978,10 +2978,10 @@ "value": "linux-fat" } ], - "purl": "pkg:golang/k8s.io/utils@v0.0.0-20260319190234-28399d86e0b5", + "purl": "pkg:golang/k8s.io/utils@v0.0.0-20260626114624-be93311217bd", "scope": "required", "type": "library", - "version": "v0.0.0-20260319190234-28399d86e0b5" + "version": "v0.0.0-20260626114624-be93311217bd" }, { "bom-ref": "pkg:golang/modernc.org/libc@v1.77.1", @@ -3184,13 +3184,13 @@ "dependencies": [ { "dependsOn": [ - "pkg:generic/go@1.26.10", - "pkg:generic/k3s-root@v0.15.0?arch=amd64", - "pkg:generic/k3s-root@v0.15.0?arch=arm", - "pkg:generic/k3s-root@v0.15.0?arch=arm64", - "pkg:generic/k3s-root@v0.15.0?arch=riscv64", + "pkg:generic/go@1.26.11", + "pkg:generic/k3s-root@v0.15.4?arch=amd64", + "pkg:generic/k3s-root@v0.15.4?arch=arm", + "pkg:generic/k3s-root@v0.15.4?arch=arm64", + "pkg:generic/k3s-root@v0.15.4?arch=riscv64", "pkg:generic/sqlite@3.53.4", - "pkg:github/containers/crun@1.28", + "pkg:github/containers/crun@1.30.1", "pkg:github/rancher/plugins@v1.9.1-k3s1", "pkg:golang/dario.cat/mergo@v1.0.2", "pkg:golang/github.com/Microsoft/go-winio@v0.6.3-0.20251027160822-ad3df93bed29", @@ -3217,7 +3217,7 @@ "pkg:golang/github.com/containerd/log@v0.1.0", "pkg:golang/github.com/containerd/nri@v0.12.0", "pkg:golang/github.com/containerd/otelttrpc@v0.1.0", - "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.4", + "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.5", "pkg:golang/github.com/containerd/plugin@v1.1.0", "pkg:golang/github.com/containerd/ttrpc@v1.2.8", "pkg:golang/github.com/containerd/typeurl/v2@v2.3.0", @@ -3239,7 +3239,7 @@ "pkg:golang/github.com/fatih/color@v1.7.0", "pkg:golang/github.com/felixge/httpsnoop@v1.1.0", "pkg:golang/github.com/fsnotify/fsnotify@v1.10.1", - "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.0", + "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.1", "pkg:golang/github.com/go-jose/go-jose/v4@v4.1.6", "pkg:golang/github.com/go-logr/logr@v1.4.3", "pkg:golang/github.com/go-logr/stdr@v1.2.2", @@ -3252,9 +3252,9 @@ "pkg:golang/github.com/grpc-ecosystem/go-grpc-middleware/v2@v2.1.0", "pkg:golang/github.com/inconshreveable/mousetrap@v1.1.0", "pkg:golang/github.com/intel/goresctrl@v0.12.0", - "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2", - "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2#cmd/containerd-shim-runc-v2", - "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.36.2-k3s2", + "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1", + "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1#cmd/containerd-shim-runc-v2", + "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.37.2-k3s1", "pkg:golang/github.com/klauspost/compress@v1.20.3", "pkg:golang/github.com/knqyf263/go-plugin@v0.9.0", "pkg:golang/github.com/mattn/go-colorable@v0.1.2", @@ -3284,10 +3284,10 @@ "pkg:golang/github.com/opencontainers/selinux@v1.13.1", "pkg:golang/github.com/pelletier/go-toml/v2@v2.3.0", "pkg:golang/github.com/pelletier/go-toml@v1.9.5", - "pkg:golang/github.com/prometheus/client_golang@v1.23.2", + "pkg:golang/github.com/prometheus/client_golang@v1.24.0", "pkg:golang/github.com/prometheus/client_model@v0.6.2", - "pkg:golang/github.com/prometheus/common@v0.67.5", - "pkg:golang/github.com/prometheus/procfs@v0.19.2", + "pkg:golang/github.com/prometheus/common@v0.70.0", + "pkg:golang/github.com/prometheus/procfs@v0.21.1", "pkg:golang/github.com/remyoudompheng/bigfft@v0.0.0-20230129092748-24d4a6f8daec", "pkg:golang/github.com/russross/blackfriday/v2@v2.1.0", "pkg:golang/github.com/shirou/gopsutil/v4@v4.26.9", @@ -3315,7 +3315,7 @@ "pkg:golang/go.opentelemetry.io/otel/metric@v1.44.0", "pkg:golang/go.opentelemetry.io/otel/trace@v1.44.0", "pkg:golang/go.opentelemetry.io/otel@v1.44.0", - "pkg:golang/go.yaml.in/yaml/v2@v2.4.3", + "pkg:golang/go.yaml.in/yaml/v2@v2.4.4", "pkg:golang/go.yaml.in/yaml/v3@v3.0.5", "pkg:golang/golang.org/x/crypto@v0.58.0", "pkg:golang/golang.org/x/mod@v0.41.0", @@ -3331,12 +3331,12 @@ "pkg:golang/gopkg.in/inf.v0@v0.9.1", "pkg:golang/gopkg.in/tomb.v1@v1.0.0-20141024135613-dd632973f1e7", "pkg:golang/gopkg.in/yaml.v3@v3.0.1", - "pkg:golang/k8s.io/apimachinery@v0.36.2", - "pkg:golang/k8s.io/client-go@v0.36.2", - "pkg:golang/k8s.io/cri-streaming@v0.36.2", + "pkg:golang/k8s.io/apimachinery@v0.37.1", + "pkg:golang/k8s.io/client-go@v0.37.1", + "pkg:golang/k8s.io/cri-streaming@v0.37.1", "pkg:golang/k8s.io/klog/v2@v2.140.0", - "pkg:golang/k8s.io/streaming@v0.36.2", - "pkg:golang/k8s.io/utils@v0.0.0-20260319190234-28399d86e0b5", + "pkg:golang/k8s.io/streaming@v0.37.1", + "pkg:golang/k8s.io/utils@v0.0.0-20260626114624-be93311217bd", "pkg:golang/modernc.org/libc@v1.77.1", "pkg:golang/modernc.org/mathutil@v1.7.1", "pkg:golang/modernc.org/memory@v1.12.1", @@ -3383,7 +3383,7 @@ ] } }, - "serialNumber": "urn:uuid:73a2cbb3-2961-5734-9620-d80f14ab9d1b", + "serialNumber": "urn:uuid:72f96428-2c3c-5986-905e-c0f31c0140b7", "specVersion": "1.6", "version": 1 } diff --git a/sbom.spdx.json b/sbom.spdx.json index bda2121..69a6656 100644 --- a/sbom.spdx.json +++ b/sbom.spdx.json @@ -7,7 +7,7 @@ ] }, "dataLicense": "CC0-1.0", - "documentNamespace": "https://github.com/eclipse-iofog/edgelet/sbom/136fa4b7e6415494518fcfdceaa54a263572f08cbb0bba9f53bc86d0260ff4c1", + "documentNamespace": "https://github.com/eclipse-iofog/edgelet/sbom/eee923aa00be1eda672577f2455f39545c33d9e70cd6159775fa5ad0efc96850", "extractedLicensingInfos": [ { "extractedText": "SQLite Is Public Domain\n\nAll of the code and documentation in SQLite has been dedicated to the public\ndomain by the authors. All code authors, and representatives of the companies\nthey work for, have signed affidavits dedicating their contributions to the\npublic domain and originals of those signed affidavits are stored in a firesafe\nat the main offices of Hwaci. Anyone is free to copy, modify, publish, use,\ncompile, sell, or distribute the original SQLite code, either in source code\nform or as a compiled binary, for any purpose, commercial or non-commercial,\nand by any means.\n\nThe previous paragraph applies to the deliverable code and documentation in\nSQLite - those parts of the SQLite library that you actually bundle and ship\nwith a larger application. Some scripts used as part of the build process (for\nexample the \"configure\" scripts generated by autoconf) might fall under other\nopen-source licenses. Nothing from these build scripts ever reaches the final\ndeliverable SQLite library, however, and so the licenses associated with those\nscripts should not be a factor in assessing your rights to copy and use the\nSQLite library.\n\nAll of the deliverable code in SQLite has been written from scratch. No code\nhas been taken from other projects or from the open internet. Every line of\ncode can be traced back to its original author, and all of those authors have\npublic domain dedications on file. So the SQLite code base is clean and is\nuncontaminated with licensed code from other projects.\n", @@ -35,14 +35,14 @@ "versionInfo": "NOASSERTION" }, { - "SPDXID": "SPDXRef-pkg-generic-go-1.26.10", + "SPDXID": "SPDXRef-pkg-generic-go-1.26.11", "copyrightText": "NOASSERTION", "description": "Toolchain pin from scripts/version.sh. The SBOM does not record the patch level of the machine that generated it.", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:generic/go@1.26.10", + "referenceLocator": "pkg:generic/go@1.26.11", "referenceType": "purl" } ], @@ -50,14 +50,14 @@ "licenseConcluded": "BSD-3-Clause", "licenseDeclared": "BSD-3-Clause", "name": "Go", - "versionInfo": "1.26.10" + "versionInfo": "1.26.11" }, { - "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-amd64", + "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-amd64", "checksums": [ { "algorithm": "SHA-256", - "checksumValue": "20066815d9941185fce3934cc3bae2fa3e2dbb46ca7e63462efb2ea59f1b15c4" + "checksumValue": "658581f9dba924b24dcca14fcbb7237d69c9d3cd56995558d56efcd522263ea9" } ], "copyrightText": "NOASSERTION", @@ -66,7 +66,7 @@ "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:generic/k3s-root@v0.15.0?arch=amd64", + "referenceLocator": "pkg:generic/k3s-root@v0.15.4?arch=amd64", "referenceType": "purl" } ], @@ -74,14 +74,14 @@ "licenseConcluded": "NOASSERTION", "licenseDeclared": "NOASSERTION", "name": "k3s-root (amd64)", - "versionInfo": "v0.15.0" + "versionInfo": "v0.15.4" }, { - "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-arm", + "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-arm", "checksums": [ { "algorithm": "SHA-256", - "checksumValue": "2e43dac7750da52a756a9d4e8598d6e89937d565582660b26ca124bd9c8dbfaa" + "checksumValue": "2a09ec8b4ab7a7fd41f9caa0b04a15cc631c2682f27f6f3605a77684717f3ac4" } ], "copyrightText": "NOASSERTION", @@ -90,7 +90,7 @@ "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:generic/k3s-root@v0.15.0?arch=arm", + "referenceLocator": "pkg:generic/k3s-root@v0.15.4?arch=arm", "referenceType": "purl" } ], @@ -98,14 +98,14 @@ "licenseConcluded": "NOASSERTION", "licenseDeclared": "NOASSERTION", "name": "k3s-root (arm)", - "versionInfo": "v0.15.0" + "versionInfo": "v0.15.4" }, { - "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-arm64", + "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-arm64", "checksums": [ { "algorithm": "SHA-256", - "checksumValue": "4bdfc715dc8b5e2c4956f8686b895a56386f4cc6468215dcd22130a680650577" + "checksumValue": "80b65fd619c8534a5cfe09310217a588e7cbb43f2f95b5f3dedcf2b39495dafc" } ], "copyrightText": "NOASSERTION", @@ -114,7 +114,7 @@ "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:generic/k3s-root@v0.15.0?arch=arm64", + "referenceLocator": "pkg:generic/k3s-root@v0.15.4?arch=arm64", "referenceType": "purl" } ], @@ -122,14 +122,14 @@ "licenseConcluded": "NOASSERTION", "licenseDeclared": "NOASSERTION", "name": "k3s-root (arm64)", - "versionInfo": "v0.15.0" + "versionInfo": "v0.15.4" }, { - "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-riscv64", + "SPDXID": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-riscv64", "checksums": [ { "algorithm": "SHA-256", - "checksumValue": "0e79998acaa156059ba1ff676a4e5f290069e25f799de43ee016a0e780f9d4d3" + "checksumValue": "fd5e0b38c0e13fba14ff45df2c0cb89fc8ae8b1c6f5a7480fd24f1d2b644b29e" } ], "copyrightText": "NOASSERTION", @@ -138,7 +138,7 @@ "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:generic/k3s-root@v0.15.0?arch=riscv64", + "referenceLocator": "pkg:generic/k3s-root@v0.15.4?arch=riscv64", "referenceType": "purl" } ], @@ -146,7 +146,7 @@ "licenseConcluded": "NOASSERTION", "licenseDeclared": "NOASSERTION", "name": "k3s-root (riscv64)", - "versionInfo": "v0.15.0" + "versionInfo": "v0.15.4" }, { "SPDXID": "SPDXRef-pkg-generic-sqlite-3.53.4", @@ -167,14 +167,14 @@ "versionInfo": "3.53.4" }, { - "SPDXID": "SPDXRef-pkg-github-containers-crun-1.28", + "SPDXID": "SPDXRef-pkg-github-containers-crun-1.30.1", "copyrightText": "NOASSERTION", "description": "Source of the static crun ELF in the embed bundle.", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:github/containers/crun@1.28", + "referenceLocator": "pkg:github/containers/crun@1.30.1", "referenceType": "purl" } ], @@ -182,7 +182,7 @@ "licenseConcluded": "GPL-2.0-or-later", "licenseDeclared": "GPL-2.0-or-later", "name": "crun", - "versionInfo": "1.28" + "versionInfo": "1.30.1" }, { "SPDXID": "SPDXRef-pkg-github-rancher-plugins-v1.9.1-k3s1", @@ -628,13 +628,13 @@ "versionInfo": "v0.1.0" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-containerd-platforms-v1.0.0-rc.4", + "SPDXID": "SPDXRef-pkg-golang-github.com-containerd-platforms-v1.0.0-rc.5", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.4", + "referenceLocator": "pkg:golang/github.com/containerd/platforms@v1.0.0-rc.5", "referenceType": "purl" } ], @@ -642,7 +642,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/containerd/platforms", - "versionInfo": "v1.0.0-rc.4" + "versionInfo": "v1.0.0-rc.5" }, { "SPDXID": "SPDXRef-pkg-golang-github.com-containerd-plugin-v1.1.0", @@ -1002,13 +1002,13 @@ "versionInfo": "v1.10.1" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-fxamacker-cbor-v2-v2.9.0", + "SPDXID": "SPDXRef-pkg-golang-github.com-fxamacker-cbor-v2-v2.9.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.0", + "referenceLocator": "pkg:golang/github.com/fxamacker/cbor/v2@v2.9.1", "referenceType": "purl" } ], @@ -1016,7 +1016,7 @@ "licenseConcluded": "MIT", "licenseDeclared": "MIT", "name": "github.com/fxamacker/cbor/v2", - "versionInfo": "v2.9.0" + "versionInfo": "v2.9.1" }, { "SPDXID": "SPDXRef-pkg-golang-github.com-go-jose-go-jose-v4-v4.1.6", @@ -1223,13 +1223,13 @@ "versionInfo": "v0.12.0" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.2-k3s2", + "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.7-k3s1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2", + "referenceLocator": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1", "referenceType": "purl" } ], @@ -1237,17 +1237,17 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/k3s-io/containerd/v2", - "versionInfo": "v2.3.2-k3s2" + "versionInfo": "v2.3.7-k3s1" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.2-k3s2-cmd-containerd-shim-runc-v2", + "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.7-k3s1-cmd-containerd-shim-runc-v2", "copyrightText": "NOASSERTION", "description": "Separate ELF built from the same containerd module that is linked into the fat runtime. It is not a second copy of that module's version.", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.2-k3s2#cmd/containerd-shim-runc-v2", + "referenceLocator": "pkg:golang/github.com/k3s-io/containerd/v2@v2.3.7-k3s1#cmd/containerd-shim-runc-v2", "referenceType": "purl" } ], @@ -1255,16 +1255,16 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "containerd-shim-runc-v2", - "versionInfo": "v2.3.2-k3s2" + "versionInfo": "v2.3.7-k3s1" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-kubernetes-staging-src-k8s.io-cri-api-v1.36.2-k3s2", + "SPDXID": "SPDXRef-pkg-golang-github.com-k3s-io-kubernetes-staging-src-k8s.io-cri-api-v1.37.2-k3s1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.36.2-k3s2", + "referenceLocator": "pkg:golang/github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api@v1.37.2-k3s1", "referenceType": "purl" } ], @@ -1272,7 +1272,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/k3s-io/kubernetes/staging/src/k8s.io/cri-api", - "versionInfo": "v1.36.2-k3s2" + "versionInfo": "v1.37.2-k3s1" }, { "SPDXID": "SPDXRef-pkg-golang-github.com-klauspost-compress-v1.20.3", @@ -1768,13 +1768,13 @@ "versionInfo": "v1.9.5" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-client-golang-v1.23.2", + "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-client-golang-v1.24.0", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/prometheus/client_golang@v1.23.2", + "referenceLocator": "pkg:golang/github.com/prometheus/client_golang@v1.24.0", "referenceType": "purl" } ], @@ -1782,7 +1782,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/prometheus/client_golang", - "versionInfo": "v1.23.2" + "versionInfo": "v1.24.0" }, { "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-client-model-v0.6.2", @@ -1802,13 +1802,13 @@ "versionInfo": "v0.6.2" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-common-v0.67.5", + "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-common-v0.70.0", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/prometheus/common@v0.67.5", + "referenceLocator": "pkg:golang/github.com/prometheus/common@v0.70.0", "referenceType": "purl" } ], @@ -1816,16 +1816,16 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/prometheus/common", - "versionInfo": "v0.67.5" + "versionInfo": "v0.70.0" }, { - "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-procfs-v0.19.2", + "SPDXID": "SPDXRef-pkg-golang-github.com-prometheus-procfs-v0.21.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/github.com/prometheus/procfs@v0.19.2", + "referenceLocator": "pkg:golang/github.com/prometheus/procfs@v0.21.1", "referenceType": "purl" } ], @@ -1833,7 +1833,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "github.com/prometheus/procfs", - "versionInfo": "v0.19.2" + "versionInfo": "v0.21.1" }, { "SPDXID": "SPDXRef-pkg-golang-github.com-remyoudompheng-bigfft-v0.0.0-20230129092748-24d4a6f8daec", @@ -2295,13 +2295,13 @@ "versionInfo": "v1.44.0" }, { - "SPDXID": "SPDXRef-pkg-golang-go.yaml.in-yaml-v2-v2.4.3", + "SPDXID": "SPDXRef-pkg-golang-go.yaml.in-yaml-v2-v2.4.4", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/go.yaml.in/yaml/v2@v2.4.3", + "referenceLocator": "pkg:golang/go.yaml.in/yaml/v2@v2.4.4", "referenceType": "purl" } ], @@ -2309,7 +2309,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "go.yaml.in/yaml/v2", - "versionInfo": "v2.4.3" + "versionInfo": "v2.4.4" }, { "SPDXID": "SPDXRef-pkg-golang-go.yaml.in-yaml-v3-v3.0.5", @@ -2567,13 +2567,13 @@ "versionInfo": "v3.0.1" }, { - "SPDXID": "SPDXRef-pkg-golang-k8s.io-apimachinery-v0.36.2", + "SPDXID": "SPDXRef-pkg-golang-k8s.io-apimachinery-v0.37.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/k8s.io/apimachinery@v0.36.2", + "referenceLocator": "pkg:golang/k8s.io/apimachinery@v0.37.1", "referenceType": "purl" } ], @@ -2581,16 +2581,16 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "k8s.io/apimachinery", - "versionInfo": "v0.36.2" + "versionInfo": "v0.37.1" }, { - "SPDXID": "SPDXRef-pkg-golang-k8s.io-client-go-v0.36.2", + "SPDXID": "SPDXRef-pkg-golang-k8s.io-client-go-v0.37.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/k8s.io/client-go@v0.36.2", + "referenceLocator": "pkg:golang/k8s.io/client-go@v0.37.1", "referenceType": "purl" } ], @@ -2598,16 +2598,16 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "k8s.io/client-go", - "versionInfo": "v0.36.2" + "versionInfo": "v0.37.1" }, { - "SPDXID": "SPDXRef-pkg-golang-k8s.io-cri-streaming-v0.36.2", + "SPDXID": "SPDXRef-pkg-golang-k8s.io-cri-streaming-v0.37.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/k8s.io/cri-streaming@v0.36.2", + "referenceLocator": "pkg:golang/k8s.io/cri-streaming@v0.37.1", "referenceType": "purl" } ], @@ -2615,7 +2615,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "k8s.io/cri-streaming", - "versionInfo": "v0.36.2" + "versionInfo": "v0.37.1" }, { "SPDXID": "SPDXRef-pkg-golang-k8s.io-klog-v2-v2.140.0", @@ -2635,13 +2635,13 @@ "versionInfo": "v2.140.0" }, { - "SPDXID": "SPDXRef-pkg-golang-k8s.io-streaming-v0.36.2", + "SPDXID": "SPDXRef-pkg-golang-k8s.io-streaming-v0.37.1", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/k8s.io/streaming@v0.36.2", + "referenceLocator": "pkg:golang/k8s.io/streaming@v0.37.1", "referenceType": "purl" } ], @@ -2649,16 +2649,16 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "k8s.io/streaming", - "versionInfo": "v0.36.2" + "versionInfo": "v0.37.1" }, { - "SPDXID": "SPDXRef-pkg-golang-k8s.io-utils-v0.0.0-20260319190234-28399d86e0b5", + "SPDXID": "SPDXRef-pkg-golang-k8s.io-utils-v0.0.0-20260626114624-be93311217bd", "copyrightText": "NOASSERTION", "downloadLocation": "NOASSERTION", "externalRefs": [ { "referenceCategory": "PACKAGE-MANAGER", - "referenceLocator": "pkg:golang/k8s.io/utils@v0.0.0-20260319190234-28399d86e0b5", + "referenceLocator": "pkg:golang/k8s.io/utils@v0.0.0-20260626114624-be93311217bd", "referenceType": "purl" } ], @@ -2666,7 +2666,7 @@ "licenseConcluded": "Apache-2.0", "licenseDeclared": "Apache-2.0", "name": "k8s.io/utils", - "versionInfo": "v0.0.0-20260319190234-28399d86e0b5" + "versionInfo": "v0.0.0-20260626114624-be93311217bd" }, { "SPDXID": "SPDXRef-pkg-golang-modernc.org-libc-v1.77.1", @@ -2853,27 +2853,27 @@ "spdxElementId": "SPDXRef-DOCUMENT" }, { - "relatedSpdxElement": "SPDXRef-pkg-generic-go-1.26.10", + "relatedSpdxElement": "SPDXRef-pkg-generic-go-1.26.11", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-amd64", + "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-amd64", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-arm", + "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-arm", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-arm64", + "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-arm64", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.0-arch-riscv64", + "relatedSpdxElement": "SPDXRef-pkg-generic-k3s-root-v0.15.4-arch-riscv64", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -2883,7 +2883,7 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-github-containers-crun-1.28", + "relatedSpdxElement": "SPDXRef-pkg-github-containers-crun-1.30.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3018,7 +3018,7 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-containerd-platforms-v1.0.0-rc.4", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-containerd-platforms-v1.0.0-rc.5", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3128,7 +3128,7 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-fxamacker-cbor-v2-v2.9.0", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-fxamacker-cbor-v2-v2.9.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3193,17 +3193,17 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.2-k3s2", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.7-k3s1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.2-k3s2-cmd-containerd-shim-runc-v2", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-containerd-v2-v2.3.7-k3s1-cmd-containerd-shim-runc-v2", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-kubernetes-staging-src-k8s.io-cri-api-v1.36.2-k3s2", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-k3s-io-kubernetes-staging-src-k8s.io-cri-api-v1.37.2-k3s1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3353,7 +3353,7 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-client-golang-v1.23.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-client-golang-v1.24.0", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3363,12 +3363,12 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-common-v0.67.5", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-common-v0.70.0", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-procfs-v0.19.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-github.com-prometheus-procfs-v0.21.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3508,7 +3508,7 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-go.yaml.in-yaml-v2-v2.4.3", + "relatedSpdxElement": "SPDXRef-pkg-golang-go.yaml.in-yaml-v2-v2.4.4", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3588,17 +3588,17 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-apimachinery-v0.36.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-apimachinery-v0.37.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-client-go-v0.36.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-client-go-v0.37.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-cri-streaming-v0.36.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-cri-streaming-v0.37.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, @@ -3608,12 +3608,12 @@ "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-streaming-v0.36.2", + "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-streaming-v0.37.1", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, { - "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-utils-v0.0.0-20260319190234-28399d86e0b5", + "relatedSpdxElement": "SPDXRef-pkg-golang-k8s.io-utils-v0.0.0-20260626114624-be93311217bd", "relationshipType": "DEPENDS_ON", "spdxElementId": "SPDXRef-pkg-golang-github.com-eclipse-iofog-edgelet" }, diff --git a/scripts/check-containerd-fork.sh b/scripts/check-containerd-fork.sh index 465e2f8..17095b7 100755 --- a/scripts/check-containerd-fork.sh +++ b/scripts/check-containerd-fork.sh @@ -7,7 +7,7 @@ cd "$(dirname "$0")/.." GO=${GO-go} MODULE=github.com/containerd/containerd/v2 WANT_PATH=github.com/k3s-io/containerd/v2 -WANT_VERSION=v2.3.2-k3s2 +WANT_VERSION=v2.3.7-k3s1 resolved_path=$("${GO}" list -mod=readonly -m -f '{{if .Replace}}{{.Replace.Path}}{{else}}{{.Path}}{{end}}' "${MODULE}") resolved_version=$("${GO}" list -mod=readonly -m -f '{{if .Replace}}{{.Replace.Version}}{{else}}{{.Version}}{{end}}' "${MODULE}") diff --git a/scripts/quality-linux.sh b/scripts/quality-linux.sh index c1e6e0d..40172b5 100755 --- a/scripts/quality-linux.sh +++ b/scripts/quality-linux.sh @@ -5,7 +5,7 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT" -GO_IMAGE="${GO_IMAGE:-golang:1.26.10}" +GO_IMAGE="${GO_IMAGE:-golang:1.26.11}" GOARCH="${GOARCH:-arm64}" GOLANGCI_LINT_VERSION="${GOLANGCI_LINT_VERSION:-v2.12.2}" GOVULNCHECK_VERSION="${GOVULNCHECK_VERSION:-v1.1.4}" diff --git a/scripts/test-linux.sh b/scripts/test-linux.sh index eed5330..9e78455 100755 --- a/scripts/test-linux.sh +++ b/scripts/test-linux.sh @@ -7,7 +7,7 @@ set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT" -GO_IMAGE="${GO_IMAGE:-golang:1.26.10}" +GO_IMAGE="${GO_IMAGE:-golang:1.26.11}" GOARCH="${GOARCH:-$(go env GOARCH)}" TEST_FLAGS="${TEST_FLAGS:-}" RUN_NOCGO=1 diff --git a/scripts/version.sh b/scripts/version.sh index 27476e7..7e06cfa 100755 --- a/scripts/version.sh +++ b/scripts/version.sh @@ -1,7 +1,7 @@ #!/bin/bash # Edgelet embed pipeline version pins (RFC R16–R19, version-matrix.md). -VERSION_GOLANG="1.26.10" +VERSION_GOLANG="1.26.11" GO=${GO-go} ARCH=${ARCH:-$("${GO}" env GOARCH)} @@ -18,11 +18,11 @@ get-module-path() { PKG_CONTAINERD=$(get-module-path github.com/containerd/containerd/v2) VERSION_CONTAINERD=$(get-module-version github.com/containerd/containerd/v2) if [ -z "${VERSION_CONTAINERD}" ]; then - VERSION_CONTAINERD="v2.3.2-k3s2" + VERSION_CONTAINERD="v2.3.7-k3s1" fi VERSION_CNIPLUGINS="v1.9.1-k3s1" -VERSION_CRUN="1.28" +VERSION_CRUN="1.30.1" # Multi-arch index digest of portainer/pause. build-embedded pulls this digest # per arch, then retags the archive portainer/pause:latest for the CRI sandbox ref. VERSION_PAUSE_REPO="portainer/pause" @@ -30,23 +30,23 @@ VERSION_PAUSE_DIGEST="sha256:df6d2fb5cff97c4070a12953a34a56422879f1e02b43400f1ca VERSION_PAUSE="${VERSION_PAUSE_REPO}@${VERSION_PAUSE_DIGEST}" # k3s-root: static net aux (iptables, ip, busybox) — selective stage into embed tar. -VERSION_ROOT="v0.15.0" +VERSION_ROOT="v0.15.4" K3S_ROOT_REPO="https://github.com/k3s-io/k3s-root/releases/download/${VERSION_ROOT}" K3S_ROOT_TAR="k3s-root-${ARCH}.tar" k3s_root_sha256() { case "${ARCH}" in amd64) - echo "20066815d9941185fce3934cc3bae2fa3e2dbb46ca7e63462efb2ea59f1b15c4" + echo "658581f9dba924b24dcca14fcbb7237d69c9d3cd56995558d56efcd522263ea9" ;; arm64) - echo "4bdfc715dc8b5e2c4956f8686b895a56386f4cc6468215dcd22130a680650577" + echo "80b65fd619c8534a5cfe09310217a588e7cbb43f2f95b5f3dedcf2b39495dafc" ;; arm) - echo "2e43dac7750da52a756a9d4e8598d6e89937d565582660b26ca124bd9c8dbfaa" + echo "2a09ec8b4ab7a7fd41f9caa0b04a15cc631c2682f27f6f3605a77684717f3ac4" ;; riscv64) - echo "0e79998acaa156059ba1ff676a4e5f290069e25f799de43ee016a0e780f9d4d3" + echo "fd5e0b38c0e13fba14ff45df2c0cb89fc8ae8b1c6f5a7480fd24f1d2b644b29e" ;; *) echo "[ERROR] unsupported ARCH for k3s-root: ${ARCH}" >&2 diff --git a/test/edgelet-kube/build.sh b/test/edgelet-kube/build.sh new file mode 100755 index 0000000..d386ecb --- /dev/null +++ b/test/edgelet-kube/build.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Builds the thin edgelet-kube binary and the fat runtime for the Lima guest. +# On macOS the Linux build runs inside the embed image. +# +# Usage: +# ./test/edgelet-kube/build.sh [--arch=arm64|amd64] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +TARGET_ARCH="$(go_arch "$(native_arch)")" +for arg in "$@"; do + case "${arg}" in + --arch=*) TARGET_ARCH="$(go_arch "${arg#*=}")" ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) die "unknown option: ${arg}" ;; + esac +done + +THIN="${REPO_ROOT}/kube/build/edgelet-kube" +FAT="${REPO_ROOT}/kube/build/edgelet-kube-server" + +log_step "Building edgelet-kube for linux/${TARGET_ARCH}" +if [[ "$(uname -s)" == "Darwin" ]]; then + "${REPO_ROOT}/kube/scripts/build.sh" --arch="${TARGET_ARCH}" +else + ARCH="${TARGET_ARCH}" "${REPO_ROOT}/kube/scripts/build.sh" +fi + +[[ -f "${THIN}" && -f "${FAT}" ]] || die "build did not write ${THIN} and ${FAT}" +for bin in "${THIN}" "${FAT}"; do + got="$(elf_go_arch "${bin}")" + [[ "${got}" == "${TARGET_ARCH}" ]] || die "${bin} is linux/${got}, want linux/${TARGET_ARCH}" +done +log_ok "linux/${TARGET_ARCH} thin binary and fat runtime are in kube/build" diff --git a/test/edgelet-kube/lib/log.sh b/test/edgelet-kube/lib/log.sh new file mode 100755 index 0000000..f2409bb --- /dev/null +++ b/test/edgelet-kube/lib/log.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Shared logging helpers for the edgelet-kube Lima suite. +# Source this file; do not execute it directly. + +if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then + _RESET='\033[0m' + _BOLD='\033[1m' + _CYAN='\033[0;36m' + _GREEN='\033[0;32m' + _YELLOW='\033[0;33m' + _RED='\033[0;31m' + _BLUE='\033[0;34m' +else + _RESET='' _BOLD='' _CYAN='' _GREEN='' _YELLOW='' _RED='' _BLUE='' +fi + +log_info() { echo -e "${_CYAN}[INFO]${_RESET} $*"; } +log_step() { echo -e "\n${_BOLD}${_BLUE}==> $*${_RESET}"; } +log_ok() { echo -e "${_GREEN}[ OK ]${_RESET} $*"; } +log_warn() { echo -e "${_YELLOW}[WARN]${_RESET} $*" >&2; } +log_fail() { echo -e "${_RED}[FAIL]${_RESET} $*" >&2; } +log_success() { echo -e "\n${_BOLD}${_GREEN}✓ $*${_RESET}"; } + +die() { + echo -e "${_RED}[ERROR]${_RESET} $*" >&2 + exit 1 +} + +# The suite never starts or stops the agent Lima VM. +refuse_agent_vm() { + if [[ "$1" == "iofog-test" ]]; then + die "refusing to start or stop iofog-test" + fi +} + +# native_arch returns the CPU arch, including under Rosetta. +native_arch() { + local arch + arch="$(uname -m)" + if [[ "${arch}" == "x86_64" && "$(uname -s)" == "Darwin" ]]; then + if sysctl -n hw.optional.arm64 2>/dev/null | grep -q 1; then + echo "arm64" + return + fi + fi + case "${arch}" in + aarch64) echo "arm64" ;; + x86_64) echo "amd64" ;; + *) echo "${arch}" ;; + esac +} + +# go_arch maps a host or guest name onto arm64 or amd64. +go_arch() { + case "$1" in + arm64|aarch64) echo "arm64" ;; + amd64|x86_64) echo "amd64" ;; + *) die "unsupported architecture: $1" ;; + esac +} + +# lima_arch maps arm64 or amd64 onto the Lima guest arch name. +lima_arch() { + case "$(go_arch "$1")" in + arm64) echo "aarch64" ;; + amd64) echo "x86_64" ;; + esac +} + +# elf_go_arch reads a Linux ELF and prints arm64 or amd64. +elf_go_arch() { + local desc + desc="$(file -b "$1" 2>/dev/null || true)" + case "${desc}" in + *aarch64*) echo "arm64" ;; + *x86-64*|*x86_64*) echo "amd64" ;; + *) echo "unknown" ;; + esac +} diff --git a/test/edgelet-kube/lima.yaml b/test/edgelet-kube/lima.yaml new file mode 100644 index 0000000..ca95c64 --- /dev/null +++ b/test/edgelet-kube/lima.yaml @@ -0,0 +1,58 @@ +# Lima VM for installing edgelet-kube and checking a Ready node. +# The guest arch is chosen at create time so it matches the Linux binary. + +vmType: vz +os: Linux + +cpus: 4 +memory: "8GiB" +disk: "40GiB" + +images: + - location: "https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img" + arch: "x86_64" + - location: "https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-arm64.img" + arch: "aarch64" + +mounts: + - location: "~" + writable: false + +rosetta: + enabled: false + +provision: + - mode: system + script: | + #!/bin/bash + set -eux + export DEBIAN_FRONTEND=noninteractive + modprobe overlay 2>/dev/null || true + modprobe br_netfilter 2>/dev/null || true + modprobe ip_tables 2>/dev/null || true + modprobe iptable_nat 2>/dev/null || true + modprobe nf_conntrack 2>/dev/null || true + apt-get update -qq + apt-get install -y --no-install-recommends \ + ca-certificates conntrack curl iptables iproute2 kmod + systemctl disable --now containerd 2>/dev/null || true + systemctl disable --now docker 2>/dev/null || true + install -d /var/tmp + echo ready >/var/tmp/edgelet-kube-vm-ready + +networks: + - vzNAT: true + +portForwards: + - guestPortRange: [1, 65535] + ignore: true + +probes: + - script: | + #!/bin/bash + grep -q overlay /proc/filesystems || modprobe overlay 2>/dev/null + hint: "Waiting for overlayfs..." + +message: | + The edgelet-kube test VM is ready. + Open a shell with: limactl shell edgelet-kube-test diff --git a/test/edgelet-kube/run-all.sh b/test/edgelet-kube/run-all.sh new file mode 100755 index 0000000..7d9eb1c --- /dev/null +++ b/test/edgelet-kube/run-all.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# Runs the edgelet-kube Lima suite: setup, build, start, install, test. +# +# Usage: +# ./test/edgelet-kube/run-all.sh [options] +# +# Options: +# --skip-setup Skip host prerequisite checks +# --skip-build Reuse kube/build/edgelet-kube and kube/build/edgelet-kube-server +# --skip-start Skip VM creation (the VM must already be running) +# --skip-stop Keep the VM running after the checks (default) +# --delete-vm Stop and delete the VM after the checks +# --vm-name=NAME Lima VM name (default: edgelet-kube-test) +# --arch=ARCH Linux arch: arm64 | amd64 (default: the host arch) +# --timeout=N Seconds to wait for the VM (default: 300) +# --ready-timeout=N Seconds to wait for the conflist and a Ready node (default: 1200) +# --ci On failure, delete the VM when --delete-vm was set +# +# Exit code: +# 0 The checks passed +# 1 Setup, build, install, or a check failed + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +SKIP_SETUP=false +SKIP_BUILD=false +SKIP_START=false +SKIP_STOP=true +DELETE_VM=false +VM_NAME="edgelet-kube-test" +TIMEOUT=300 +READY_TIMEOUT=1200 +CI_MODE=false +TARGET_ARCH="$(go_arch "$(native_arch)")" + +for arg in "$@"; do + case "${arg}" in + --skip-setup) SKIP_SETUP=true ;; + --skip-build) SKIP_BUILD=true ;; + --skip-start) SKIP_START=true ;; + --skip-stop) SKIP_STOP=true ;; + --delete-vm) DELETE_VM=true; SKIP_STOP=false ;; + --vm-name=*) VM_NAME="${arg#*=}" ;; + --arch=*) TARGET_ARCH="$(go_arch "${arg#*=}")" ;; + --timeout=*) TIMEOUT="${arg#*=}" ;; + --ready-timeout=*) READY_TIMEOUT="${arg#*=}" ;; + --ci) CI_MODE=true ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) log_warn "Unknown option: ${arg}" ;; + esac +done + +refuse_agent_vm "${VM_NAME}" + +HOST_ARCH="$(go_arch "$(native_arch)")" + +echo "" +echo -e "${_BOLD}======================================================================${_RESET}" +echo -e "${_BOLD} edgelet-kube Lima suite${_RESET}" +echo -e "${_BOLD} Host: $(uname -s)/${HOST_ARCH} Target: linux/${TARGET_ARCH} VM: ${VM_NAME}${_RESET}" +echo -e "${_BOLD}======================================================================${_RESET}" +echo "" + +START_TIME=$(date +%s) +OVERALL_STATUS=0 + +cleanup() { + local exit_code=$? + if [[ "${exit_code}" -ne 0 && "${CI_MODE}" == "true" && "${DELETE_VM}" == "true" ]]; then + log_warn "Cleaning up VM '${VM_NAME}' after failure" + "${SCRIPT_DIR}/vm-stop.sh" --vm-name="${VM_NAME}" --delete 2>/dev/null || true + fi +} +trap cleanup EXIT + +require_binaries() { + local thin="${REPO_ROOT}/kube/build/edgelet-kube" + local fat="${REPO_ROOT}/kube/build/edgelet-kube-server" + local bin got + [[ -f "${thin}" && -f "${fat}" ]] || \ + die "No pre-built binaries in kube/build. Remove --skip-build to build." + for bin in "${thin}" "${fat}"; do + got="$(elf_go_arch "${bin}")" + [[ "${got}" == "${TARGET_ARCH}" ]] || \ + die "${bin} is linux/${got}, want linux/${TARGET_ARCH}. Remove --skip-build to rebuild." + done +} + +if [[ "${SKIP_SETUP}" == "false" ]]; then + log_step "Step 1/5: Host prerequisites" + "${SCRIPT_DIR}/setup.sh" +else + log_info "Skipping setup (--skip-setup)" +fi + +if [[ "${SKIP_BUILD}" == "false" ]]; then + log_step "Step 2/5: Building linux/${TARGET_ARCH} binaries" + "${SCRIPT_DIR}/build.sh" --arch="${TARGET_ARCH}" +else + log_info "Skipping build (--skip-build)" + require_binaries +fi + +if [[ "${SKIP_START}" == "false" ]]; then + log_step "Step 3/5: Starting Lima VM '${VM_NAME}'" + "${SCRIPT_DIR}/vm-start.sh" --vm-name="${VM_NAME}" --arch="${TARGET_ARCH}" --timeout="${TIMEOUT}" +else + log_info "Skipping VM start (--skip-start)" +fi + +log_step "Step 4/5: Installing edgelet-kube in the VM" +"${SCRIPT_DIR}/vm-install.sh" --vm-name="${VM_NAME}" --arch="${TARGET_ARCH}" + +log_step "Step 5/5: Checking the node" +set +e +"${SCRIPT_DIR}/vm-test.sh" --vm-name="${VM_NAME}" --ready-timeout="${READY_TIMEOUT}" +TEST_EXIT=$? +set -e +if [[ "${TEST_EXIT}" -ne 0 ]]; then + OVERALL_STATUS=1 +fi + +if [[ "${DELETE_VM}" == "true" ]]; then + log_step "Tearing down VM '${VM_NAME}'" + "${SCRIPT_DIR}/vm-stop.sh" --vm-name="${VM_NAME}" --delete +elif [[ "${SKIP_STOP}" == "false" ]]; then + "${SCRIPT_DIR}/vm-stop.sh" --vm-name="${VM_NAME}" +else + echo "" + log_info "VM '${VM_NAME}' is still running." + log_info " Re-run checks: ./test/edgelet-kube/vm-test.sh --vm-name=${VM_NAME}" + log_info " Open a shell: limactl shell ${VM_NAME}" + log_info " Stop the VM: ./test/edgelet-kube/vm-stop.sh --vm-name=${VM_NAME}" + log_info " Delete the VM: ./test/edgelet-kube/vm-stop.sh --vm-name=${VM_NAME} --delete" +fi + +END_TIME=$(date +%s) +ELAPSED=$((END_TIME - START_TIME)) + +echo "" +echo -e "${_BOLD}======================================================================" +if [[ "${OVERALL_STATUS}" -eq 0 ]]; then + echo -e "${_GREEN} ALL CHECKS PASSED${_RESET}${_BOLD} (${ELAPSED}s)" +else + echo -e "${_RED} CHECKS FAILED${_RESET}${_BOLD} (${ELAPSED}s)" +fi +echo -e "${_BOLD}======================================================================${_RESET}" +echo "" + +exit "${OVERALL_STATUS}" diff --git a/test/edgelet-kube/setup.sh b/test/edgelet-kube/setup.sh new file mode 100755 index 0000000..340ca4b --- /dev/null +++ b/test/edgelet-kube/setup.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# Checks the host tools for the edgelet-kube Lima suite. +# Darwin builds the Linux binaries inside Docker, so a cross compiler is not required. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +if [[ "$(uname -s)" == "Darwin" ]]; then + if ! command -v brew >/dev/null 2>&1; then + die "Homebrew is not installed. Install it from https://brew.sh and re-run." + fi + log_info "Homebrew: OK ($(brew --version | head -1))" +fi + +if ! command -v limactl >/dev/null 2>&1; then + if [[ "$(uname -s)" == "Darwin" ]]; then + log_info "Installing Lima..." + brew install lima + else + die "limactl not found" + fi +fi +log_info "Lima: OK ($(limactl --version 2>/dev/null | head -1))" + +if ! command -v jq >/dev/null 2>&1; then + if [[ "$(uname -s)" == "Darwin" ]]; then + log_info "Installing jq..." + brew install jq + else + die "jq not found" + fi +fi +log_info "jq: OK ($(jq --version))" + +if ! command -v file >/dev/null 2>&1; then + die "file(1) is required to check the Linux binaries" +fi + +if [[ "$(uname -s)" == "Darwin" ]]; then + if ! command -v docker >/dev/null 2>&1; then + die "Docker is required to build the Linux binaries on macOS" + fi + if ! docker info >/dev/null 2>&1; then + die "Docker is installed but the daemon is not running" + fi + log_info "Docker: OK ($(docker version --format '{{.Server.Version}}' 2>/dev/null || echo running))" +fi + +log_success "Prerequisites are present. Run ./test/edgelet-kube/run-all.sh" diff --git a/test/edgelet-kube/vm-install.sh b/test/edgelet-kube/vm-install.sh new file mode 100755 index 0000000..71fd87b --- /dev/null +++ b/test/edgelet-kube/vm-install.sh @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +# Installs the thin binary in the Lima VM and starts edgelet-kube.service. +# +# Usage: +# ./test/edgelet-kube/vm-install.sh [--vm-name=edgelet-kube-test] [--arch=arm64|amd64] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +VM_NAME="edgelet-kube-test" +TARGET_ARCH="$(go_arch "$(native_arch)")" + +for arg in "$@"; do + case "${arg}" in + --vm-name=*) VM_NAME="${arg#*=}" ;; + --arch=*) TARGET_ARCH="$(go_arch "${arg#*=}")" ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) die "unknown option: ${arg}" ;; + esac +done + +refuse_agent_vm "${VM_NAME}" + +THIN="${REPO_ROOT}/kube/build/edgelet-kube" +FAT="${REPO_ROOT}/kube/build/edgelet-kube-server" +INSTALL="${REPO_ROOT}/kube/scripts/install.sh" + +[[ -f "${THIN}" ]] || die "thin binary not found at ${THIN}. Run ./test/edgelet-kube/build.sh" +[[ -f "${FAT}" ]] || die "fat runtime not found at ${FAT}. Run ./test/edgelet-kube/build.sh" +[[ -f "${INSTALL}" ]] || die "install script not found at ${INSTALL}" +for bin in "${THIN}" "${FAT}"; do + got="$(elf_go_arch "${bin}")" + [[ "${got}" == "${TARGET_ARCH}" ]] || die "${bin} is linux/${got}, want linux/${TARGET_ARCH}" +done + +# write_lima_node records the guest lima0 address as the node IP and on the +# serving certificate. That address is the one the Mac dials. eth0 is the +# user-mode address and owns the default route, so an unset node-ip publishes +# eth0 on LoadBalancer Services. An existing serving pair is removed so the +# next start issues a certificate that includes lima0. +write_lima_node() { + local line ip elapsed=0 + while true; do + line="$(limactl --tty=false shell "${VM_NAME}" -- ip -4 -o addr show dev lima0 2>/dev/null || true)" + ip="$(printf '%s\n' "${line}" | awk 'NF { print $4; exit }' | cut -d/ -f1)" + if [[ "${ip}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then + break + fi + if (( elapsed >= 60 )); then + die "guest lima0 has no IPv4 address" + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + log_info "Node IP and serving certificate will use guest lima0 ${ip}" + limactl --tty=false shell "${VM_NAME}" -- sudo bash -c \ + "mkdir -p /etc/edgelet-kube && printf 'node-ip: %s\\ntls-san:\\n - %s\\n' '${ip}' '${ip}' > /etc/edgelet-kube/config.yaml" + limactl --tty=false shell "${VM_NAME}" -- sudo rm -f \ + /var/lib/edgelet-kube/server/tls/serving.crt \ + /var/lib/edgelet-kube/server/tls/serving.key +} + +log_step "Installing edgelet-kube in VM '${VM_NAME}'" +write_lima_node +limactl --tty=false shell "${VM_NAME}" -- sudo sh "${INSTALL}" --bin-path="${THIN}" + +log_info "Waiting for edgelet-kube.service to be active" +elapsed=0 +until limactl --tty=false shell "${VM_NAME}" -- sudo systemctl is-active --quiet edgelet-kube >/dev/null 2>&1; do + if (( elapsed >= 90 )); then + limactl --tty=false shell "${VM_NAME}" -- sudo systemctl status edgelet-kube --no-pager -l || true + die "edgelet-kube.service did not become active" + fi + sleep 3 + elapsed=$((elapsed + 3)) +done +log_success "edgelet-kube.service is active in VM '${VM_NAME}'" diff --git a/test/edgelet-kube/vm-start.sh b/test/edgelet-kube/vm-start.sh new file mode 100755 index 0000000..7791e18 --- /dev/null +++ b/test/edgelet-kube/vm-start.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Creates and starts the edgelet-kube-test Lima VM. +# +# Usage: +# ./test/edgelet-kube/vm-start.sh [--vm-name=edgelet-kube-test] [--arch=arm64|amd64] [--timeout=300] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +VM_NAME="edgelet-kube-test" +TIMEOUT=300 +TARGET_ARCH="$(go_arch "$(native_arch)")" +LIMA_YAML="${SCRIPT_DIR}/lima.yaml" + +for arg in "$@"; do + case "${arg}" in + --vm-name=*) VM_NAME="${arg#*=}" ;; + --arch=*) TARGET_ARCH="$(go_arch "${arg#*=}")" ;; + --timeout=*) TIMEOUT="${arg#*=}" ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) die "unknown option: ${arg}" ;; + esac +done + +refuse_agent_vm "${VM_NAME}" +command -v limactl >/dev/null 2>&1 || die "limactl not found. Run ./test/edgelet-kube/setup.sh first." +command -v jq >/dev/null 2>&1 || die "jq not found. Run ./test/edgelet-kube/setup.sh first." + +LIMA_ARCH="$(lima_arch "${TARGET_ARCH}")" +HOST_ARCH="$(go_arch "$(native_arch)")" +VM_TYPE="vz" +if [[ "${TARGET_ARCH}" != "${HOST_ARCH}" ]]; then + VM_TYPE="qemu" + log_warn "linux/${TARGET_ARCH} does not match the host. The guest will use qemu." +fi + +vm_status() { + limactl list --json 2>/dev/null \ + | jq -r "select(.name == \"${VM_NAME}\") | .status" 2>/dev/null \ + | head -1 || true +} + +vm_arch() { + limactl list --json 2>/dev/null \ + | jq -r "select(.name == \"${VM_NAME}\") | .arch" 2>/dev/null \ + | head -1 || true +} + +status="$(vm_status)" +if [[ -n "${status}" ]]; then + got="$(vm_arch)" + if [[ -n "${got}" && "${got}" != "${LIMA_ARCH}" ]]; then + die "VM '${VM_NAME}' is ${got}, want ${LIMA_ARCH}. Delete it with ./test/edgelet-kube/vm-stop.sh --delete and re-run." + fi + log_info "VM '${VM_NAME}' already exists (status: ${status})" +else + log_step "Creating Lima VM '${VM_NAME}' (${LIMA_ARCH}, ${VM_TYPE})" + limactl --tty=false create \ + --name="${VM_NAME}" \ + --arch="${LIMA_ARCH}" \ + --vm-type="${VM_TYPE}" \ + "${LIMA_YAML}" + log_ok "VM '${VM_NAME}' created" +fi + +status="$(vm_status)" +if [[ "${status}" == "Running" ]]; then + log_info "VM '${VM_NAME}' is already running" +else + log_step "Starting VM '${VM_NAME}'" + limactl --tty=false start --timeout=1200s "${VM_NAME}" \ + || die "Could not start VM '${VM_NAME}'" +fi + +log_step "Waiting for SSH (timeout: ${TIMEOUT}s)" +elapsed=0 +until limactl --tty=false shell "${VM_NAME}" -- echo ready >/dev/null 2>&1; do + if (( elapsed >= TIMEOUT )); then + die "VM '${VM_NAME}' did not accept SSH within ${TIMEOUT}s" + fi + sleep 5 + elapsed=$((elapsed + 5)) +done + +log_info "Waiting for provisioning to finish" +elapsed=0 +until limactl --tty=false shell "${VM_NAME}" -- test -f /var/tmp/edgelet-kube-vm-ready >/dev/null 2>&1; do + if (( elapsed >= TIMEOUT )); then + die "VM '${VM_NAME}' did not finish provisioning within ${TIMEOUT}s" + fi + sleep 5 + elapsed=$((elapsed + 5)) +done + +limactl --tty=false shell "${VM_NAME}" -- sudo modprobe overlay >/dev/null 2>&1 || true +limactl --tty=false shell "${VM_NAME}" -- sudo modprobe br_netfilter >/dev/null 2>&1 || true +cgroup="$(limactl --tty=false shell "${VM_NAME}" -- stat -fc %T /sys/fs/cgroup 2>/dev/null || echo unknown)" +log_info "cgroup filesystem: ${cgroup}" +log_success "VM '${VM_NAME}' is ready" diff --git a/test/edgelet-kube/vm-stop.sh b/test/edgelet-kube/vm-stop.sh new file mode 100755 index 0000000..8d1cbe9 --- /dev/null +++ b/test/edgelet-kube/vm-stop.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Stops the edgelet-kube-test Lima VM. --delete removes it. +# +# Usage: +# ./test/edgelet-kube/vm-stop.sh [--vm-name=edgelet-kube-test] [--delete] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +VM_NAME="edgelet-kube-test" +DELETE=false + +for arg in "$@"; do + case "${arg}" in + --vm-name=*) VM_NAME="${arg#*=}" ;; + --delete) DELETE=true ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) die "unknown option: ${arg}" ;; + esac +done + +refuse_agent_vm "${VM_NAME}" + +if ! command -v limactl >/dev/null 2>&1; then + log_warn "limactl not found — nothing to stop" + exit 0 +fi + +status="$(limactl list --json 2>/dev/null \ + | jq -r "select(.name == \"${VM_NAME}\") | .status" 2>/dev/null \ + | head -1 || true)" + +if [[ -z "${status}" ]]; then + log_info "VM '${VM_NAME}' does not exist" + exit 0 +fi + +if [[ "${status}" == "Running" ]]; then + log_step "Stopping VM '${VM_NAME}'" + limactl stop "${VM_NAME}" + log_ok "VM stopped" +else + log_info "VM '${VM_NAME}' is not running (status: ${status})" +fi + +if [[ "${DELETE}" == "true" ]]; then + log_step "Deleting VM '${VM_NAME}'" + limactl delete "${VM_NAME}" + log_ok "VM deleted" +fi diff --git a/test/edgelet-kube/vm-test.sh b/test/edgelet-kube/vm-test.sh new file mode 100755 index 0000000..90c65ee --- /dev/null +++ b/test/edgelet-kube/vm-test.sh @@ -0,0 +1,268 @@ +#!/usr/bin/env bash +# Checks extract, the containerd socket, the bridge conflist, a Ready node, +# the iptables family, and that the Mac can reach the API at the guest address +# on lima0. It then restarts edgelet-kube three times and requires CoreDNS to +# become Ready after each restart. +# +# Usage: +# ./test/edgelet-kube/vm-test.sh [--vm-name=edgelet-kube-test] [--ready-timeout=1200] + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# shellcheck source=lib/log.sh +source "${SCRIPT_DIR}/lib/log.sh" + +VM_NAME="edgelet-kube-test" +READY_TIMEOUT=1200 + +for arg in "$@"; do + case "${arg}" in + --vm-name=*) VM_NAME="${arg#*=}" ;; + --ready-timeout=*) READY_TIMEOUT="${arg#*=}" ;; + --help|-h) + sed -n '/^# Usage:/,/^[^#]/p' "$0" | grep '^#' | sed 's/^# \?//' + exit 0 + ;; + *) die "unknown option: ${arg}" ;; + esac +done + +refuse_agent_vm "${VM_NAME}" + +guest_eval() { + local payload + payload="$(printf '%s\n' "$1" | base64 | tr -d '\n')" + limactl --tty=false shell "${VM_NAME}" -- sudo bash -c "set -o pipefail; printf '%s' '${payload}' | base64 -d | bash" +} + +show_diagnostics() { + log_warn "edgelet-kube.service status:" + limactl --tty=false shell "${VM_NAME}" -- sudo systemctl status edgelet-kube --no-pager -l || true + log_warn "recent edgelet-kube logs:" + limactl --tty=false shell "${VM_NAME}" -- sudo journalctl -u edgelet-kube --no-pager -n 120 || true +} + +wait_guest() { + local desc="$1" + local timeout="$2" + local script="$3" + local elapsed=0 + local next_log=0 + local output="" + local status=0 + while true; do + status=0 + output="$(guest_eval "${script}" 2>&1)" || status=$? + if [[ "${status}" -eq 0 ]]; then + log_ok "${desc}" + return 0 + fi + if (( elapsed >= timeout )); then + log_fail "${desc} (waited ${timeout}s)" + if [[ -n "${output}" ]]; then + printf '%s\n' "${output}" >&2 + fi + return 1 + fi + if (( elapsed >= next_log )); then + log_info "waiting for ${desc} (${elapsed}s/${timeout}s)" + next_log=$((elapsed + 30)) + fi + sleep 5 + elapsed=$((elapsed + 5)) + done +} + +# lima_guest_ip is the IPv4 address of lima0 inside the guest. +# That is the vzNAT address the Mac can dial. eth0 is the user-mode address. +lima_guest_ip() { + local line ip + line="$(guest_eval 'ip -4 -o addr show dev lima0 | awk "{print \$4}" | cut -d/ -f1')" + ip="$(printf '%s\n' "${line}" | awk 'NF { print; exit }')" + if [[ ! "${ip}" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then + echo "guest lima0 has no IPv4 address" >&2 + if [[ -n "${line}" ]]; then + printf '%s\n' "${line}" >&2 + fi + return 1 + fi + printf '%s\n' "${ip}" +} + +# check_host_api dials the API from the Mac at the guest lima address and +# requires that address on the serving certificate. +check_host_api() { + local guest san + guest="$(lima_guest_ip)" || return 1 + if ! nc -z -G 5 "${guest}" 6443; then + log_fail "API ${guest}:6443 is not reachable from the host" + return 1 + fi + san="$(openssl s_client -connect "${guest}:6443" -servername "${guest}" /dev/null | openssl x509 -noout -ext subjectAltName 2>/dev/null || true)" + if ! printf '%s\n' "${san}" | grep -Eq "(IP Address|IP):${guest}(,|[[:space:]]|$)"; then + log_fail "serving certificate does not include ${guest}" + printf '%s\n' "${san}" >&2 + return 1 + fi + log_ok "API https://${guest}:6443 is reachable and the certificate includes ${guest}" +} + +EXTRACT_CHECK='set -eu +thin=$(readlink -f /usr/local/bin/edgelet-kube) +fats=$(find /var/lib/edgelet-kube/data -type f -path "*/bin/edgelet-kube" 2>/dev/null || true) +if [ -z "$fats" ]; then + echo "runtime was not extracted" >&2 + exit 1 +fi +count=$(printf "%s\n" "$fats" | grep -c .) +if [ "$count" != "1" ]; then + echo "expected one extracted runtime" >&2 + printf "%s\n" "$fats" >&2 + exit 1 +fi +fat=$(readlink -f "$fats") +test "$thin" != "$fat" +if cmp -s "$thin" "$fat"; then + echo "installed binary matches the extracted runtime" >&2 + exit 1 +fi +pid=$(systemctl show -p MainPID --value edgelet-kube.service) +test "$pid" -gt 0 +exe=$(readlink -f "/proc/${pid}/exe") +test "$exe" = "$fat" +child="" +for dir in /proc/[0-9]*; do + cmd=$(tr "\0" " " < "$dir/cmdline" 2>/dev/null || true) + case "$cmd" in + *--edgelet-kube-containerd-child*) + cexe=$(readlink -f "$dir/exe" 2>/dev/null || true) + case "$cexe" in + */bin/edgelet-kube) child=${dir#/proc/}; break ;; + esac + ;; + esac +done +test -n "$child" +cexe=$(readlink -f "/proc/${child}/exe") +test "$cexe" = "$fat" +' + +SOCKET_CHECK='set -eu +test -S /run/edgelet-kube/containerd.sock +' + +CONFLIST_CHECK='set -eu +file=/var/lib/edgelet-kube/agent/etc/cni/net.d/10-bridge.conflist +test -f "$file" +grep -F -q "\"type\":\"bridge\"" "$file" +grep -F -q "\"hairpinMode\":true" "$file" +' + +NODE_CHECK='set -eu +out=$(/usr/local/bin/kubectl --kubeconfig /etc/edgelet-kube/edgelet-kube.yaml get nodes --no-headers) +printf "%s\n" "$out" | awk "{print \$2}" | grep -qx Ready +' + +IPTABLES_CHECK='set -eu +aux=$(find /var/lib/edgelet-kube/data -type d -path "*/bin/aux" | head -n 1) +test -n "$aux" +for name in iptables iptables-save iptables-restore ip6tables ip6tables-save ip6tables-restore; do + test "$(readlink "$aux/$name")" = xtables-nft-multi +done +' + +COREDNS_CHECK='set -eu +ready=$(/usr/local/bin/kubectl --kubeconfig /etc/edgelet-kube/edgelet-kube.yaml get pods -n kube-system -l k8s-app=kube-dns -o jsonpath="{.items[0].status.containerStatuses[0].ready}") +test "$ready" = true +' + +# Three restarts, each bounded by 90 tries of 2s. CoreDNS stays unready +# until a pod can reach the API. The guest also dials the kubernetes +# Service, which is the host-side check that ClusterIP forwarding is back. +RESTART_CHECK='set -eu +k=/usr/local/bin/kubectl +export KUBECONFIG=/etc/edgelet-kube/edgelet-kube.yaml +portal_open() { + local svc + svc=$($k get svc kubernetes -o jsonpath="{.spec.clusterIP}" 2>/dev/null || true) + test -n "$svc" + timeout 3 bash -c "echo >/dev/tcp/${svc}/443" 2>/dev/null +} +for i in 1 2 3; do + echo "restart ${i}/3" + systemctl restart edgelet-kube + ok=0 + for _ in $(seq 1 90); do + if systemctl is-active --quiet edgelet-kube && test -S /run/edgelet-kube/containerd.sock; then + node=$($k get nodes --no-headers 2>/dev/null | awk "{print \$2}" || true) + dns=$($k get pods -n kube-system -l k8s-app=kube-dns -o jsonpath="{.items[0].status.containerStatuses[0].ready}" 2>/dev/null || true) + if [ "$node" = Ready ] && [ "$dns" = true ] && portal_open; then + ok=1 + break + fi + fi + sleep 2 + done + test "$ok" = 1 + echo "ready after restart ${i}" +done +' + +echo "" +echo "======================================================================" +echo " edgelet-kube Lima checks" +echo " VM: ${VM_NAME}" +echo "======================================================================" + +log_step "Extracted runtime" +if ! wait_guest "thin binary extracted the fat runtime and execs it" 180 "${EXTRACT_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "containerd socket" +if ! wait_guest "containerd socket /run/edgelet-kube/containerd.sock" 180 "${SOCKET_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "Bridge conflist" +if ! wait_guest "bridge conflist with hairpinMode true" "${READY_TIMEOUT}" "${CONFLIST_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "Node" +if ! wait_guest "node Ready" "${READY_TIMEOUT}" "${NODE_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "API from the host" +if ! check_host_api; then + show_diagnostics + exit 1 +fi + +log_step "iptables family" +if ! wait_guest "iptables, iptables-save, and iptables-restore name xtables-nft-multi" 60 "${IPTABLES_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "CoreDNS" +if ! wait_guest "CoreDNS Ready" "${READY_TIMEOUT}" "${COREDNS_CHECK}"; then + show_diagnostics + exit 1 +fi + +log_step "Restart storm" +if ! guest_eval "${RESTART_CHECK}"; then + log_fail "CoreDNS was not Ready after three edgelet-kube restarts" + show_diagnostics + exit 1 +fi +log_ok "CoreDNS Ready after three edgelet-kube restarts" + +log_success "edgelet-kube checks passed"