diff --git a/.changes/unreleased/Added-20260910-115216.yaml b/.changes/unreleased/Added-20260910-115216.yaml new file mode 100644 index 0000000..a531397 --- /dev/null +++ b/.changes/unreleased/Added-20260910-115216.yaml @@ -0,0 +1,3 @@ +kind: Added +body: E2E test on local machine for developers on a kind cluster supporting both linux and MacOS +time: 2026-09-10T11:52:16.94752+02:00 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..85baa2d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +.git +_artifacts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml new file mode 100644 index 0000000..1660d13 --- /dev/null +++ b/.github/workflows/e2e.yaml @@ -0,0 +1,88 @@ +name: E2E + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +env: + KIND_VERSION: v0.32.0 + KUBERNETES_VERSION: v1.32.11 + KIND_CLUSTER_NAME: udev-manager-e2e + ARTIFACT_ROOT: ${{ github.workspace }}/_artifacts/kind + +jobs: + kind-e2e: + name: E2E - kind cluster + runs-on: ubuntu-latest + timeout-minutes: 25 + + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache-dependency-path: | + go.sum + test/e2e/go.sum + + - name: Install Kind and kubectl + shell: bash + run: | + set -euo pipefail + case "$(uname -m)" in + x86_64) architecture=amd64 ;; + aarch64|arm64) architecture=arm64 ;; + *) echo "unsupported runner architecture: $(uname -m)" >&2; exit 1 ;; + esac + + kind_url="https://kind.sigs.k8s.io/dl/${KIND_VERSION}/kind-linux-${architecture}" + curl -fsSLo kind "${kind_url}" + curl -fsSLo kind.sha256sum "${kind_url}.sha256sum" + echo "$(awk '{print $1}' kind.sha256sum) kind" | sha256sum --check + chmod +x kind + sudo mv kind /usr/local/bin/kind + + kubectl_url="https://dl.k8s.io/release/${KUBERNETES_VERSION}/bin/linux/${architecture}/kubectl" + curl -fsSLo kubectl "${kubectl_url}" + curl -fsSLo kubectl.sha256 "${kubectl_url}.sha256" + echo "$(cat kubectl.sha256) kubectl" | sha256sum --check + chmod +x kubectl + sudo mv kubectl /usr/local/bin/kubectl + + - name: Prepare kernel device drivers + shell: bash + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y -q rdma-core "linux-modules-extra-$(uname -r)" + sudo modprobe nbd nbds_max=8 max_part=8 + + if sudo modprobe rdma_rxe; then + echo "Using rdma_rxe for software RDMA devices" + elif sudo modprobe siw; then + echo "Using siw for software RDMA devices" + else + echo "Neither rdma_rxe nor siw is available in $(uname -r)" >&2 + exit 1 + fi + + sudo udevadm settle + test -b /dev/nbd0 + + - name: Run multi-node E2E scenarios + run: make e2e + + - name: Upload E2E results and diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: kind-e2e-logs + path: _artifacts/ + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 06efabc..abc51e4 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ go.work.sum # Claude Code local settings .claude/settings.local.json + +# Kind end-to-end test diagnostics +_artifacts/ diff --git a/Makefile b/Makefile index db7f63a..082f015 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ SETUP := apt-get update -qq && apt-get install -y -q libudev-dev LINT_IMAGE := golangci/golangci-lint:v2.1.6 -.PHONY: test build coverage lint +.PHONY: test build coverage lint kind-up kind-down kind-device e2e test: docker run --rm -v "$(CURDIR):/go/app" -w /go/app $(IMAGE) \ @@ -20,3 +20,15 @@ coverage: lint: docker run --rm -v "$(CURDIR):/go/app" -w /go/app $(LINT_IMAGE) \ sh -c "$(SETUP) && golangci-lint run ./..." + +kind-up: + bash test/kind/kind.sh up + +kind-down: + bash test/kind/kind.sh down + +kind-device: + bash test/kind/kind.sh device "$(ACTION)" "$(NODE)" "$(LABEL)" "$(SIGNATURE)" "$(DEVICE)" "$(PEER)" "$(RDMA_DEVICE)" + +e2e: + bash test/kind/e2e.sh diff --git a/README.md b/README.md index 04804d2..a4ea20f 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,70 @@ make build # compile make test # run tests with -race ``` +### Kind development cluster and E2E tests + +The Kind cluster runs the `udev-manager` executable against devices +created by the Linux kernel. It uses GPT-labelled NBD partitions, veth pairs, +and software RDMA (`rdma_rxe`, with `siw` as a fallback). The devices have real +sysfs entries, udev records, and `/dev/infiniband` character devices. +Device construction and the test `udevd` run only in a separate test-toolbox +image; the production image still contains only the normal `udev-manager` +executable and runtime dependencies. Both normal builds and the Kind tests use +the root `udev-manager.Dockerfile`; Docker builds it for the current platform. + +Linux requires a rootful Docker daemon and kernel support for NBD partitions +plus either `rdma_rxe` or `siw`. +On macOS, it starts OrbStack when necessary and uses its `orbstack` +Docker context without changing the global Docker context. `docker`, `kind`, +`kubectl`, and Go must be on `PATH`; macOS additionally requires `orbctl`. + +```bash +make kind-up # leave a populated cluster running for manual testing +make e2e # create, test, diagnose on failure, and remove an isolated cluster +``` + +The manual cluster has one control-plane and two workers and uses context +`kind-udev-manager-dev` in the active kubeconfig (`$KUBECONFIG`, or +`~/.kube/config` by default). It includes shared individual and batch +partitions, node-local bandwidth and software-RDMA devices, a matched non-RDMA +interface, RDMA devices rejected by PF/VF filters because they have no PCI +parent, and a NUMA resource on every node. + +```bash +make kind-device ACTION=status +make kind-device ACTION=reset +make kind-device ACTION=seed +make kind-device ACTION=add-partition \ + LABEL=e2e_disk-hot SIGNATURE=UDEV_MANAGER_E2E_HOT +make kind-device ACTION=remove-partition LABEL=e2e_disk-hot +make kind-device ACTION=add-veth NODE=udev-manager-dev-worker \ + DEVICE=e2ebw-manual PEER=e2ebw-peer2 +make kind-device ACTION=add-rdma NODE=udev-manager-dev-worker2 \ + DEVICE=e2erdma-any PEER=e2eany-peer RDMA_DEVICE=rxe_e2eany +make kind-down +``` + +Set `KEEP_E2E_CLUSTER=1` to retain a failed E2E cluster. Diagnostics are written +under `_artifacts/kind/`. The E2E command uses a temporary context in the active +kubeconfig and restores the previously selected context when it exits. +`KIND_CLUSTER_NAME`, `UDEV_MANAGER_IMAGE`, `DEVICE_LAB_IMAGE`, and +`DOCKER_CONTEXT` can override the defaults. + +The Ginkgo suite in `test/e2e` controls devices through the per-node device-lab +pods. It creates and removes devices between scenarios and generates its +consumer Jobs from Go; the production application contains no simulation or +test-control code. NBD devices are shared by the Linux kernel and exposed on +all Kind nodes, while veth and RDMA devices remain local to their selected node. +Software-RDMA attachment does not emit a second netdev uevent, so that scenario +restarts only the target node's manager pod to re-enumerate after attach/remove; +the partition and bandwidth scenarios exercise live add/remove events directly. +Set `E2E_FOCUS` to a Ginkgo focus expression when debugging one scenario. + +The portable E2E suite does not create positive PCI SR-IOV PF/VF devices; +those classifications remain covered by unit tests. An RDMA-capable veth has +no PCI parent and is therefore used to verify that both PF and mixed-case VF +filters reject an unknown device type. + ## Examples See the [examples/](examples/) directory for sample configurations. diff --git a/test/e2e/devices_test.go b/test/e2e/devices_test.go new file mode 100644 index 0000000..0bb8d08 --- /dev/null +++ b/test/e2e/devices_test.go @@ -0,0 +1,176 @@ +package e2e_test + +import ( + "context" + "os" + + "github.com/ydb-platform/udev-manager/test/e2e/internal/lab" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("udev-manager on a multi-node Kind cluster", Ordered, Serial, func() { + var ( + ctx context.Context + testEnv *lab.Lab + topology lab.Topology + ) + + BeforeAll(func() { + if os.Getenv("E2E_CONTEXT") == "" { + Skip("E2E_CONTEXT is set by make e2e") + } + + ctx = context.Background() + var err error + testEnv, err = lab.NewFromEnv() + Expect(err).NotTo(HaveOccurred()) + topology, err = testEnv.Topology(ctx) + Expect(err).NotTo(HaveOccurred()) + }) + + BeforeEach(func() { + Expect(testEnv.DeleteTestJobs(ctx)).To(Succeed()) + Expect(testEnv.ResetAll(ctx)).To(Succeed()) + }) + + AfterEach(func() { + Expect(testEnv.DeleteTestJobs(ctx)).To(Succeed()) + Expect(testEnv.ResetAll(ctx)).To(Succeed()) + }) + + It("runs the production manager and test infrastructure on every node", func() { + Expect(topology.ControlPlanes).To(HaveLen(1)) + Expect(topology.Workers).To(HaveLen(2)) + + for _, node := range topology.All() { + Expect(testEnv.WaitDaemonSetOnNode(ctx, "udevd", node)).To(Succeed()) + Expect(testEnv.WaitDaemonSetOnNode(ctx, "device-lab", node)).To(Succeed()) + Expect(testEnv.WaitDaemonSetOnNode(ctx, "udev-manager", node)).To(Succeed()) + Expect(testEnv.VerifyManagerExecutable(ctx, node)).To(Succeed()) + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/numa-node0", 2)).To(Succeed()) + } + }) + + It("adds, consumes, and removes a shared real partition", func() { + partition, err := testEnv.AddSharedPartition(ctx, "e2e_disk-live", "UDEV_MANAGER_E2E_LIVE") + Expect(err).NotTo(HaveOccurred()) + + for _, node := range topology.All() { + Expect(testEnv.VerifyPartition(ctx, node, partition, "e2e_disk-live", "UDEV_MANAGER_E2E_LIVE")).To(Succeed()) + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/part-live", 1)).To(Succeed()) + } + + node, err := testEnv.RunConsumer(ctx, lab.Consumer{ + Name: "partition-live", + Resource: "devices.example/part-live", + Command: `test -b "$DEVICES_EXAMPLE_PART_LIVE_PATH" && dd if="$DEVICES_EXAMPLE_PART_LIVE_PATH" bs=64 count=1 status=none | grep -q UDEV_MANAGER_E2E_LIVE`, + }) + Expect(err).NotTo(HaveOccurred()) + Expect(topology.All()).To(ContainElement(node)) + + Expect(testEnv.RemoveSharedPartition(ctx, partition)).To(Succeed()) + for _, node := range topology.All() { + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/part-live", 0)).To(Succeed()) + } + }) + + It("updates a batch as partitions are added and removed", func() { + for _, node := range topology.All() { + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/batch-data", 0)).To(Succeed()) + } + + partitionA, err := testEnv.AddSharedPartition(ctx, "e2e_batch_a", "UDEV_MANAGER_E2E_BATCH_A") + Expect(err).NotTo(HaveOccurred()) + partitionB, err := testEnv.AddSharedPartition(ctx, "e2e_batch_b", "UDEV_MANAGER_E2E_BATCH_B") + Expect(err).NotTo(HaveOccurred()) + + for _, node := range topology.All() { + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/batch-data", 2)).To(Succeed()) + } + + _, err = testEnv.RunConsumer(ctx, lab.Consumer{ + Name: "batch-two", + Resource: "devices.example/batch-data", + Command: `test -b "$DEVICES_EXAMPLE_PART_A_PATH" && test -b "$DEVICES_EXAMPLE_PART_B_PATH" && ` + + `dd if="$DEVICES_EXAMPLE_PART_A_PATH" bs=64 count=1 status=none | grep -q UDEV_MANAGER_E2E_BATCH_A && ` + + `dd if="$DEVICES_EXAMPLE_PART_B_PATH" bs=64 count=1 status=none | grep -q UDEV_MANAGER_E2E_BATCH_B`, + }) + Expect(err).NotTo(HaveOccurred()) + + Expect(testEnv.RemoveSharedPartition(ctx, partitionA)).To(Succeed()) + for _, node := range topology.All() { + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/batch-data", 2)).To(Succeed()) + } + + _, err = testEnv.RunConsumer(ctx, lab.Consumer{ + Name: "batch-one", + Resource: "devices.example/batch-data", + Command: `test -z "${DEVICES_EXAMPLE_PART_A_PATH:-}" && test -b "$DEVICES_EXAMPLE_PART_B_PATH" && dd if="$DEVICES_EXAMPLE_PART_B_PATH" bs=64 count=1 status=none | grep -q UDEV_MANAGER_E2E_BATCH_B`, + }) + Expect(err).NotTo(HaveOccurred()) + + Expect(testEnv.RemoveSharedPartition(ctx, partitionB)).To(Succeed()) + for _, node := range topology.All() { + Expect(testEnv.WaitResource(ctx, node, "allocatable", "devices.example/batch-data", 0)).To(Succeed()) + } + }) + + It("keeps network bandwidth resources local to their node", func() { + target := topology.Workers[0] + shares, err := testEnv.AddVeth(ctx, target, "e2ebw-local", "e2ebw-peer") + Expect(err).NotTo(HaveOccurred()) + Expect(shares).To(BeNumerically(">", 0)) + Expect(testEnv.WaitResource(ctx, target, "allocatable", "devices.example/netbw-local", shares)).To(Succeed()) + for _, node := range topology.Without(target) { + Expect(testEnv.WaitResourceAbsent(ctx, node, "devices.example/netbw-local")).To(Succeed()) + } + + node, err := testEnv.RunConsumer(ctx, lab.Consumer{ + Name: "bandwidth-local", + Resource: "devices.example/netbw-local", + Command: "true", + }) + Expect(err).NotTo(HaveOccurred()) + Expect(node).To(Equal(target)) + + Expect(testEnv.RemoveNetwork(ctx, target, "e2ebw-local")).To(Succeed()) + Expect(testEnv.WaitResource(ctx, target, "allocatable", "devices.example/netbw-local", 0)).To(Succeed()) + }) + + It("registers only RDMA-enabled matches and applies PF/VF filters case-insensitively", func() { + target := topology.Workers[1] + _, err := testEnv.AddVeth(ctx, target, "e2enonrdma", "e2enon-peer") + Expect(err).NotTo(HaveOccurred()) + for _, node := range topology.All() { + Expect(testEnv.WaitResourceAbsent(ctx, node, "devices.example/netrdma-nonrdma")).To(Succeed()) + } + + Expect(testEnv.AddRDMA(ctx, target, "e2erdma-any", "e2eany-peer", "rxe_e2eany")).To(Succeed()) + Expect(testEnv.WaitResource(ctx, target, "allocatable", "devices.example/netrdma-any", 2)).To(Succeed()) + for _, node := range topology.Without(target) { + Expect(testEnv.WaitResourceAbsent(ctx, node, "devices.example/netrdma-any")).To(Succeed()) + } + + node, err := testEnv.RunConsumer(ctx, lab.Consumer{ + Name: "rdma-local", + Resource: "devices.example/netrdma-any", + HostNetwork: true, + Command: `test -n "$(find /dev/infiniband -maxdepth 1 -name 'uverbs*' -type c -print -quit)" && ibv_devices | grep -q rxe_e2eany`, + }) + Expect(err).NotTo(HaveOccurred()) + Expect(node).To(Equal(target)) + + Expect(testEnv.AddRDMA(ctx, target, "e2erdma-pf", "e2epf-peer", "rxe_e2epf")).To(Succeed()) + Expect(testEnv.AddRDMA(ctx, target, "e2erdma-vf", "e2evf-peer", "rxe_e2evf")).To(Succeed()) + for _, resource := range []string{"devices.example/netrdma-pf", "devices.example/netrdma-vf"} { + for _, candidate := range topology.All() { + Expect(testEnv.WaitResourceAbsent(ctx, candidate, resource)).To(Succeed()) + } + } + + Expect(testEnv.RemoveRDMA(ctx, target, "e2erdma-any", "rxe_e2eany")).To(Succeed()) + Expect(testEnv.WaitResource(ctx, target, "allocatable", "devices.example/netrdma-any", 0)).To(Succeed()) + }) +}) diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go new file mode 100644 index 0000000..cbc47c6 --- /dev/null +++ b/test/e2e/e2e_suite_test.go @@ -0,0 +1,13 @@ +package e2e_test + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestE2E(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "udev-manager Kind E2E Suite") +} diff --git a/test/e2e/go.mod b/test/e2e/go.mod new file mode 100644 index 0000000..81e3e38 --- /dev/null +++ b/test/e2e/go.mod @@ -0,0 +1,21 @@ +module github.com/ydb-platform/udev-manager/test/e2e + +go 1.24.1 + +require ( + github.com/onsi/ginkgo/v2 v2.23.4 + github.com/onsi/gomega v1.37.0 +) + +require ( + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-task/slim-sprig/v3 v3.0.0 // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 // indirect + go.uber.org/automaxprocs v1.6.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sys v0.32.0 // indirect + golang.org/x/text v0.23.0 // indirect + golang.org/x/tools v0.31.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/e2e/go.sum b/test/e2e/go.sum new file mode 100644 index 0000000..0acd796 --- /dev/null +++ b/test/e2e/go.sum @@ -0,0 +1,41 @@ +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8= +github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/onsi/ginkgo/v2 v2.23.4 h1:ktYTpKJAVZnDT4VjxSbiBenUjmlL/5QkBEocaWXiQus= +github.com/onsi/ginkgo/v2 v2.23.4/go.mod h1:Bt66ApGPBFzHyR+JO10Zbt0Gsp4uWxu5mIOTusL46e8= +github.com/onsi/gomega v1.37.0 h1:CdEG8g0S133B4OswTDC/5XPSzE1OeP29QOioj2PID2Y= +github.com/onsi/gomega v1.37.0/go.mod h1:8D9+Txp43QWKhM24yyOBEdpkzN8FvJyAwecBgsU4KU0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g= +github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= +go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20= +golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= +golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/e2e/internal/lab/lab.go b/test/e2e/internal/lab/lab.go new file mode 100644 index 0000000..eb8dbcd --- /dev/null +++ b/test/e2e/internal/lab/lab.go @@ -0,0 +1,510 @@ +package lab + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "sort" + "strconv" + "strings" + "time" +) + +const ( + defaultNamespace = "udev-manager-e2e" + defaultImage = "udev-manager-device-lab:kind-e2e" + commandTimeout = 3 * time.Minute + resourceTimeout = 2 * time.Minute +) + +type Lab struct { + context string + namespace string + image string +} + +type Topology struct { + ControlPlanes []string + Workers []string +} + +func (t Topology) All() []string { + result := make([]string, 0, len(t.ControlPlanes)+len(t.Workers)) + result = append(result, t.ControlPlanes...) + result = append(result, t.Workers...) + return result +} + +func (t Topology) Without(excluded string) []string { + var result []string + for _, node := range t.All() { + if node != excluded { + result = append(result, node) + } + } + return result +} + +type Partition struct { + Label string + Signature string + Device string + Owner string +} + +type Consumer struct { + Name string + Resource string + Command string + HostNetwork bool +} + +func NewFromEnv() (*Lab, error) { + contextName := os.Getenv("E2E_CONTEXT") + if contextName == "" { + return nil, errors.New("E2E_CONTEXT is required") + } + + namespace := os.Getenv("E2E_NAMESPACE") + if namespace == "" { + namespace = defaultNamespace + } + image := os.Getenv("E2E_DEVICE_LAB_IMAGE") + if image == "" { + image = defaultImage + } + + return &Lab{context: contextName, namespace: namespace, image: image}, nil +} + +func (l *Lab) kubectl(ctx context.Context, stdin []byte, args ...string) ([]byte, error) { + commandCtx, cancel := context.WithTimeout(ctx, commandTimeout) + defer cancel() + + commandArgs := append([]string{"--context", l.context}, args...) + command := exec.CommandContext(commandCtx, "kubectl", commandArgs...) + if stdin != nil { + command.Stdin = bytes.NewReader(stdin) + } + output, err := command.CombinedOutput() + if err != nil { + return nil, fmt.Errorf("kubectl %s: %w\n%s", strings.Join(commandArgs, " "), err, output) + } + return output, nil +} + +func (l *Lab) Topology(ctx context.Context) (Topology, error) { + output, err := l.kubectl(ctx, nil, "get", "nodes", "-o", "json") + if err != nil { + return Topology{}, err + } + + var list struct { + Items []struct { + Metadata struct { + Name string `json:"name"` + Labels map[string]string `json:"labels"` + } `json:"metadata"` + } `json:"items"` + } + if err := json.Unmarshal(output, &list); err != nil { + return Topology{}, fmt.Errorf("decode nodes: %w", err) + } + + var result Topology + for _, node := range list.Items { + _, controlPlane := node.Metadata.Labels["node-role.kubernetes.io/control-plane"] + _, legacyMaster := node.Metadata.Labels["node-role.kubernetes.io/master"] + if controlPlane || legacyMaster { + result.ControlPlanes = append(result.ControlPlanes, node.Metadata.Name) + } else { + result.Workers = append(result.Workers, node.Metadata.Name) + } + } + sort.Strings(result.ControlPlanes) + sort.Strings(result.Workers) + return result, nil +} + +func (l *Lab) podOnNode(ctx context.Context, app, node string) (string, bool, error) { + output, err := l.kubectl(ctx, nil, "get", "pods", "--namespace", l.namespace, + "--selector", "app="+app, "--field-selector", "spec.nodeName="+node, "-o", "json") + if err != nil { + return "", false, err + } + + var list struct { + Items []struct { + Metadata struct { + Name string `json:"name"` + } `json:"metadata"` + Status struct { + Phase string `json:"phase"` + Conditions []struct { + Type string `json:"type"` + Status string `json:"status"` + } `json:"conditions"` + } `json:"status"` + } `json:"items"` + } + if err := json.Unmarshal(output, &list); err != nil { + return "", false, fmt.Errorf("decode %s pods on %s: %w", app, node, err) + } + for _, pod := range list.Items { + ready := false + for _, condition := range pod.Status.Conditions { + if condition.Type == "Ready" && condition.Status == "True" { + ready = true + break + } + } + if pod.Status.Phase == "Running" { + return pod.Metadata.Name, ready, nil + } + } + return "", false, nil +} + +func (l *Lab) WaitDaemonSetOnNode(ctx context.Context, app, node string) error { + deadline := time.Now().Add(resourceTimeout) + var lastErr error + for time.Now().Before(deadline) { + _, ready, err := l.podOnNode(ctx, app, node) + if err == nil && ready { + return nil + } + lastErr = err + time.Sleep(time.Second) + } + return fmt.Errorf("pod app=%s on %s did not become ready: %w", app, node, lastErr) +} + +func (l *Lab) execInPod(ctx context.Context, app, node, container string, args ...string) ([]byte, error) { + pod, _, err := l.podOnNode(ctx, app, node) + if err != nil { + return nil, err + } + if pod == "" { + return nil, fmt.Errorf("no app=%s pod is running on %s", app, node) + } + + kubectlArgs := []string{"exec", "--namespace", l.namespace, pod, "--container", container, "--"} + kubectlArgs = append(kubectlArgs, args...) + return l.kubectl(ctx, nil, kubectlArgs...) +} + +func (l *Lab) deviceLab(ctx context.Context, node string, args ...string) ([]byte, error) { + command := append([]string{"/usr/local/bin/device-lab"}, args...) + return l.execInPod(ctx, "device-lab", node, "device-lab", command...) +} + +func (l *Lab) VerifyManagerExecutable(ctx context.Context, node string) error { + _, err := l.execInPod(ctx, "udev-manager", node, "udev-manager", "/bin/sh", "-ec", + `test "$(readlink /proc/1/exe)" = /usr/bin/udev-manager`) + return err +} + +func (l *Lab) ResetAll(ctx context.Context) error { + topology, err := l.Topology(ctx) + if err != nil { + return err + } + var result error + for _, node := range topology.All() { + if _, err := l.deviceLab(ctx, node, "reset"); err != nil { + result = errors.Join(result, fmt.Errorf("reset %s: %w", node, err)) + } + } + return result +} + +func (l *Lab) DeleteTestJobs(ctx context.Context) error { + _, err := l.kubectl(ctx, nil, "delete", "jobs", "--namespace", l.namespace, + "--selector", "app.kubernetes.io/part-of=udev-manager-e2e", "--ignore-not-found", "--wait=true") + return err +} + +func (l *Lab) AddSharedPartition(ctx context.Context, label, signature string) (Partition, error) { + topology, err := l.Topology(ctx) + if err != nil { + return Partition{}, err + } + if len(topology.Workers) == 0 { + return Partition{}, errors.New("a worker node is required to own shared NBD devices") + } + + partition := Partition{Label: label, Signature: signature, Owner: topology.Workers[0]} + output, err := l.deviceLab(ctx, partition.Owner, "partition", "add", label, signature, "auto") + if err != nil { + return Partition{}, err + } + for _, line := range strings.Split(string(output), "\n") { + if value, ok := strings.CutPrefix(line, "partition="); ok { + partition.Device = strings.TrimSpace(value) + } + } + if partition.Device == "" { + return Partition{}, fmt.Errorf("device-lab did not report a partition path:\n%s", output) + } + + for _, node := range topology.All() { + if _, err := l.deviceLab(ctx, node, "partition", "expose", partition.Device, "add"); err != nil { + _ = l.RemoveSharedPartition(ctx, partition) + return Partition{}, fmt.Errorf("expose %s on %s: %w", partition.Device, node, err) + } + } + return partition, nil +} + +func (l *Lab) RemoveSharedPartition(ctx context.Context, partition Partition) error { + topology, err := l.Topology(ctx) + if err != nil { + return err + } + + var result error + for _, node := range topology.All() { + if _, err := l.deviceLab(ctx, node, "partition", "expose", partition.Device, "remove"); err != nil { + result = errors.Join(result, fmt.Errorf("remove exposure from %s: %w", node, err)) + } + } + if _, err := l.deviceLab(ctx, partition.Owner, "partition", "remove", partition.Label); err != nil { + result = errors.Join(result, fmt.Errorf("disconnect %s: %w", partition.Label, err)) + } + return result +} + +func (l *Lab) VerifyPartition(ctx context.Context, node string, partition Partition, label, signature string) error { + _, err := l.deviceLab(ctx, node, "partition", "verify", partition.Device, label, signature) + return err +} + +func (l *Lab) AddVeth(ctx context.Context, node, device, peer string) (int, error) { + output, err := l.deviceLab(ctx, node, "net", "add", device, peer) + if err != nil { + return 0, err + } + for _, line := range strings.Split(string(output), "\n") { + if value, ok := strings.CutPrefix(line, "speed="); ok { + speed, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return 0, fmt.Errorf("parse speed from %q: %w", line, err) + } + shares := speed / 1000 + if shares < 1 { + return 0, fmt.Errorf("interface speed %d cannot provide a 1000 Mbps share", speed) + } + return shares, nil + } + } + return 0, fmt.Errorf("device-lab did not report interface speed:\n%s", output) +} + +func (l *Lab) RemoveNetwork(ctx context.Context, node, device string) error { + _, err := l.deviceLab(ctx, node, "net", "remove", device) + return err +} + +func (l *Lab) AddRDMA(ctx context.Context, node, device, peer, rdmaDevice string) error { + if _, err := l.deviceLab(ctx, node, "rdma", "add", device, peer, rdmaDevice, "auto"); err != nil { + return err + } + if err := l.restartManagerOnNode(ctx, node); err != nil { + _ = l.RemoveRDMA(ctx, node, device, rdmaDevice) + return fmt.Errorf("restart manager on %s after adding %s: %w", node, rdmaDevice, err) + } + return nil +} + +func (l *Lab) RemoveRDMA(ctx context.Context, node, device, rdmaDevice string) error { + if _, err := l.deviceLab(ctx, node, "rdma", "remove", device, rdmaDevice); err != nil { + return err + } + if err := l.restartManagerOnNode(ctx, node); err != nil { + return fmt.Errorf("restart manager on %s after removing %s: %w", node, rdmaDevice, err) + } + return nil +} + +func (l *Lab) restartManagerOnNode(ctx context.Context, node string) error { + pod, _, err := l.podOnNode(ctx, "udev-manager", node) + if err != nil { + return err + } + if pod == "" { + return fmt.Errorf("no udev-manager pod is running on %s", node) + } + if _, err := l.kubectl(ctx, nil, "delete", "pod", pod, "--namespace", l.namespace, "--wait=true"); err != nil { + return err + } + return l.WaitDaemonSetOnNode(ctx, "udev-manager", node) +} + +type nodeStatus struct { + Status struct { + Capacity map[string]string `json:"capacity"` + Allocatable map[string]string `json:"allocatable"` + } `json:"status"` +} + +func (l *Lab) resourceQuantity(ctx context.Context, node, section, resource string) (string, bool, error) { + output, err := l.kubectl(ctx, nil, "get", "node", node, "-o", "json") + if err != nil { + return "", false, err + } + var status nodeStatus + if err := json.Unmarshal(output, &status); err != nil { + return "", false, fmt.Errorf("decode node %s: %w", node, err) + } + var resources map[string]string + switch section { + case "capacity": + resources = status.Status.Capacity + case "allocatable": + resources = status.Status.Allocatable + default: + return "", false, fmt.Errorf("unknown resource section %q", section) + } + value, found := resources[resource] + return value, found, nil +} + +func (l *Lab) WaitResource(ctx context.Context, node, section, resource string, expected int) error { + deadline := time.Now().Add(resourceTimeout) + wanted := strconv.Itoa(expected) + last := "" + for time.Now().Before(deadline) { + value, found, err := l.resourceQuantity(ctx, node, section, resource) + if err == nil { + if found { + last = value + } + if found && value == wanted { + return nil + } + } else { + last = err.Error() + } + time.Sleep(2 * time.Second) + } + return fmt.Errorf("%s %s on %s = %s, want %s", section, resource, node, last, wanted) +} + +func (l *Lab) WaitResourceAbsent(ctx context.Context, node, resource string) error { + deadline := time.Now().Add(10 * time.Second) + consecutiveAbsent := 0 + for time.Now().Before(deadline) { + value, found, err := l.resourceQuantity(ctx, node, "capacity", resource) + if err != nil { + return err + } + if found { + return fmt.Errorf("capacity %s on %s unexpectedly exists with value %s", resource, node, value) + } + consecutiveAbsent++ + if consecutiveAbsent == 5 { + return nil + } + time.Sleep(time.Second) + } + return fmt.Errorf("capacity %s on %s did not remain absent", resource, node) +} + +func (l *Lab) RunConsumer(ctx context.Context, consumer Consumer) (string, error) { + name := "e2e-" + consumer.Name + _, _ = l.kubectl(ctx, nil, "delete", "job", name, "--namespace", l.namespace, + "--ignore-not-found", "--wait=true") + + manifest := map[string]any{ + "apiVersion": "batch/v1", + "kind": "Job", + "metadata": map[string]any{ + "name": name, + "namespace": l.namespace, + "labels": map[string]string{ + "app.kubernetes.io/part-of": "udev-manager-e2e", + }, + }, + "spec": map[string]any{ + "backoffLimit": 0, + "template": map[string]any{ + "metadata": map[string]any{ + "labels": map[string]string{ + "app.kubernetes.io/part-of": "udev-manager-e2e", + }, + }, + "spec": map[string]any{ + "hostNetwork": consumer.HostNetwork, + "restartPolicy": "Never", + "containers": []any{map[string]any{ + "name": "verify", + "image": l.image, + "imagePullPolicy": "Never", + "command": []string{"/bin/sh", "-ec", consumer.Command}, + "resources": map[string]any{ + "limits": map[string]string{consumer.Resource: "1"}, + }, + }}, + }, + }, + }, + } + content, err := json.Marshal(manifest) + if err != nil { + return "", fmt.Errorf("encode consumer job: %w", err) + } + if _, err := l.kubectl(ctx, content, "apply", "-f", "-"); err != nil { + return "", err + } + + deadline := time.Now().Add(commandTimeout) + for time.Now().Before(deadline) { + output, err := l.kubectl(ctx, nil, "get", "job", name, "--namespace", l.namespace, "-o", "json") + if err == nil { + var job struct { + Status struct { + Succeeded int `json:"succeeded"` + Failed int `json:"failed"` + } `json:"status"` + } + if json.Unmarshal(output, &job) == nil { + if job.Status.Succeeded > 0 { + return l.consumerNode(ctx, name) + } + if job.Status.Failed > 0 { + logs, _ := l.kubectl(ctx, nil, "logs", "job/"+name, "--namespace", l.namespace, "--all-containers") + return "", fmt.Errorf("consumer job %s failed:\n%s", name, logs) + } + } + } + time.Sleep(2 * time.Second) + } + logs, _ := l.kubectl(ctx, nil, "logs", "job/"+name, "--namespace", l.namespace, "--all-containers") + return "", fmt.Errorf("consumer job %s did not complete:\n%s", name, logs) +} + +func (l *Lab) consumerNode(ctx context.Context, job string) (string, error) { + output, err := l.kubectl(ctx, nil, "get", "pods", "--namespace", l.namespace, + "--selector", "job-name="+job, "-o", "json") + if err != nil { + return "", err + } + var list struct { + Items []struct { + Spec struct { + NodeName string `json:"nodeName"` + } `json:"spec"` + } `json:"items"` + } + if err := json.Unmarshal(output, &list); err != nil { + return "", fmt.Errorf("decode consumer pod: %w", err) + } + if len(list.Items) != 1 || list.Items[0].Spec.NodeName == "" { + return "", fmt.Errorf("consumer job %s has no scheduled pod", job) + } + return list.Items[0].Spec.NodeName, nil +} diff --git a/test/e2e/topology_test.go b/test/e2e/topology_test.go new file mode 100644 index 0000000..79910b6 --- /dev/null +++ b/test/e2e/topology_test.go @@ -0,0 +1,25 @@ +package e2e_test + +import ( + "os" + "path/filepath" + "runtime" + "strings" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("Kind topology", func() { + It("declares one control-plane and two workers", func() { + _, filename, _, ok := runtime.Caller(0) + Expect(ok).To(BeTrue()) + + content, err := os.ReadFile(filepath.Join(filepath.Dir(filename), "..", "kind", "cluster.yaml")) + Expect(err).NotTo(HaveOccurred()) + + cluster := string(content) + Expect(strings.Count(cluster, "role: control-plane")).To(Equal(1)) + Expect(strings.Count(cluster, "role: worker")).To(Equal(2)) + }) +}) diff --git a/test/kind/app-config.yaml b/test/kind/app-config.yaml new file mode 100644 index 0000000..6e4d8ec --- /dev/null +++ b/test/kind/app-config.yaml @@ -0,0 +1,26 @@ +domain: devices.example +health_check_port: 8080 +partitions: + - matcher: '^e2e_disk-(.*)$' +batchPartitions: + - name: data + matcher: '^e2e_batch_(.*)$' + count: 2 +networkBandwidth: + - matcher: '^e2ebw-(.*)$' + mbpsPerShare: 1000 +networkRdma: + - matcher: '^e2erdma-(any)$' + resourceCount: 2 + - matcher: '^e2erdma-(pf)$' + resourceCount: 1 + deviceType: PF + - matcher: '^e2erdma-(vf)$' + resourceCount: 1 + deviceType: vF + - matcher: '^e2e(nonrdma)$' + resourceCount: 1 +numaAffinity: + - name: node0 + numaNode: 0 + count: 2 diff --git a/test/kind/cluster.yaml b/test/kind/cluster.yaml new file mode 100644 index 0000000..8543882 --- /dev/null +++ b/test/kind/cluster.yaml @@ -0,0 +1,9 @@ +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +nodes: + - role: control-plane + image: kindest/node:v1.32.11 + - role: worker + image: kindest/node:v1.32.11 + - role: worker + image: kindest/node:v1.32.11 diff --git a/test/kind/daemonset.yaml b/test/kind/daemonset.yaml new file mode 100644 index 0000000..ad00465 --- /dev/null +++ b/test/kind/daemonset.yaml @@ -0,0 +1,71 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: udev-manager + namespace: udev-manager-e2e +spec: + selector: + matchLabels: + app: udev-manager + template: + metadata: + labels: + app: udev-manager + spec: + hostNetwork: true + tolerations: + - operator: Exists + containers: + - name: udev-manager + image: udev-manager:kind-e2e + imagePullPolicy: Never + env: + - name: UDEV_MANAGER_ARGS + value: -v=5 + securityContext: + privileged: true + readinessProbe: + httpGet: + path: /healthz + port: 8080 + periodSeconds: 2 + livenessProbe: + httpGet: + path: /healthz + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 5 + volumeMounts: + - name: config + mountPath: /etc/udev-manager + readOnly: true + - name: host-dev + mountPath: /dev + - name: host-sys + mountPath: /sys + readOnly: true + - name: host-udev + mountPath: /run/udev + readOnly: true + - name: device-plugins + mountPath: /var/lib/kubelet/device-plugins + volumes: + - name: config + configMap: + name: udev-manager-config + - name: host-dev + hostPath: + path: /dev + type: Directory + - name: host-sys + hostPath: + path: /sys + type: Directory + - name: host-udev + hostPath: + path: /run/udev + type: DirectoryOrCreate + - name: device-plugins + hostPath: + path: /var/lib/kubelet/device-plugins + type: Directory diff --git a/test/kind/device-lab.Dockerfile b/test/kind/device-lab.Dockerfile new file mode 100644 index 0000000..0fd6852 --- /dev/null +++ b/test/kind/device-lab.Dockerfile @@ -0,0 +1,20 @@ +FROM debian:bookworm-slim + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + coreutils \ + fdisk \ + grep \ + ibverbs-providers \ + ibverbs-utils \ + iproute2 \ + kmod \ + qemu-utils \ + rdma-core \ + udev \ + util-linux && \ + rm -rf /var/lib/apt/lists/* + +COPY --chmod=0755 test/kind/device-lab.sh /usr/local/bin/device-lab + +ENTRYPOINT ["/usr/local/bin/device-lab"] diff --git a/test/kind/device-lab.sh b/test/kind/device-lab.sh new file mode 100644 index 0000000..86f5a92 --- /dev/null +++ b/test/kind/device-lab.sh @@ -0,0 +1,405 @@ +#!/usr/bin/env bash +set -euo pipefail + +STATE_DIR=${STATE_DIR:-/state} +NBD_MAX=${NBD_MAX:-8} + +log() { printf 'device-lab: %s\n' "$*" >&2; } +fail() { log "$*"; return 1; } + +wait_for_path() { + local path=$1 + local attempt + for attempt in $(seq 1 100); do + [[ -e "${path}" ]] && return 0 + sleep 0.1 + done + fail "timed out waiting for ${path}" +} + +validate_label() { + [[ "$1" =~ ^e2e_[A-Za-z0-9_.-]+$ ]] || fail "invalid partition label: $1" +} + +validate_signature() { + [[ "$1" =~ ^UDEV_MANAGER_E2E_[A-Z0-9_]+$ ]] || fail "invalid signature: $1" +} + +validate_interface() { + [[ "$1" =~ ^e2e[A-Za-z0-9_.-]+$ ]] || fail "invalid interface name: $1" + (( ${#1} <= 15 )) || fail "interface name is longer than 15 characters: $1" +} + +validate_rdma_name() { + [[ "$1" =~ ^(rxe|siw)_e2e[A-Za-z0-9_.-]+$ ]] || fail "invalid RDMA device name: $1" +} + +validate_nbd_base() { + [[ "$1" =~ ^/dev/nbd([0-7])$ ]] || fail "NBD device is outside the owned test range: $1" +} + +validate_nbd_partition() { + [[ "$1" =~ ^/dev/nbd([0-7])p1$ ]] || fail "NBD partition is outside the owned test range: $1" +} + +ensure_block_node() { + local path=$1 + local name=${path##*/} + local sysfs_dev="/sys/class/block/${name}/dev" + local major + local minor + + wait_for_path "${sysfs_dev}" + if [[ ! -b "${path}" ]]; then + IFS=: read -r major minor < "${sysfs_dev}" + mknod "${path}" b "${major}" "${minor}" + fi +} + +ensure_char_node() { + local path=$1 + local sysfs_dev=$2 + local major + local minor + + wait_for_path "${sysfs_dev}" + if [[ ! -c "${path}" ]]; then + mkdir -p "${path%/*}" + IFS=: read -r major minor < "${sysfs_dev}" + mknod "${path}" c "${major}" "${minor}" + fi +} + +ensure_rdma_nodes() { + local sysfs_dev + if [[ -e /sys/class/infiniband_cm/rdma_cm/dev ]]; then + ensure_char_node /dev/infiniband/rdma_cm /sys/class/infiniband_cm/rdma_cm/dev + fi + for sysfs_dev in /sys/class/infiniband_verbs/uverbs*/dev; do + [[ -e "${sysfs_dev}" ]] || continue + ensure_char_node "/dev/infiniband/$(basename "$(dirname "${sysfs_dev}")")" "${sysfs_dev}" + done +} + +select_free_nbd() { + local index + local device + + modprobe nbd nbds_max="${NBD_MAX}" max_part=8 + udevadm settle --timeout=30 + if [[ "$(cat /sys/module/nbd/parameters/max_part)" == 0 ]]; then + fail "the nbd kernel driver was loaded without partition support" + fi + for index in $(seq 0 $((NBD_MAX - 1))); do + device="/dev/nbd${index}" + ensure_block_node "${device}" + if [[ "$(cat "/sys/class/block/nbd${index}/size")" == "0" ]]; then + printf '%s\n' "${device}" + return 0 + fi + done + fail "no free NBD device in the owned test range" +} + +partition_add() { + local label=$1 + local signature=$2 + local requested=${3:-auto} + local record + local device + local image + local partition + + validate_label "${label}" + validate_signature "${signature}" + mkdir -p "${STATE_DIR}" + record="${STATE_DIR}/partition-${label}.record" + image="${STATE_DIR}/partition-${label}.img" + + if [[ -f "${record}" ]]; then + device=$(cat "${record}") + validate_nbd_base "${device}" + partition="${device}p1" + if [[ -e "/sys/class/block/${partition##*/}" ]]; then + printf 'partition=%s\n' "${partition}" + return 0 + fi + fail "owned partition ${label} has stale state; run reset first" + fi + + if [[ "${requested}" == auto ]]; then + device=$(select_free_nbd) + else + device=${requested} + validate_nbd_base "${device}" + ensure_block_node "${device}" + [[ "$(cat "/sys/class/block/${device##*/}/size")" == "0" ]] || fail "${device} is already connected" + fi + + truncate --size 32M "${image}" + printf 'label: gpt\nsize=16M, type=linux, name="%s"\n' "${label}" | sfdisk "${image}" >/dev/null + if ! qemu-nbd --connect="${device}" --format=raw "${image}"; then + rm -f "${image}" + return 1 + fi + printf '%s\n' "${device}" > "${record}" + + partition="${device}p1" + if ! wait_for_path "/sys/class/block/${partition##*/}/dev"; then + blockdev --rereadpt "${device}" + fi + ensure_block_node "${partition}" + printf '%s\n' "${signature}" | dd of="${partition}" bs=64 count=1 conv=notrunc status=none + udevadm settle --timeout=30 + log "created ${partition} with PARTNAME=${label}" + printf 'partition=%s\n' "${partition}" +} + +partition_expose() { + local partition=$1 + local action=$2 + local name + local record + + validate_nbd_partition "${partition}" + name=${partition##*/} + record="${STATE_DIR}/exposure-${name}.record" + mkdir -p "${STATE_DIR}" + + case "${action}" in + add) + ensure_block_node "${partition}" + printf '%s\n' "${partition}" > "${record}" + udevadm settle --timeout=30 + ;; + remove) + [[ -f "${record}" ]] || return 0 + rm -f "${partition}" "${record}" + ;; + *) fail "partition expose action must be add or remove" ;; + esac +} + +partition_remove() { + local label=$1 + local record + local device + + validate_label "${label}" + record="${STATE_DIR}/partition-${label}.record" + [[ -f "${record}" ]] || return 0 + device=$(cat "${record}") + validate_nbd_base "${device}" + if [[ -e "/sys/class/block/${device##*/}" ]]; then + ensure_block_node "${device}" + qemu-nbd --disconnect "${device}" >/dev/null 2>&1 || true + fi + rm -f "${record}" "${STATE_DIR}/partition-${label}.img" + log "disconnected ${device} owned by ${label}" +} + +partition_path() { + local label=$1 + local record + local device + + validate_label "${label}" + record="${STATE_DIR}/partition-${label}.record" + [[ -f "${record}" ]] || fail "partition ${label} is not owned by this lab" + device=$(cat "${record}") + validate_nbd_base "${device}" + printf '%sp1\n' "${device}" +} + +partition_verify() { + local partition=$1 + local label=$2 + local signature=$3 + local name=${partition##*/} + + validate_nbd_partition "${partition}" + validate_label "${label}" + validate_signature "${signature}" + ensure_block_node "${partition}" + udevadm info --query=property --path="/sys/class/block/${name}" | grep -Fxq 'DEVTYPE=partition' + udevadm info --query=property --path="/sys/class/block/${name}" | grep -Fxq "PARTNAME=${label}" + dd if="${partition}" bs=64 count=1 status=none | grep -q "${signature}" +} + +net_add() { + local interface=$1 + local peer=$2 + local record + + validate_interface "${interface}" + validate_interface "${peer}" + mkdir -p "${STATE_DIR}" + record="${STATE_DIR}/net-${interface}.record" + [[ ! -f "${record}" ]] || fail "interface ${interface} is already owned by device-lab" + [[ ! -e "/sys/class/net/${interface}" ]] || fail "interface ${interface} already exists" + + ip link add "${interface}" type veth peer name "${peer}" + ip link set "${peer}" up + ip link set "${interface}" up + wait_for_path "/sys/class/net/${interface}/speed" + printf '%s\n' "${peer}" > "${record}" + udevadm settle --timeout=30 + printf 'speed=%s\n' "$(cat "/sys/class/net/${interface}/speed")" +} + +net_remove() { + local interface=$1 + local record + + validate_interface "${interface}" + record="${STATE_DIR}/net-${interface}.record" + [[ -f "${record}" ]] || return 0 + ip link delete "${interface}" >/dev/null 2>&1 || true + rm -f "${record}" + udevadm settle --timeout=30 || true +} + +select_rdma_driver() { + modprobe ib_uverbs >/dev/null 2>&1 || true + modprobe rdma_ucm >/dev/null 2>&1 || true + if [[ -d /sys/module/rdma_rxe ]] || modprobe rdma_rxe >/dev/null 2>&1; then + printf 'rxe\n' + return 0 + fi + if [[ -d /sys/module/siw ]] || modprobe siw >/dev/null 2>&1; then + printf 'siw\n' + return 0 + fi + fail "neither rdma_rxe nor siw is available in kernel $(uname -r)" +} + +rdma_add() { + local interface=$1 + local peer=$2 + local rdma_device=$3 + local requested_driver=${4:-auto} + local driver + local record + + validate_interface "${interface}" + validate_interface "${peer}" + validate_rdma_name "${rdma_device}" + record="${STATE_DIR}/rdma-${rdma_device}.record" + [[ ! -f "${record}" ]] || fail "RDMA device ${rdma_device} is already owned by device-lab" + + if [[ "${requested_driver}" == auto ]]; then + driver=$(select_rdma_driver) + else + driver=${requested_driver} + [[ "${driver}" == rxe || "${driver}" == siw ]] || fail "RDMA driver must be auto, rxe, or siw" + fi + net_add "${interface}" "${peer}" >/dev/null + if ! rdma link add "${rdma_device}" type "${driver}" netdev "${interface}"; then + net_remove "${interface}" + return 1 + fi + printf '%s\n' "${interface}" > "${record}" + wait_for_path "/sys/class/infiniband/${rdma_device}" + ensure_rdma_nodes + udevadm settle --timeout=30 + ibv_devices | grep -q "${rdma_device}" + log "created ${rdma_device} with ${driver} on ${interface}" + printf 'driver=%s\n' "${driver}" +} + +rdma_remove() { + local interface=$1 + local rdma_device=$2 + local record + + validate_interface "${interface}" + validate_rdma_name "${rdma_device}" + record="${STATE_DIR}/rdma-${rdma_device}.record" + [[ -f "${record}" ]] || return 0 + ip link set "${interface}" down >/dev/null 2>&1 || true + rdma link delete "${rdma_device}" >/dev/null 2>&1 || true + rm -f "${record}" + net_remove "${interface}" +} + +reset() { + local record + local rdma_device + local interface + local partition + local label + + mkdir -p "${STATE_DIR}" + for record in "${STATE_DIR}"/rdma-*.record; do + [[ -f "${record}" ]] || continue + rdma_device=${record##*/rdma-} + rdma_device=${rdma_device%.record} + interface=$(cat "${record}") + rdma_remove "${interface}" "${rdma_device}" || true + done + for record in "${STATE_DIR}"/net-*.record; do + [[ -f "${record}" ]] || continue + interface=${record##*/net-} + interface=${interface%.record} + net_remove "${interface}" || true + done + for record in "${STATE_DIR}"/exposure-*.record; do + [[ -f "${record}" ]] || continue + partition=$(cat "${record}") + partition_expose "${partition}" remove || true + done + for record in "${STATE_DIR}"/partition-*.record; do + [[ -f "${record}" ]] || continue + label=${record##*/partition-} + label=${label%.record} + partition_remove "${label}" || true + done + udevadm settle --timeout=30 || true + log "removed all devices owned by this lab" +} + +status() { + printf '%s\n' '--- owned state ---' + find "${STATE_DIR}" -maxdepth 1 -type f -name '*.record' -print -exec sh -c 'printf " "; cat "$1"' _ {} \; + printf '%s\n' '--- block devices ---' + lsblk -o NAME,TYPE,SIZE,PARTLABEL + printf '%s\n' '--- e2e network devices ---' + ip -details link show | grep -E '^[0-9]+: e2e' || true + printf '%s\n' '--- RDMA devices ---' + rdma link show || true + ibv_devices || true + ls -l /dev/infiniband 2>/dev/null || true +} + +case "${1:-}" in + partition) + case "${2:-}" in + add) partition_add "${3:-}" "${4:-}" "${5:-auto}" ;; + expose) partition_expose "${3:-}" "${4:-}" ;; + path) partition_path "${3:-}" ;; + remove) partition_remove "${3:-}" ;; + verify) partition_verify "${3:-}" "${4:-}" "${5:-}" ;; + *) fail "usage: device-lab partition {add LABEL SIGNATURE [auto|DEVICE]|expose DEVICE add|remove|path LABEL|remove LABEL|verify DEVICE LABEL SIGNATURE}" ;; + esac + ;; + net) + case "${2:-}" in + add) net_add "${3:-}" "${4:-}" ;; + remove) net_remove "${3:-}" ;; + *) fail "usage: device-lab net {add DEVICE PEER|remove DEVICE}" ;; + esac + ;; + rdma) + case "${2:-}" in + add) rdma_add "${3:-}" "${4:-}" "${5:-}" "${6:-auto}" ;; + remove) rdma_remove "${3:-}" "${4:-}" ;; + *) fail "usage: device-lab rdma {add DEVICE PEER RDMA_DEVICE [auto|rxe|siw]|remove DEVICE RDMA_DEVICE}" ;; + esac + ;; + reset) reset ;; + status) status ;; + *) + printf 'usage: %s {partition ...|net ...|rdma ...|reset|status}\n' "$0" >&2 + exit 2 + ;; +esac diff --git a/test/kind/device-lab.yaml b/test/kind/device-lab.yaml new file mode 100644 index 0000000..0ed2609 --- /dev/null +++ b/test/kind/device-lab.yaml @@ -0,0 +1,57 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: device-lab + namespace: udev-manager-e2e +spec: + selector: + matchLabels: + app: device-lab + template: + metadata: + labels: + app: device-lab + spec: + hostNetwork: true + tolerations: + - operator: Exists + containers: + - name: device-lab + image: udev-manager-device-lab:kind-e2e + imagePullPolicy: Never + command: [sleep, infinity] + securityContext: + privileged: true + volumeMounts: + - name: host-dev + mountPath: /dev + - name: host-sys + mountPath: /sys + - name: host-udev + mountPath: /run/udev + - name: host-modules + mountPath: /lib/modules + readOnly: true + - name: state + mountPath: /state + volumes: + - name: host-dev + hostPath: + path: /dev + type: Directory + - name: host-sys + hostPath: + path: /sys + type: Directory + - name: host-udev + hostPath: + path: /run/udev + type: DirectoryOrCreate + - name: host-modules + hostPath: + path: /lib/modules + type: Directory + - name: state + hostPath: + path: /var/lib/udev-manager-e2e + type: DirectoryOrCreate diff --git a/test/kind/e2e.sh b/test/kind/e2e.sh new file mode 100644 index 0000000..7c68eff --- /dev/null +++ b/test/kind/e2e.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail + +KIND_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO_ROOT=$(cd "${KIND_DIR}/../.." && pwd) +export KIND_CLUSTER_NAME=${KIND_CLUSTER_NAME:-udev-manager-e2e-$$} + +# shellcheck source=kind.sh +source "${KIND_DIR}/kind.sh" + +previous_context=$(kubectl config current-context 2>/dev/null || true) +cluster_owned=0 + +restore_context() { + if [[ -n "${previous_context}" ]]; then + kubectl config use-context "${previous_context}" >/dev/null 2>&1 || true + else + kubectl config unset current-context >/dev/null 2>&1 || true + fi +} + +cleanup() { + local status=$? + trap - EXIT + + if [[ ${status} -ne 0 && "${cluster_owned}" == 1 ]] && cluster_exists; then + echo "E2E failed; collecting diagnostics" >&2 + collect_logs + fi + + if [[ "${cluster_owned}" == 1 && "${KEEP_E2E_CLUSTER:-0}" != 1 ]]; then + if cluster_exists; then + if kubectl --context "${KIND_CONTEXT}" get namespace "${NAMESPACE}" >/dev/null 2>&1; then + reset_all_devices || true + fi + kind delete cluster --name "${KIND_CLUSTER_NAME}" || true + fi + elif [[ "${cluster_owned}" == 1 ]]; then + echo "Keeping cluster ${KIND_CLUSTER_NAME}; inspect it with kubectl --context ${KIND_CONTEXT}" + fi + restore_context + exit "${status}" +} +trap cleanup EXIT + +preflight +require_command go +if cluster_exists; then + echo "refusing to reuse existing E2E cluster ${KIND_CLUSTER_NAME}" >&2 + exit 1 +fi +cluster_owned=1 +ensure_cluster +deploy 0 + +mkdir -p "${ARTIFACT_ROOT}/${KIND_CLUSTER_NAME}" +export E2E_CONTEXT=${KIND_CONTEXT} +export E2E_NAMESPACE=${NAMESPACE} +export E2E_DEVICE_LAB_IMAGE=${DEVICE_LAB_IMAGE} + +( + ginkgo_args=(-ginkgo.v "-ginkgo.junit-report=${ARTIFACT_ROOT}/${KIND_CLUSTER_NAME}/junit.xml") + if [[ -n "${E2E_FOCUS:-}" ]]; then + ginkgo_args+=("-ginkgo.focus=${E2E_FOCUS}") + fi + cd "${REPO_ROOT}/test/e2e" + go test -v . -count=1 "${ginkgo_args[@]}" +) + +echo "Kind E2E passed with real kernel devices on $(uname -s)/$(uname -m)" diff --git a/test/kind/kind.sh b/test/kind/kind.sh new file mode 100644 index 0000000..610696a --- /dev/null +++ b/test/kind/kind.sh @@ -0,0 +1,365 @@ +#!/usr/bin/env bash +set -euo pipefail + +KIND_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO_ROOT=$(cd "${KIND_DIR}/../.." && pwd) +NAMESPACE=${E2E_NAMESPACE:-udev-manager-e2e} +UDEV_MANAGER_IMAGE=${UDEV_MANAGER_IMAGE:-udev-manager:kind-e2e} +DEVICE_LAB_IMAGE=${DEVICE_LAB_IMAGE:-udev-manager-device-lab:kind-e2e} +KIND_CLUSTER_NAME=${KIND_CLUSTER_NAME:-udev-manager-dev} +KIND_CONTEXT=kind-${KIND_CLUSTER_NAME} +ARTIFACT_ROOT=${ARTIFACT_ROOT:-${REPO_ROOT}/_artifacts/kind} + +require_command() { + command -v "$1" >/dev/null 2>&1 || { + echo "required command not found: $1" >&2 + return 1 + } +} + +configure_platform() { + case "$(uname -s)" in + Darwin) + require_command orbctl + if [[ "$(orbctl status)" != Running ]]; then + orbctl start + fi + export DOCKER_CONTEXT=${DOCKER_CONTEXT:-orbstack} + ;; + Linux) ;; # Do nothing! + *) + echo "unsupported host OS: $(uname -s)" >&2 + return 1 + ;; + esac +} + +preflight() { + configure_platform + require_command docker + require_command kind + require_command kubectl + docker info >/dev/null + mkdir -p "${ARTIFACT_ROOT}" +} + +cluster_exists() { + local cluster + while IFS= read -r cluster; do + [[ "${cluster}" == "${KIND_CLUSTER_NAME}" ]] && return 0 + done < <(kind get clusters 2>/dev/null) + return 1 +} + +ensure_cluster() { + if ! cluster_exists; then + kind create cluster \ + --name "${KIND_CLUSTER_NAME}" \ + --config "${KIND_DIR}/cluster.yaml" \ + --wait 180s + else + # Always merge its context into the user's active kubeconfig. + kind export kubeconfig --name "${KIND_CLUSTER_NAME}" + fi + + validate_cluster_topology +} + +validate_cluster_topology() { + local control_planes + local workers + + control_planes=$(kubectl --context "${KIND_CONTEXT}" get nodes \ + --selector='node-role.kubernetes.io/control-plane' -o name | awk 'NF { count++ } END { print count + 0 }') + workers=$(kubectl --context "${KIND_CONTEXT}" get nodes \ + --selector='!node-role.kubernetes.io/control-plane,!node-role.kubernetes.io/master' \ + -o name | awk 'NF { count++ } END { print count + 0 }') + if [[ "${control_planes}" != 1 || "${workers}" != 2 ]]; then + echo "cluster ${KIND_CLUSTER_NAME} has ${control_planes} control-plane and ${workers} worker nodes; expected 1 and 2" >&2 + echo "delete the incompatible development cluster with 'make kind-down' and run 'make kind-up' again" >&2 + return 1 + fi +} + +apply_config() { + kubectl --context "${KIND_CONTEXT}" create namespace "${NAMESPACE}" \ + --dry-run=client -o yaml | kubectl --context "${KIND_CONTEXT}" apply -f - + + kubectl --context "${KIND_CONTEXT}" create configmap udev-manager-config \ + --namespace "${NAMESPACE}" \ + --from-file=config.yaml="${KIND_DIR}/app-config.yaml" \ + --dry-run=client -o yaml | kubectl --context "${KIND_CONTEXT}" apply -f - +} + +apply_manifest() { + local manifest=$1 + sed \ + -e "s|image: udev-manager:kind-e2e|image: ${UDEV_MANAGER_IMAGE}|g" \ + -e "s|image: udev-manager-device-lab:kind-e2e|image: ${DEVICE_LAB_IMAGE}|g" \ + "${manifest}" | kubectl --context "${KIND_CONTEXT}" apply -f - +} + +build_images() { + docker build -f "${REPO_ROOT}/udev-manager.Dockerfile" \ + --build-arg GOARCH= -t "${UDEV_MANAGER_IMAGE}" "${REPO_ROOT}" + docker build -f "${KIND_DIR}/device-lab.Dockerfile" \ + -t "${DEVICE_LAB_IMAGE}" "${REPO_ROOT}" + + kind load docker-image "${UDEV_MANAGER_IMAGE}" "${DEVICE_LAB_IMAGE}" \ + --name "${KIND_CLUSTER_NAME}" +} + +all_nodes() { + kubectl --context "${KIND_CONTEXT}" get nodes \ + -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | sort +} + +worker_nodes() { + kubectl --context "${KIND_CONTEXT}" get nodes \ + --selector='!node-role.kubernetes.io/control-plane,!node-role.kubernetes.io/master' \ + -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' | sort +} + +first_worker() { + local node + node=$(worker_nodes | head -n 1) + [[ -n "${node}" ]] || { + echo "the device lab requires at least one worker node" >&2 + return 1 + } + printf '%s\n' "${node}" +} + +device_lab_pod() { + local node=$1 + kubectl --context "${KIND_CONTEXT}" get pod --namespace "${NAMESPACE}" \ + --selector app=device-lab --field-selector "spec.nodeName=${node}" \ + -o jsonpath='{.items[0].metadata.name}' +} + +run_device_lab() { + local node=$1 + shift + local pod + pod=$(device_lab_pod "${node}") + [[ -n "${pod}" ]] || { + echo "device-lab pod not found on ${node}" >&2 + return 1 + } + kubectl --context "${KIND_CONTEXT}" exec --namespace "${NAMESPACE}" \ + "${pod}" --container device-lab -- /usr/local/bin/device-lab "$@" +} + +reset_all_devices() { + local node + while IFS= read -r node; do + run_device_lab "${node}" reset + done < <(all_nodes) +} + +restart_manager_on_node() { + local node=$1 + local pod + pod=$(kubectl --context "${KIND_CONTEXT}" get pod --namespace "${NAMESPACE}" \ + --selector app=udev-manager --field-selector "spec.nodeName=${node}" \ + -o jsonpath='{.items[0].metadata.name}') + kubectl --context "${KIND_CONTEXT}" delete pod "${pod}" --namespace "${NAMESPACE}" --wait=true + kubectl --context "${KIND_CONTEXT}" rollout status daemonset/udev-manager \ + --namespace "${NAMESPACE}" --timeout=180s +} + +add_shared_partition() { + local label=$1 + local signature=$2 + local owner + local output + local partition + local node + + owner=$(first_worker) + output=$(run_device_lab "${owner}" partition add "${label}" "${signature}" auto) + partition=$(sed -n 's/^partition=//p' <<< "${output}" | tail -n 1) + [[ -n "${partition}" ]] || { + echo "device-lab did not report the created partition" >&2 + return 1 + } + while IFS= read -r node; do + run_device_lab "${node}" partition expose "${partition}" add + done < <(all_nodes) + printf '%s\n' "${partition}" +} + +remove_shared_partition() { + local label=$1 + local owner + local partition + local node + + owner=$(first_worker) + partition=$(run_device_lab "${owner}" partition path "${label}") + while IFS= read -r node; do + run_device_lab "${node}" partition expose "${partition}" remove + done < <(all_nodes) + run_device_lab "${owner}" partition remove "${label}" +} + +seed_devices() { + local first + local second + + first=$(worker_nodes | sed -n '1p') + second=$(worker_nodes | sed -n '2p') + if [[ -z "${first}" || -z "${second}" ]]; then + echo "seeding requires two worker nodes" >&2 + return 1 + fi + + reset_all_devices + add_shared_partition e2e_disk-one UDEV_MANAGER_E2E_ONE >/dev/null + add_shared_partition e2e_batch_a UDEV_MANAGER_E2E_BATCH_A >/dev/null + add_shared_partition e2e_batch_b UDEV_MANAGER_E2E_BATCH_B >/dev/null + + run_device_lab "${first}" net add e2ebw-uplink e2ebw-peer + run_device_lab "${first}" rdma add e2erdma-any e2eany-peer rxe_e2eany auto + run_device_lab "${second}" net add e2enonrdma e2enon-peer + run_device_lab "${second}" rdma add e2erdma-pf e2epf-peer rxe_e2epf auto + run_device_lab "${second}" rdma add e2erdma-vf e2evf-peer rxe_e2evf auto +} + +deploy() { + local seed=${1:-0} + + build_images + apply_config + + apply_manifest "${KIND_DIR}/udevd.yaml" + kubectl --context "${KIND_CONTEXT}" rollout restart daemonset/udevd \ + --namespace "${NAMESPACE}" + kubectl --context "${KIND_CONTEXT}" rollout status daemonset/udevd \ + --namespace "${NAMESPACE}" --timeout=180s + + apply_manifest "${KIND_DIR}/device-lab.yaml" + kubectl --context "${KIND_CONTEXT}" rollout restart daemonset/device-lab \ + --namespace "${NAMESPACE}" + kubectl --context "${KIND_CONTEXT}" rollout status daemonset/device-lab \ + --namespace "${NAMESPACE}" --timeout=180s + reset_all_devices + if [[ "${seed}" == 1 ]]; then + seed_devices + fi + + apply_manifest "${KIND_DIR}/daemonset.yaml" + kubectl --context "${KIND_CONTEXT}" rollout restart daemonset/udev-manager \ + --namespace "${NAMESPACE}" + kubectl --context "${KIND_CONTEXT}" rollout status daemonset/udev-manager \ + --namespace "${NAMESPACE}" --timeout=180s +} + +up() { + preflight + ensure_cluster + deploy 1 + echo + echo "Kind cluster ${KIND_CLUSTER_NAME} is ready with real kernel devices." + echo "Context: ${KIND_CONTEXT} (stored in the active kubeconfig)" + echo "Inspect: kubectl --context ${KIND_CONTEXT} get nodes" + echo "Devices: make kind-device ACTION=status" + echo "Delete: make kind-down" +} + +down() { + configure_platform + require_command kind + require_command kubectl + if cluster_exists; then + if kubectl --context "${KIND_CONTEXT}" get namespace "${NAMESPACE}" >/dev/null 2>&1; then + reset_all_devices || true + fi + kind delete cluster --name "${KIND_CLUSTER_NAME}" + fi +} + +device() { + local action=${1:-} + local requested_node=${2:-} + local label=${3:-} + local signature=${4:-} + local device_name=${5:-} + local peer=${6:-} + local rdma_device=${7:-} + local node + + preflight + node=${requested_node:-$(first_worker)} + case "${action}" in + seed) seed_devices ;; + reset) reset_all_devices ;; + status) + if [[ -n "${requested_node}" ]]; then + run_device_lab "${node}" status + else + while IFS= read -r node; do + echo "=== ${node} ===" + run_device_lab "${node}" status + done < <(all_nodes) + fi + ;; + add-partition) add_shared_partition "${label}" "${signature}" ;; + remove-partition) remove_shared_partition "${label}" ;; + add-veth) run_device_lab "${node}" net add "${device_name}" "${peer}" ;; + remove-network) run_device_lab "${node}" net remove "${device_name}" ;; + add-rdma) + run_device_lab "${node}" rdma add "${device_name}" "${peer}" "${rdma_device}" auto + restart_manager_on_node "${node}" + ;; + remove-rdma) + run_device_lab "${node}" rdma remove "${device_name}" "${rdma_device}" + restart_manager_on_node "${node}" + ;; + *) + echo "ACTION must be seed, reset, status, add-partition, remove-partition, add-veth, remove-network, add-rdma, or remove-rdma" >&2 + return 2 + ;; + esac +} + +collect_logs() { + local destination=${1:-${ARTIFACT_ROOT}/${KIND_CLUSTER_NAME}} + local node + + mkdir -p "${destination}" + kind export logs "${destination}" --name "${KIND_CLUSTER_NAME}" || true + kubectl --context "${KIND_CONTEXT}" get all --all-namespaces -o wide \ + > "${destination}/kubernetes-resources.txt" 2>&1 || true + kubectl --context "${KIND_CONTEXT}" describe nodes \ + > "${destination}/nodes.txt" 2>&1 || true + kubectl --context "${KIND_CONTEXT}" logs --selector app=udev-manager --namespace "${NAMESPACE}" \ + --all-containers --prefix --tail=-1 > "${destination}/udev-manager.log" 2>&1 || true + kubectl --context "${KIND_CONTEXT}" logs --selector app=udevd --namespace "${NAMESPACE}" \ + --all-containers --prefix --tail=-1 > "${destination}/udevd.log" 2>&1 || true + + while IFS= read -r node; do + docker exec "${node}" /bin/sh -ec ' + udevadm info --export-db + ip -details link show + rdma link show 2>/dev/null || true + lsblk -o NAME,TYPE,SIZE,PARTLABEL + ls -l /dev/infiniband 2>/dev/null || true + find /var/lib/udev-manager-e2e -maxdepth 1 -type f -print -exec cat {} \; 2>/dev/null || true + ' > "${destination}/device-state-${node}.txt" 2>&1 || true + run_device_lab "${node}" status > "${destination}/device-lab-${node}.txt" 2>&1 || true + done < <(kind get nodes --name "${KIND_CLUSTER_NAME}") +} + +main() { + case "${1:-}" in + up) up ;; + down) down ;; + device) shift; device "$@" ;; + *) echo "usage: $0 {up|down|device ACTION [NODE ...]}" >&2; return 2 ;; + esac +} + +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + main "$@" +fi diff --git a/test/kind/udevd.yaml b/test/kind/udevd.yaml new file mode 100644 index 0000000..1a58021 --- /dev/null +++ b/test/kind/udevd.yaml @@ -0,0 +1,55 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: udevd + namespace: udev-manager-e2e +spec: + selector: + matchLabels: + app: udevd + template: + metadata: + labels: + app: udevd + spec: + hostNetwork: true + tolerations: + - operator: Exists + containers: + - name: udevd + image: udev-manager-device-lab:kind-e2e + imagePullPolicy: Never + command: + - /bin/sh + - -ec + args: + - rm -f /run/udev/control; exec /lib/systemd/systemd-udevd --resolve-names=never + securityContext: + privileged: true + readinessProbe: + exec: + command: + - udevadm + - control + - --ping + periodSeconds: 1 + volumeMounts: + - name: host-dev + mountPath: /dev + - name: host-sys + mountPath: /sys + - name: host-udev + mountPath: /run/udev + volumes: + - name: host-dev + hostPath: + path: /dev + type: Directory + - name: host-sys + hostPath: + path: /sys + type: Directory + - name: host-udev + hostPath: + path: /run/udev + type: DirectoryOrCreate diff --git a/udev-manager.Dockerfile b/udev-manager.Dockerfile index 0a80638..dc44a2a 100644 --- a/udev-manager.Dockerfile +++ b/udev-manager.Dockerfile @@ -3,8 +3,12 @@ FROM golang:1.24-bookworm as build WORKDIR /go/app COPY . /go/app -RUN apt update && apt install -y libudev-dev -RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o udev-manager cmd/udev-manager/main.go +ARG GOARCH=amd64 + +RUN apt-get update && \ + apt-get install -y --no-install-recommends libudev-dev && \ + rm -rf /var/lib/apt/lists/* +RUN CGO_ENABLED=1 GOOS=linux GOARCH=${GOARCH} go build -o udev-manager ./cmd/udev-manager FROM debian:bookworm